From eb5ac239889ea4a65bbc316aa6f51b06a34c2cab Mon Sep 17 00:00:00 2001 From: yuyi Date: Sun, 23 May 2021 22:59:57 +0800 Subject: [PATCH] checker: fix match expr with if expr (fix #10177 #10178) (#10179) --- vlib/v/checker/checker.v | 3 ++ vlib/v/checker/tests/if_match_expr.out | 7 +++ vlib/v/gen/c/cgen.v | 1 + .../match_expr_with_if_or_match_expr_test.v | 43 +++++++++++++++++++ 4 files changed, 54 insertions(+) create mode 100644 vlib/v/tests/match_expr_with_if_or_match_expr_test.v diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 23246c6f97..f0fe606a3a 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -5326,6 +5326,9 @@ pub fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type { mut stmt := branch.stmts[branch.stmts.len - 1] match mut stmt { ast.ExprStmt { + if node.is_expr { + c.expected_type = node.expected_type + } expr_type := c.expr(stmt.expr) if ret_type == ast.void_type { ret_type = expr_type diff --git a/vlib/v/checker/tests/if_match_expr.out b/vlib/v/checker/tests/if_match_expr.out index 81c13a7f69..9c6597646b 100644 --- a/vlib/v/checker/tests/if_match_expr.out +++ b/vlib/v/checker/tests/if_match_expr.out @@ -40,3 +40,10 @@ vlib/v/checker/tests/if_match_expr.vv:23:3: error: `match` expression branch has | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 24 | _ = match true {true {1} else {-1}} // OK 25 | match true {true {1} else {-1}} // result +vlib/v/checker/tests/if_match_expr.vv:25:3: error: return type mismatch, it should be `int` + 23 | match true {true {} else {}} // statement not expression + 24 | _ = match true {true {1} else {-1}} // OK + 25 | match true {true {1} else {-1}} // result + | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + 26 | } + 27 | } diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 762e03a98a..5921517bfa 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -1018,6 +1018,7 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) { g.skip_stmt_pos = true g.write('$tmp_var = ') g.stmt(stmt) + g.writeln(';') } } else { g.stmt(stmt) diff --git a/vlib/v/tests/match_expr_with_if_or_match_expr_test.v b/vlib/v/tests/match_expr_with_if_or_match_expr_test.v new file mode 100644 index 0000000000..891f198079 --- /dev/null +++ b/vlib/v/tests/match_expr_with_if_or_match_expr_test.v @@ -0,0 +1,43 @@ +fn foo1() int { + return match 1 { + 1 { + if true { + 1 + } else { + 2 + } + } + else { + if true { + 3 + } else { + 4 + } + } + } +} + +fn foo2() int { + return match 1 { + 1 { + match true { + true { 1 } + false { 2 } + } + } + else { + match false { + true { 3 } + false { 4 } + } + } + } +} + +fn test_match_expr_with_if_or_match_expr() { + println(foo1()) + assert foo1() == 1 + + println(foo2()) + assert foo2() == 1 +}