diff --git a/vlib/v/parser/if_match.v b/vlib/v/parser/if_match.v index 9a5b579129..d1e0bac9e6 100644 --- a/vlib/v/parser/if_match.v +++ b/vlib/v/parser/if_match.v @@ -87,6 +87,9 @@ fn (mut p Parser) if_expr(is_comptime bool) ast.IfExpr { is_guard = true var_pos := p.tok.position() var_name := p.check_name() + if p.scope.known_var(var_name) { + p.error_with_pos('redefinition of `$var_name`', var_pos) + } comments << p.eat_comments({}) p.check(.decl_assign) comments << p.eat_comments({}) diff --git a/vlib/v/parser/tests/if_guard_redefinition.out b/vlib/v/parser/tests/if_guard_redefinition.out new file mode 100644 index 0000000000..7f2a5b2392 --- /dev/null +++ b/vlib/v/parser/tests/if_guard_redefinition.out @@ -0,0 +1,7 @@ +vlib/v/parser/tests/if_guard_redefinition.vv:7:8: error: redefinition of `x` + 5 | fn main() { + 6 | x := 1 + 7 | if x := opt_fn() { + | ^ + 8 | println(x) + 9 | } diff --git a/vlib/v/parser/tests/if_guard_redefinition.vv b/vlib/v/parser/tests/if_guard_redefinition.vv new file mode 100644 index 0000000000..b54ee90a15 --- /dev/null +++ b/vlib/v/parser/tests/if_guard_redefinition.vv @@ -0,0 +1,10 @@ +fn opt_fn() ?int { + return 2 +} + +fn main() { + x := 1 + if x := opt_fn() { + println(x) + } +}