1
0
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:
yuyi 2022-07-11 01:21:54 +08:00 committed by GitHub
parent 3549055548
commit 58c5d387c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 33 additions and 0 deletions

View File

@ -103,6 +103,11 @@ pub fn (s &Scope) known_var(name string) bool {
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 {
s.find_const(name) or { return false }
return true

View File

@ -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 | }

View File

@ -0,0 +1,16 @@
module main
__global (
number int
)
fn init() {
number = 123
}
fn main() {
f1 := fn [number] () {
println(number)
}
f1()
}

View File

@ -1031,6 +1031,11 @@ fn (mut p Parser) closure_vars() []ast.Param {
p.check(.name)
var_name := p.prev_tok.lit
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())
continue
}