From 6365d9e070be37c1b26b348fd9ada605359dfd7b Mon Sep 17 00:00:00 2001 From: Makhnev Petr <51853996+i582@users.noreply.github.com> Date: Thu, 26 Jan 2023 19:40:10 +0400 Subject: [PATCH] checker: forbid var declaration in post statement of for loop (#17120) --- vlib/v/checker/for.v | 8 +++++++- .../for_c_stmt_with_var_declaration_in_post_stmt.out | 5 +++++ .../tests/for_c_stmt_with_var_declaration_in_post_stmt.vv | 3 +++ 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 vlib/v/checker/tests/for_c_stmt_with_var_declaration_in_post_stmt.out create mode 100644 vlib/v/checker/tests/for_c_stmt_with_var_declaration_in_post_stmt.vv diff --git a/vlib/v/checker/for.v b/vlib/v/checker/for.v index c8cf84d930..b5c9bf47ce 100644 --- a/vlib/v/checker/for.v +++ b/vlib/v/checker/for.v @@ -14,7 +14,13 @@ fn (mut c Checker) for_c_stmt(node ast.ForCStmt) { c.expr(node.cond) if node.has_inc { if node.inc is ast.AssignStmt { - for right in node.inc.right { + assign := node.inc + + if assign.op == .decl_assign { + c.error('for loop post statement cannot be a variable declaration', assign.pos) + } + + for right in assign.right { if right is ast.CallExpr { if right.or_block.stmts.len > 0 { c.error('options are not allowed in `for statement increment` (yet)', diff --git a/vlib/v/checker/tests/for_c_stmt_with_var_declaration_in_post_stmt.out b/vlib/v/checker/tests/for_c_stmt_with_var_declaration_in_post_stmt.out new file mode 100644 index 0000000000..32cccdf389 --- /dev/null +++ b/vlib/v/checker/tests/for_c_stmt_with_var_declaration_in_post_stmt.out @@ -0,0 +1,5 @@ +vlib/v/checker/tests/for_c_stmt_with_var_declaration_in_post_stmt.vv:1:26: error: for loop post statement cannot be a variable declaration + 1 | for i := 100; i < 200; j := 100 { + | ~~ + 2 | println(j) + 3 | } \ No newline at end of file diff --git a/vlib/v/checker/tests/for_c_stmt_with_var_declaration_in_post_stmt.vv b/vlib/v/checker/tests/for_c_stmt_with_var_declaration_in_post_stmt.vv new file mode 100644 index 0000000000..07706ee122 --- /dev/null +++ b/vlib/v/checker/tests/for_c_stmt_with_var_declaration_in_post_stmt.vv @@ -0,0 +1,3 @@ +for i := 100; i < 200; j := 100 { + println(j) +}