From c64c4907a2b8785115c2f7be2fd1ef3b946a4f9d Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 22 Jun 2022 14:04:15 +0800 Subject: [PATCH] parser: check closure var name conflict (#14823) --- vlib/v/parser/fn.v | 11 +++++++++++ vlib/v/parser/tests/closure_var_name_conflict.out | 7 +++++++ vlib/v/parser/tests/closure_var_name_conflict.vv | 10 ++++++++++ 3 files changed, 28 insertions(+) create mode 100644 vlib/v/parser/tests/closure_var_name_conflict.out create mode 100644 vlib/v/parser/tests/closure_var_name_conflict.vv diff --git a/vlib/v/parser/fn.v b/vlib/v/parser/fn.v index 8bf0b45039..d9f21e0753 100644 --- a/vlib/v/parser/fn.v +++ b/vlib/v/parser/fn.v @@ -751,6 +751,17 @@ fn (mut p Parser) anon_fn() ast.AnonFn { typ := ast.new_type(idx) p.inside_defer = old_inside_defer // name := p.table.get_type_name(typ) + if inherited_vars.len > 0 && args.len > 0 { + for arg in args { + for var in inherited_vars { + if arg.name == var.name { + p.error_with_pos('the parameter name `$arg.name` conflicts with the captured value name', + arg.pos) + break + } + } + } + } return ast.AnonFn{ decl: ast.FnDecl{ name: name diff --git a/vlib/v/parser/tests/closure_var_name_conflict.out b/vlib/v/parser/tests/closure_var_name_conflict.out new file mode 100644 index 0000000000..333a0ccb8d --- /dev/null +++ b/vlib/v/parser/tests/closure_var_name_conflict.out @@ -0,0 +1,7 @@ +vlib/v/parser/tests/closure_var_name_conflict.vv:4:15: error: the parameter name `x` conflicts with the captured value name + 2 | x := 1 + 3 | + 4 | y := fn [x] (x int) { + | ^ + 5 | println(x) + 6 | } diff --git a/vlib/v/parser/tests/closure_var_name_conflict.vv b/vlib/v/parser/tests/closure_var_name_conflict.vv new file mode 100644 index 0000000000..02cd7bbcd0 --- /dev/null +++ b/vlib/v/parser/tests/closure_var_name_conflict.vv @@ -0,0 +1,10 @@ +fn main() { + x := 1 + + y := fn [x] (x int) { + println(x) + } + + y(x) + y(2) +}