From 76d37f6595ba3553dbbbfbc90ee0df57f6327860 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sat, 17 Aug 2024 11:02:38 -0300 Subject: [PATCH] cgen: fix for loop with array fixed returned from fn (#22069) --- vlib/v/gen/c/cgen.v | 8 +++++++- vlib/v/gen/c/for.v | 3 +++ vlib/v/tests/array_fixed_for_loop_test.v | 16 ++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/array_fixed_for_loop_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index ea449dd6215240..95b19558ea923f 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -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 { diff --git a/vlib/v/gen/c/for.v b/vlib/v/gen/c/for.v index e12d4c81a56e15..aa0ad7aae41450 100644 --- a/vlib/v/gen/c/for.v +++ b/vlib/v/gen/c/for.v @@ -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}];') } } diff --git a/vlib/v/tests/array_fixed_for_loop_test.v b/vlib/v/tests/array_fixed_for_loop_test.v new file mode 100644 index 00000000000000..514b7c1145f687 --- /dev/null +++ b/vlib/v/tests/array_fixed_for_loop_test.v @@ -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{} +}