From a65b73d3e447f324012883909c4f13d284fb8705 Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 19 Jan 2021 12:50:23 +0800 Subject: [PATCH] cgen: fix for_in_fixed_array (fix #8186) (#8195) --- vlib/v/gen/cgen.v | 29 +++++++++++++---------------- vlib/v/tests/fixed_array_test.v | 14 ++++++++++++++ 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 2a882880b8..8245304523 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -1288,21 +1288,15 @@ fn (mut g Gen) for_in(it ast.ForInStmt) { } else if it.kind == .array_fixed { atmp := g.new_tmp_var() atmp_type := g.typ(it.cond_type).trim('*') - if !it.cond.is_lvalue() { - g.write('$atmp_type *$atmp = ') - if !it.cond_type.is_ptr() { - g.write('&') + if it.cond_type.is_ptr() || it.cond is ast.ArrayInit { + if !it.cond.is_lvalue() { + g.write('$atmp_type *$atmp = (($atmp_type)') + } else { + g.write('$atmp_type *$atmp = (') } - g.write('(($atmp_type)') - } else { - g.write('$atmp_type *$atmp = ') - if !it.cond_type.is_ptr() { - g.write('&') - } - g.write('(') + g.expr(it.cond) + g.writeln(');') } - g.expr(it.cond) - g.writeln(');') i := if it.key_var in ['', '_'] { g.new_tmp_var() } else { it.key_var } cond_sym := g.table.get_type_symbol(it.cond_type) info := cond_sym.info as table.ArrayFixed @@ -1316,10 +1310,13 @@ fn (mut g Gen) for_in(it ast.ForInStmt) { styp := g.typ(it.val_type) g.write('\t$styp ${c_name(it.val_var)}') } - if it.val_is_mut { - g.writeln(' = &(*$atmp)[$i];') + addr := if it.val_is_mut { '&' } else { '' } + if it.cond_type.is_ptr() || it.cond is ast.ArrayInit { + g.writeln(' = ${addr}(*$atmp)[$i];') } else { - g.writeln(' = (*$atmp)[$i];') + g.write(' = $addr') + g.expr(it.cond) + g.writeln('[$i];') } } } else if it.kind == .map { diff --git a/vlib/v/tests/fixed_array_test.v b/vlib/v/tests/fixed_array_test.v index 0c58b007ef..d31c726c5d 100644 --- a/vlib/v/tests/fixed_array_test.v +++ b/vlib/v/tests/fixed_array_test.v @@ -85,3 +85,17 @@ fn test_iteration_over_fixed_array_literal() { } assert s == 27.25 } + +fn calc_size(a [3]int) { + mut s := 0 + for i in a { + println(i) + s += i + } + assert s == 6 +} + +fn test_for_in_fixed_array() { + arr := [1,2,3]! + calc_size(arr) +}