From 34961a23b4fb8b23fea206d06c61a9026b3de835 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Thu, 21 Apr 2022 13:15:21 +0300 Subject: [PATCH] ast: allow `a := match x { 101 { ... for {...} ... y }` --- vlib/v/ast/ast.v | 3 + vlib/v/checker/tests/if_match_expr.out | 7 --- .../match_expression_with_for_loop_test.v | 58 +++++++++++++++++++ 3 files changed, 61 insertions(+), 7 deletions(-) create mode 100644 vlib/v/tests/match_expression_with_for_loop_test.v diff --git a/vlib/v/ast/ast.v b/vlib/v/ast/ast.v index 06e898bb50..bce6e6d7f4 100644 --- a/vlib/v/ast/ast.v +++ b/vlib/v/ast/ast.v @@ -1821,6 +1821,9 @@ pub fn (stmt Stmt) check_c_expr() ? { AssignStmt { return } + ForCStmt, ForInStmt, ForStmt { + return + } ExprStmt { if stmt.expr.is_expr() { return diff --git a/vlib/v/checker/tests/if_match_expr.out b/vlib/v/checker/tests/if_match_expr.out index 81c13a7f69..bb4dc85293 100644 --- a/vlib/v/checker/tests/if_match_expr.out +++ b/vlib/v/checker/tests/if_match_expr.out @@ -1,10 +1,3 @@ -vlib/v/checker/tests/if_match_expr.vv:8:6: error: `if` expression branch has unsupported statement (`v.ast.ForStmt`) - 6 | if true {1} else {-1} // result - 7 | } else { - 8 | for {break} - | ^ - 9 | {} - 10 | match true {true {} else {}} // statement not expression vlib/v/checker/tests/if_match_expr.vv:9:2: error: `if` expression branch has unsupported statement (`v.ast.Block`) 7 | } else { 8 | for {break} diff --git a/vlib/v/tests/match_expression_with_for_loop_test.v b/vlib/v/tests/match_expression_with_for_loop_test.v new file mode 100644 index 0000000000..c86ea6ae22 --- /dev/null +++ b/vlib/v/tests/match_expression_with_for_loop_test.v @@ -0,0 +1,58 @@ +fn test_match_with_for_in_loop() { + a := 101 + b := match a { + 101 { + mut aa := []int{} + for i in 0 .. 3 { + aa << i + } + aa + } + else { + [0] + } + } + println(b) + assert b == [0, 1, 2] +} + +fn test_match_with_for_c_loop() { + a := 101 + b := match a { + 101 { + mut aa := []int{} + for i := 0; i < 3; i++ { + aa << i + } + aa + } + else { + [0] + } + } + println(b) + assert b == [0, 1, 2] +} + +fn test_match_with_for_loop() { + a := 101 + b := match a { + 101 { + mut aa := []int{} + mut i := 0 + for { + aa << i + i++ + if i == 3 { + break + } + } + aa + } + else { + [0] + } + } + println(b) + assert b == [0, 1, 2] +}