1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

cgen: fix short circuiting behaviour of logical expressions, when several PrefixExpr's are used in if conditions (#16660)

This commit is contained in:
Felipe Pena 2022-12-13 08:09:03 -03:00 committed by GitHub
parent 992621bd91
commit 738fe77300
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 55 additions and 0 deletions

View File

@ -886,6 +886,28 @@ fn (mut g Gen) infix_expr_and_or_op(node ast.InfixExpr) {
g.inside_ternary = prev_inside_ternary
return
}
} else if node.right is ast.PrefixExpr && g.inside_ternary == 0 {
prefix := node.right
if prefix.op == .not && prefix.right is ast.CallExpr {
call_expr := prefix.right as ast.CallExpr
if call_expr.or_block.kind != .absent {
prev_inside_ternary := g.inside_ternary
g.inside_ternary = 0
tmp := g.new_tmp_var()
cur_line := g.go_before_stmt(0).trim_space()
g.empty_line = true
g.write('bool ${tmp} = (')
g.expr(node.left)
g.writeln(');')
g.set_current_pos_as_last_stmt_pos()
g.write('${cur_line} ${tmp} ${node.op.str()} ')
g.infix_left_var_name = '!${tmp}'
g.expr(node.right)
g.infix_left_var_name = ''
g.inside_ternary = prev_inside_ternary
return
}
}
}
g.gen_plain_infix_expr(node)
}

View File

@ -0,0 +1,4 @@
True 2
ok
True 3
False 3

View File

@ -0,0 +1,29 @@
fn false_(n int) !bool {
println('False ${n}')
return false
}
fn true_(n int) !bool {
println('True ${n}')
return true
}
fn true_2() !bool {
println('True')
return true
}
fn test() ! {
if true_(2)! || !false_(2)! {
println('ok')
}
if false {
} else if (true_(3)! || !false_(3)!) && false_(3)! {
println('ok2')
}
}
fn main() {
test() or { panic(err) }
}