From 1dd1be4400020cbb4e914e96ad4d6ccd358ce4f0 Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 24 Feb 2021 21:06:29 +0800 Subject: [PATCH] cgen: fix if_expr with array.map (fix #8925) (#8937) --- vlib/v/gen/c/cgen.v | 34 +++++++++++++++++++++++-------- vlib/v/tests/if_expression_test.v | 13 ++++++++++++ 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 5bfc95d5b0..86e47afca4 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -4117,6 +4117,30 @@ fn (mut g Gen) concat_expr(node ast.ConcatExpr) { } } +fn (mut g Gen) need_tmp_var_in_if(node ast.IfExpr) bool { + if node.is_expr && g.inside_ternary == 0 { + if g.is_autofree { + return true + } + for branch in node.branches { + if branch.stmts.len == 1 { + if branch.stmts[0] is ast.ExprStmt { + stmt := branch.stmts[0] as ast.ExprStmt + if stmt.expr is ast.CallExpr { + if stmt.expr.is_method { + left_sym := g.table.get_type_symbol(stmt.expr.receiver_type) + if left_sym.kind in [.array, .array_fixed, .map] { + return true + } + } + } + } + } + } + } + return false +} + fn (mut g Gen) if_expr(node ast.IfExpr) { if node.is_comptime { g.comp_if(node) @@ -4128,15 +4152,7 @@ fn (mut g Gen) if_expr(node ast.IfExpr) { // easier to use a temp var, than do C tricks with commas, introduce special vars etc // (as it used to be done). // Always use this in -autofree, since ?: can have tmp expressions that have to be freed. - first_branch := node.branches[0] - needs_tmp_var := node.is_expr && (g.is_autofree || (g.pref.experimental - && (first_branch.stmts.len > 1 || (first_branch.stmts[0] is ast.ExprStmt - && (first_branch.stmts[0] as ast.ExprStmt).expr is ast.IfExpr)))) - /* - needs_tmp_var := node.is_expr && - (g.autofree || g.pref.experimental) && - (node.branches[0].stmts.len > 1 || node.branches[0].stmts[0] is ast.IfExpr) - */ + needs_tmp_var := g.need_tmp_var_in_if(node) tmp := if needs_tmp_var { g.new_tmp_var() } else { '' } mut cur_line := '' if needs_tmp_var { diff --git a/vlib/v/tests/if_expression_test.v b/vlib/v/tests/if_expression_test.v index 7c0580d037..4d63333d59 100644 --- a/vlib/v/tests/if_expression_test.v +++ b/vlib/v/tests/if_expression_test.v @@ -167,3 +167,16 @@ fn test_multi_if_expr_with_infix() { a := if 1 == 0 { 1 } else if 1 == 0 { 2 } else { 3 } + 4 assert a == 7 } + +fn test_if_expr_with_array_map() { + num_string := '2 3' + + assigned := if num_string.len > 1 { + num_string.split(' ').map(it.int()) + } else { + [789] + } + + println(assigned) + assert assigned == [2, 3] +}