Skip to content

Commit 1dd1be4

Browse files
authored
cgen: fix if_expr with array.map (fix #8925) (#8937)
1 parent 05a0853 commit 1dd1be4

File tree

2 files changed

+38
-9
lines changed

2 files changed

+38
-9
lines changed

vlib/v/gen/c/cgen.v

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4117,6 +4117,30 @@ fn (mut g Gen) concat_expr(node ast.ConcatExpr) {
41174117
}
41184118
}
41194119

4120+
fn (mut g Gen) need_tmp_var_in_if(node ast.IfExpr) bool {
4121+
if node.is_expr && g.inside_ternary == 0 {
4122+
if g.is_autofree {
4123+
return true
4124+
}
4125+
for branch in node.branches {
4126+
if branch.stmts.len == 1 {
4127+
if branch.stmts[0] is ast.ExprStmt {
4128+
stmt := branch.stmts[0] as ast.ExprStmt
4129+
if stmt.expr is ast.CallExpr {
4130+
if stmt.expr.is_method {
4131+
left_sym := g.table.get_type_symbol(stmt.expr.receiver_type)
4132+
if left_sym.kind in [.array, .array_fixed, .map] {
4133+
return true
4134+
}
4135+
}
4136+
}
4137+
}
4138+
}
4139+
}
4140+
}
4141+
return false
4142+
}
4143+
41204144
fn (mut g Gen) if_expr(node ast.IfExpr) {
41214145
if node.is_comptime {
41224146
g.comp_if(node)
@@ -4128,15 +4152,7 @@ fn (mut g Gen) if_expr(node ast.IfExpr) {
41284152
// easier to use a temp var, than do C tricks with commas, introduce special vars etc
41294153
// (as it used to be done).
41304154
// Always use this in -autofree, since ?: can have tmp expressions that have to be freed.
4131-
first_branch := node.branches[0]
4132-
needs_tmp_var := node.is_expr && (g.is_autofree || (g.pref.experimental
4133-
&& (first_branch.stmts.len > 1 || (first_branch.stmts[0] is ast.ExprStmt
4134-
&& (first_branch.stmts[0] as ast.ExprStmt).expr is ast.IfExpr))))
4135-
/*
4136-
needs_tmp_var := node.is_expr &&
4137-
(g.autofree || g.pref.experimental) &&
4138-
(node.branches[0].stmts.len > 1 || node.branches[0].stmts[0] is ast.IfExpr)
4139-
*/
4155+
needs_tmp_var := g.need_tmp_var_in_if(node)
41404156
tmp := if needs_tmp_var { g.new_tmp_var() } else { '' }
41414157
mut cur_line := ''
41424158
if needs_tmp_var {

vlib/v/tests/if_expression_test.v

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,3 +167,16 @@ fn test_multi_if_expr_with_infix() {
167167
a := if 1 == 0 { 1 } else if 1 == 0 { 2 } else { 3 } + 4
168168
assert a == 7
169169
}
170+
171+
fn test_if_expr_with_array_map() {
172+
num_string := '2 3'
173+
174+
assigned := if num_string.len > 1 {
175+
num_string.split(' ').map(it.int())
176+
} else {
177+
[789]
178+
}
179+
180+
println(assigned)
181+
assert assigned == [2, 3]
182+
}

0 commit comments

Comments
 (0)