diff --git a/vlib/v/gen/c/if.v b/vlib/v/gen/c/if.v index 92da23e3ee..30d69f7ef5 100644 --- a/vlib/v/gen/c/if.v +++ b/vlib/v/gen/c/if.v @@ -17,23 +17,9 @@ fn (mut g Gen) need_tmp_var_in_if(node ast.IfExpr) bool { if branch.stmts.len == 1 { if branch.stmts[0] is ast.ExprStmt { stmt := branch.stmts[0] as ast.ExprStmt - if is_noreturn_callexpr(stmt.expr) { + if g.need_tmp_var_in_expr(stmt.expr) { return true } - if stmt.expr is ast.MatchExpr { - return true - } - if stmt.expr is ast.CallExpr { - if stmt.expr.is_method { - left_sym := g.table.sym(stmt.expr.receiver_type) - if left_sym.kind in [.array, .array_fixed, .map] { - return true - } - } - if stmt.expr.or_block.kind != .absent { - return true - } - } } } } @@ -41,6 +27,33 @@ fn (mut g Gen) need_tmp_var_in_if(node ast.IfExpr) bool { return false } +fn (mut g Gen) need_tmp_var_in_expr(expr ast.Expr) bool { + if is_noreturn_callexpr(expr) { + return true + } + if expr is ast.MatchExpr { + return true + } + if expr is ast.CallExpr { + if expr.is_method { + left_sym := g.table.sym(expr.receiver_type) + if left_sym.kind in [.array, .array_fixed, .map] { + return true + } + } + if expr.or_block.kind != .absent { + return true + } + } + if expr is ast.CastExpr { + return g.need_tmp_var_in_expr(expr.expr) + } + if expr is ast.ParExpr { + return g.need_tmp_var_in_expr(expr.expr) + } + return false +} + fn (mut g Gen) if_expr(node ast.IfExpr) { if node.is_comptime { g.comptime_if(node) diff --git a/vlib/v/tests/inout/printing_optional_in_if_expr.out b/vlib/v/tests/inout/printing_optional_in_if_expr.out new file mode 100644 index 0000000000..d00491fd7e --- /dev/null +++ b/vlib/v/tests/inout/printing_optional_in_if_expr.out @@ -0,0 +1 @@ +1 diff --git a/vlib/v/tests/inout/printing_optional_in_if_expr.vv b/vlib/v/tests/inout/printing_optional_in_if_expr.vv new file mode 100644 index 0000000000..f1c9f9b201 --- /dev/null +++ b/vlib/v/tests/inout/printing_optional_in_if_expr.vv @@ -0,0 +1,11 @@ +fn optional() ?int { + return 1 +} + +fn main() { + println(if true { + i32(optional() or { 2 }) + } else { + i32(8) + }) +}