From 8521e227b43c73e2ce13c6f286aab79c051f076e Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 17 Aug 2021 02:48:58 +0800 Subject: [PATCH] cgen: fix if expr of multi stmts (#11208) --- vlib/v/gen/c/assert.v | 2 +- vlib/v/gen/c/cgen.v | 2 +- vlib/v/gen/c/infix_expr.v | 4 ++++ vlib/v/tests/if_expr_of_multi_stmts_test.v | 15 +++++++++++++++ 4 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/if_expr_of_multi_stmts_test.v diff --git a/vlib/v/gen/c/assert.v b/vlib/v/gen/c/assert.v index fa6f74a393..5390d73bfe 100644 --- a/vlib/v/gen/c/assert.v +++ b/vlib/v/gen/c/assert.v @@ -104,7 +104,7 @@ fn (mut g Gen) gen_assert_single_expr(expr ast.Expr, typ ast.Type) { // eprintln('> gen_assert_single_expr typ: $typ | expr: $expr | typeof(expr): ${typeof(expr)}') unknown_value := '*unknown value*' match expr { - ast.CastExpr, ast.IndexExpr, ast.MatchExpr { + ast.CastExpr, ast.IfExpr, ast.IndexExpr, ast.MatchExpr { g.write(ctoslit(unknown_value)) } ast.PrefixExpr { diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 9351a6f395..e9a8355a81 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -4584,7 +4584,7 @@ fn (mut g Gen) need_tmp_var_in_if(node ast.IfExpr) bool { return true } for branch in node.branches { - if branch.cond is ast.IfGuardExpr { + if branch.cond is ast.IfGuardExpr || branch.stmts.len > 1 { return true } if branch.stmts.len == 1 { diff --git a/vlib/v/gen/c/infix_expr.v b/vlib/v/gen/c/infix_expr.v index 36f610ebe0..740c993a68 100644 --- a/vlib/v/gen/c/infix_expr.v +++ b/vlib/v/gen/c/infix_expr.v @@ -506,6 +506,8 @@ fn (mut g Gen) infix_expr_left_shift_op(node ast.InfixExpr) { fn (mut g Gen) infix_expr_and_or_op(node ast.InfixExpr) { if node.right is ast.IfExpr { // b := a && if true { a = false ...} else {...} + prev_inside_ternary := g.inside_ternary + g.inside_ternary = 0 if g.need_tmp_var_in_if(node.right) { tmp := g.new_tmp_var() cur_line := g.go_before_stmt(0).trim_space() @@ -518,8 +520,10 @@ fn (mut g Gen) infix_expr_and_or_op(node ast.InfixExpr) { g.infix_left_var_name = if node.op == .and { tmp } else { '!$tmp' } g.expr(node.right) g.infix_left_var_name = '' + g.inside_ternary = prev_inside_ternary return } + g.inside_ternary = prev_inside_ternary } g.gen_plain_infix_expr(node) } diff --git a/vlib/v/tests/if_expr_of_multi_stmts_test.v b/vlib/v/tests/if_expr_of_multi_stmts_test.v new file mode 100644 index 0000000000..308db30539 --- /dev/null +++ b/vlib/v/tests/if_expr_of_multi_stmts_test.v @@ -0,0 +1,15 @@ +fn test_if_expr_of_multi_stmts() { + a := 2 + ret := if a > 1 { + mut b := 1 + b *= 10 + println(b) + b + } else { + mut c := 0 + c += 2 + println(c) + c + } + assert ret == 10 +}