Skip to content

Commit

Permalink
cgen: fix shortcircuiting of infix and/or expressions (vlang#21740)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 authored Jun 27, 2024
1 parent d67f4d0 commit d9a300c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
16 changes: 16 additions & 0 deletions vlib/v/gen/c/infix.v
Original file line number Diff line number Diff line change
Expand Up @@ -1057,6 +1057,22 @@ fn (mut g Gen) infix_expr_and_or_op(node ast.InfixExpr) {
return
}
}
} else if node.right is ast.InfixExpr && g.need_tmp_var_in_expr(node.right) {
prev_inside_ternary := g.inside_ternary
g.inside_ternary = 0
tmp := g.new_tmp_var()
cur_line := g.go_before_last_stmt().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 = if node.op == .and { tmp } else { '!${tmp}' }
g.expr(node.right)
g.infix_left_var_name = ''
g.inside_ternary = prev_inside_ternary
return
}
g.gen_plain_infix_expr(node)
}
Expand Down
17 changes: 17 additions & 0 deletions vlib/v/tests/infix_expr_and_or_operate_unnecessary_eval_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
fn f(s string) !int {
if s == '' {
return error('invalid s')
}
return s.len
}

fn test_infix_expr_and_or_operate_unnecessary_eval() {
v := ''
x := v != 'xyz' || f(v)! < f('abc')!
dump(x)
assert x

y := v == 'xyz' && f(v)! < f('abc')!
dump(y)
assert !y
}

0 comments on commit d9a300c

Please sign in to comment.