cgen: fix if expr of multi stmts (#11208)

pull/11214/head
yuyi 2021-08-17 02:48:58 +08:00 committed by GitHub
parent 405ed584a1
commit 8521e227b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 21 additions and 2 deletions

View File

@ -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 {

View File

@ -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 {

View File

@ -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)
}

View File

@ -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
}