mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
parser: check closure capture global variable (#15010)
This commit is contained in:
parent
3549055548
commit
58c5d387c4
@ -103,6 +103,11 @@ pub fn (s &Scope) known_var(name string) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn (s &Scope) known_global(name string) bool {
|
||||||
|
s.find_global(name) or { return false }
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
pub fn (s &Scope) known_const(name string) bool {
|
pub fn (s &Scope) known_const(name string) bool {
|
||||||
s.find_const(name) or { return false }
|
s.find_const(name) or { return false }
|
||||||
return true
|
return true
|
||||||
|
@ -0,0 +1,7 @@
|
|||||||
|
vlib/v/checker/tests/globals/closure_capture_global_var.vv:12:12: error: no need to capture global variable `number` in closure
|
||||||
|
10 |
|
||||||
|
11 | fn main() {
|
||||||
|
12 | f1 := fn [number] () {
|
||||||
|
| ~~~~~~
|
||||||
|
13 | println(number)
|
||||||
|
14 | }
|
16
vlib/v/checker/tests/globals/closure_capture_global_var.vv
Normal file
16
vlib/v/checker/tests/globals/closure_capture_global_var.vv
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
module main
|
||||||
|
|
||||||
|
__global (
|
||||||
|
number int
|
||||||
|
)
|
||||||
|
|
||||||
|
fn init() {
|
||||||
|
number = 123
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
f1 := fn [number] () {
|
||||||
|
println(number)
|
||||||
|
}
|
||||||
|
f1()
|
||||||
|
}
|
@ -1031,6 +1031,11 @@ fn (mut p Parser) closure_vars() []ast.Param {
|
|||||||
p.check(.name)
|
p.check(.name)
|
||||||
var_name := p.prev_tok.lit
|
var_name := p.prev_tok.lit
|
||||||
mut var := p.scope.parent.find_var(var_name) or {
|
mut var := p.scope.parent.find_var(var_name) or {
|
||||||
|
if p.table.global_scope.known_global(var_name) {
|
||||||
|
p.error_with_pos('no need to capture global variable `$var_name` in closure',
|
||||||
|
p.prev_tok.pos())
|
||||||
|
continue
|
||||||
|
}
|
||||||
p.error_with_pos('undefined ident: `$var_name`', p.prev_tok.pos())
|
p.error_with_pos('undefined ident: `$var_name`', p.prev_tok.pos())
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user