Skip to content

Commit

Permalink
cgen: fix for loop with array fixed returned from fn (vlang#22069)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp authored Aug 17, 2024
1 parent e9c9580 commit 76d37f6
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
8 changes: 7 additions & 1 deletion vlib/v/gen/c/cgen.v
Original file line number Diff line number Diff line change
Expand Up @@ -5784,7 +5784,13 @@ fn (mut g Gen) return_stmt(node ast.Return) {
} else {
node.types[0]
}
g.write('memcpy(${tmpvar}.ret_arr, ${g.expr_string(node.exprs[0])}, sizeof(${g.typ(typ)}))')
typ_sym := g.table.final_sym(typ)
if typ_sym.kind == .array_fixed
&& (typ_sym.info as ast.ArrayFixed).is_fn_ret {
g.write('memcpy(${tmpvar}.ret_arr, ${g.expr_string(node.exprs[0])}.ret_arr, sizeof(${g.typ(typ)}))')
} else {
g.write('memcpy(${tmpvar}.ret_arr, ${g.expr_string(node.exprs[0])}, sizeof(${g.typ(typ)}))')
}
} else if node.exprs[0] in [ast.ArrayInit, ast.StructInit] {
if node.exprs[0] is ast.ArrayInit && node.exprs[0].is_fixed
&& node.exprs[0].has_init {
Expand Down
3 changes: 3 additions & 0 deletions vlib/v/gen/c/for.v
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,9 @@ fn (mut g Gen) for_in_stmt(node_ ast.ForInStmt) {
} else {
g.write(' = ${addr}')
g.expr(node.cond)
if info.is_fn_ret {
g.write('.ret_arr')
}
g.writeln('[${idx}];')
}
}
Expand Down
16 changes: 16 additions & 0 deletions vlib/v/tests/array_fixed_for_loop_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
fn double() (bool, [4]i16) {
return true, [4]i16{}
}

fn foo() [4]i16 {
_, b := double()
for i in b {
println(i)
}
return b
}

fn test_main() {
arr := foo()
assert arr == [4]i16{}
}

0 comments on commit 76d37f6

Please sign in to comment.