cgen: fix for_in array of fixed_array (fix #9098) (#9099)

pull/9111/head
yuyi 2021-03-04 18:39:39 +08:00 committed by GitHub
parent 5b041db442
commit 5f9af3f594
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 0 deletions

View File

@ -1385,6 +1385,10 @@ fn (mut g Gen) for_in_stmt(node ast.ForInStmt) {
g.write('\t')
g.write_fn_ptr_decl(val_sym.info as table.FnType, c_name(node.val_var))
g.writeln(' = ((voidptr*)$tmp${op_field}data)[$i];')
} else if val_sym.kind == .array_fixed && !node.val_is_mut {
right := '(($styp*)$tmp${op_field}data)[$i]'
g.writeln('\t$styp ${c_name(node.val_var)};')
g.writeln('\tmemcpy(*($styp*)${c_name(node.val_var)}, (byte*)$right, sizeof($styp));')
} else {
// If val is mutable (pointer behind the scenes), we need to generate
// `int* val = ((int*)arr.data) + i;`

View File

@ -0,0 +1,25 @@
fn test_for_in_containers_of_fixed_array() {
mut rets := []string{}
arr := [][2]int{len: 3}
for pair in arr {
println(pair)
rets << '$pair'
}
assert rets[0] == '[0, 0]'
assert rets[1] == '[0, 0]'
assert rets[2] == '[0, 0]'
}
fn test_for_mut_in_containers_of_fixed_array() {
mut rets := []string{}
mut arr := [][2]int{len: 3}
for mut pair in arr {
println(pair)
rets << '$pair'
}
assert rets[0] == '[0, 0]'
assert rets[1] == '[0, 0]'
assert rets[2] == '[0, 0]'
}