From c4b0fdcbaff87871052185512a6e5a2a71068e89 Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 9 Mar 2021 22:18:07 +0800 Subject: [PATCH] cgen: fix for_in fixed_array of fixed_array literal (#9206) --- vlib/v/gen/c/cgen.v | 15 ++++++++++++--- .../tests/for_in_containers_of_fixed_array_test.v | 12 ++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 7239001298..63ad2e53f6 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -1403,8 +1403,15 @@ fn (mut g Gen) for_in_stmt(node ast.ForInStmt) { } } else if node.kind == .array_fixed { mut cond_var := '' - needs_tmp_var := node.cond_type.is_ptr() || node.cond is ast.ArrayInit - if needs_tmp_var { + cond_type_is_ptr := node.cond_type.is_ptr() + cond_is_literal := node.cond is ast.ArrayInit + if cond_is_literal { + cond_var = g.new_tmp_var() + g.write(g.typ(node.cond_type)) + g.write(' $cond_var = ') + g.expr(node.cond) + g.writeln(';') + } else if cond_type_is_ptr { cond_var = g.new_tmp_var() cond_var_type := g.typ(node.cond_type).trim('*') if !node.cond.is_lvalue() { @@ -1437,8 +1444,10 @@ fn (mut g Gen) for_in_stmt(node ast.ForInStmt) { } if !is_fixed_array { addr := if node.val_is_mut { '&' } else { '' } - if needs_tmp_var { + if cond_type_is_ptr { g.writeln(' = ${addr}(*$cond_var)[$idx];') + } else if cond_is_literal { + g.writeln(' = $addr$cond_var[$idx];') } else { g.write(' = $addr') g.expr(node.cond) diff --git a/vlib/v/tests/for_in_containers_of_fixed_array_test.v b/vlib/v/tests/for_in_containers_of_fixed_array_test.v index 9780b61a2c..b97c2e7e50 100644 --- a/vlib/v/tests/for_in_containers_of_fixed_array_test.v +++ b/vlib/v/tests/for_in_containers_of_fixed_array_test.v @@ -50,6 +50,18 @@ fn test_for_mut_in_fixed_array_of_fixed_array() { assert rets[2] == '[5, 6]' } +fn test_for_in_fixed_array_of_fixed_array_literal() { + mut rets := []string{} + + for pair in [[1, 2]!, [3, 4]!, [5, 6]!]! { + println(pair) + rets << '$pair' + } + assert rets[0] == '[1, 2]' + assert rets[1] == '[3, 4]' + assert rets[2] == '[5, 6]' +} + fn test_for_in_map_of_fixed_array() { mut rets := []string{} m := map{'aa': [1, 2]!, 'bb': [3, 4]!, 'cc': [5, 6]!}