cgen: fix if expr of multi stmts (#11208)
parent
405ed584a1
commit
8521e227b4
|
@ -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)}')
|
// eprintln('> gen_assert_single_expr typ: $typ | expr: $expr | typeof(expr): ${typeof(expr)}')
|
||||||
unknown_value := '*unknown value*'
|
unknown_value := '*unknown value*'
|
||||||
match expr {
|
match expr {
|
||||||
ast.CastExpr, ast.IndexExpr, ast.MatchExpr {
|
ast.CastExpr, ast.IfExpr, ast.IndexExpr, ast.MatchExpr {
|
||||||
g.write(ctoslit(unknown_value))
|
g.write(ctoslit(unknown_value))
|
||||||
}
|
}
|
||||||
ast.PrefixExpr {
|
ast.PrefixExpr {
|
||||||
|
|
|
@ -4584,7 +4584,7 @@ fn (mut g Gen) need_tmp_var_in_if(node ast.IfExpr) bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
for branch in node.branches {
|
for branch in node.branches {
|
||||||
if branch.cond is ast.IfGuardExpr {
|
if branch.cond is ast.IfGuardExpr || branch.stmts.len > 1 {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if branch.stmts.len == 1 {
|
if branch.stmts.len == 1 {
|
||||||
|
|
|
@ -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) {
|
fn (mut g Gen) infix_expr_and_or_op(node ast.InfixExpr) {
|
||||||
if node.right is ast.IfExpr {
|
if node.right is ast.IfExpr {
|
||||||
// b := a && if true { a = false ...} else {...}
|
// 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) {
|
if g.need_tmp_var_in_if(node.right) {
|
||||||
tmp := g.new_tmp_var()
|
tmp := g.new_tmp_var()
|
||||||
cur_line := g.go_before_stmt(0).trim_space()
|
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.infix_left_var_name = if node.op == .and { tmp } else { '!$tmp' }
|
||||||
g.expr(node.right)
|
g.expr(node.right)
|
||||||
g.infix_left_var_name = ''
|
g.infix_left_var_name = ''
|
||||||
|
g.inside_ternary = prev_inside_ternary
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
g.inside_ternary = prev_inside_ternary
|
||||||
}
|
}
|
||||||
g.gen_plain_infix_expr(node)
|
g.gen_plain_infix_expr(node)
|
||||||
}
|
}
|
||||||
|
|
|
@ -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
|
||||||
|
}
|
Loading…
Reference in New Issue