cgen: fix for_in fixed_array of fixed_array literal (#9206)

pull/9217/head
yuyi 2021-03-09 22:18:07 +08:00 committed by GitHub
parent 3edcb7e601
commit c4b0fdcbaf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 3 deletions

View File

@ -1403,8 +1403,15 @@ fn (mut g Gen) for_in_stmt(node ast.ForInStmt) {
} }
} else if node.kind == .array_fixed { } else if node.kind == .array_fixed {
mut cond_var := '' mut cond_var := ''
needs_tmp_var := node.cond_type.is_ptr() || node.cond is ast.ArrayInit cond_type_is_ptr := node.cond_type.is_ptr()
if needs_tmp_var { 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 = g.new_tmp_var()
cond_var_type := g.typ(node.cond_type).trim('*') cond_var_type := g.typ(node.cond_type).trim('*')
if !node.cond.is_lvalue() { if !node.cond.is_lvalue() {
@ -1437,8 +1444,10 @@ fn (mut g Gen) for_in_stmt(node ast.ForInStmt) {
} }
if !is_fixed_array { if !is_fixed_array {
addr := if node.val_is_mut { '&' } else { '' } addr := if node.val_is_mut { '&' } else { '' }
if needs_tmp_var { if cond_type_is_ptr {
g.writeln(' = ${addr}(*$cond_var)[$idx];') g.writeln(' = ${addr}(*$cond_var)[$idx];')
} else if cond_is_literal {
g.writeln(' = $addr$cond_var[$idx];')
} else { } else {
g.write(' = $addr') g.write(' = $addr')
g.expr(node.cond) g.expr(node.cond)

View File

@ -50,6 +50,18 @@ fn test_for_mut_in_fixed_array_of_fixed_array() {
assert rets[2] == '[5, 6]' 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() { fn test_for_in_map_of_fixed_array() {
mut rets := []string{} mut rets := []string{}
m := map{'aa': [1, 2]!, 'bb': [3, 4]!, 'cc': [5, 6]!} m := map{'aa': [1, 2]!, 'bb': [3, 4]!, 'cc': [5, 6]!}