1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

gen: fix for ... in array (#8428)

This commit is contained in:
Enzo 2021-01-30 12:27:11 +01:00 committed by GitHub
parent a044441224
commit ced7649bf8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 7 deletions

View File

@ -1283,14 +1283,14 @@ fn (mut g Gen) for_in(it ast.ForInStmt) {
g.writeln('// FOR IN array')
styp := g.typ(it.val_type)
val_sym := g.table.get_type_symbol(it.val_type)
cond_type_is_ptr := it.cond_type.is_ptr()
tmp := g.new_tmp_var()
tmp_type := if cond_type_is_ptr { 'array *' } else { 'array' }
g.write('$tmp_type $tmp = ')
g.write(g.typ(it.cond_type))
g.write(' $tmp = ')
g.expr(it.cond)
g.writeln(';')
i := if it.key_var in ['', '_'] { g.new_tmp_var() } else { it.key_var }
op_field := if cond_type_is_ptr { '->' } else { '.' }
op_field := if it.cond_type.is_ptr() { '->' } else { '.' } +
if it.cond_type.share() == .shared_t { 'val.' } else { '' }
g.writeln('for (int $i = 0; $i < $tmp${op_field}len; ++$i) {')
if it.val_var != '_' {
if val_sym.kind == .function {
@ -1350,9 +1350,9 @@ fn (mut g Gen) for_in(it ast.ForInStmt) {
g.writeln('// FOR IN map')
idx := g.new_tmp_var()
atmp := g.new_tmp_var()
atmp_styp := g.typ(it.cond_type)
arw_or_pt := if it.cond_type.nr_muls() > 0 { '->' } else { '.' }
g.write('$atmp_styp $atmp = ')
arw_or_pt := if it.cond_type.is_ptr() { '->' } else { '.' }
g.write(g.typ(it.cond_type))
g.write(' $atmp = ')
g.expr(it.cond)
g.writeln(';')
g.writeln('for (int $idx = 0; $idx < $atmp${arw_or_pt}key_values.len; ++$idx) {')

20
vlib/v/tests/array_test.v Normal file
View File

@ -0,0 +1,20 @@
fn test_for_in_array_named_array() {
mut array := [1]
for elem in array {
assert elem == 1
}
for mut elem in array {
assert *elem == 1
elem = 2
assert *elem == 2
}
}
fn test_for_in_shared_array_named_array() {
shared array := &[1]
rlock array {
for elem in array {
assert elem == 1
}
}
}