diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index c2ce720b05..a65b8a2257 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -3440,6 +3440,18 @@ fn (mut c Checker) ident(mut node ast.Ident) ast.Type { c.error(util.new_suggestion(node.name, const_names_in_mod).say('undefined ident: `${node.name}`'), node.pos) } else { + // If a variable is not found in the scope of an anonymous function + // but is in an external scope, then we can suggest the user add it to the capturing list. + if c.inside_anon_fn { + found_var := c.fn_scope.find_var(node.name) + + if found_var != none { + c.error('`${node.name}` must be added to the capture list for the closure to be used inside', + node.pos) + return ast.void_type + } + } + c.error('undefined ident: `${node.name}`', node.pos) } } diff --git a/vlib/v/checker/tests/anon_fn_arg_type_err.out b/vlib/v/checker/tests/anon_fn_arg_type_err.out index a45921cad9..af0fb10383 100644 --- a/vlib/v/checker/tests/anon_fn_arg_type_err.out +++ b/vlib/v/checker/tests/anon_fn_arg_type_err.out @@ -1,12 +1,12 @@ vlib/v/checker/tests/anon_fn_arg_type_err.vv:6:14: error: use `_` to name an unused parameter 4 | mut i := 1 - 5 | + 5 | 6 | func := fn (i) int { | ^ 7 | return i 8 | } -vlib/v/checker/tests/anon_fn_arg_type_err.vv:7:10: error: undefined ident: `i` - 5 | +vlib/v/checker/tests/anon_fn_arg_type_err.vv:7:10: error: `i` must be added to the capture list for the closure to be used inside + 5 | 6 | func := fn (i) int { 7 | return i | ^ @@ -14,7 +14,7 @@ vlib/v/checker/tests/anon_fn_arg_type_err.vv:7:10: error: undefined ident: `i` 9 | vlib/v/checker/tests/anon_fn_arg_type_err.vv:10:15: error: cannot use `int` as `i` in argument 1 to `func` 8 | } - 9 | + 9 | 10 | println(func(i) == 1) | ^ 11 | } diff --git a/vlib/v/parser/tests/closure_not_declared.out b/vlib/v/parser/tests/closure_not_declared.out index a90ceacf06..093797970c 100644 --- a/vlib/v/parser/tests/closure_not_declared.out +++ b/vlib/v/parser/tests/closure_not_declared.out @@ -1,4 +1,4 @@ -vlib/v/parser/tests/closure_not_declared.vv:4:9: error: undefined ident: `a` +vlib/v/parser/tests/closure_not_declared.vv:4:9: error: `a` must be added to the capture list for the closure to be used inside 2 | a := 1 3 | f := fn () { 4 | print(a)