cgen: use a temp variable for the array part inside 'for x in array{}'

pull/4403/head
Delyan Angelov 2020-04-14 13:22:58 +03:00
parent 2df4998acc
commit c04c973f84
1 changed files with 16 additions and 17 deletions

View File

@ -548,31 +548,30 @@ fn (g mut Gen) for_in(it ast.ForInStmt) {
g.writeln('}') g.writeln('}')
} else if it.kind == .array { } else if it.kind == .array {
// `for num in nums {` // `for num in nums {`
g.writeln('// FOR IN') g.writeln('// FOR IN array')
i := if it.key_var == '' { g.new_tmp_var() } else { it.key_var }
styp := g.typ(it.val_type) styp := g.typ(it.val_type)
g.write('for (int $i = 0; $i < ')
g.expr(it.cond)
cond_type_is_ptr := table.type_is_ptr(it.cond_type) cond_type_is_ptr := table.type_is_ptr(it.cond_type)
if cond_type_is_ptr { atmp := g.new_tmp_var()
g.writeln('->') atmp_type := if cond_type_is_ptr { 'array *' } else { 'array' }
} else { g.write('${atmp_type} ${atmp} = ')
g.writeln('.')
}
g.write('len; $i++) {')
g.write('\t$styp $it.val_var = (($styp*)')
g.expr(it.cond) g.expr(it.cond)
g.writeln(';')
i := if it.key_var == '' { g.new_tmp_var() } else { it.key_var }
if cond_type_is_ptr { if cond_type_is_ptr {
g.writeln('->') g.writeln('for (int $i = 0; $i < ${atmp}->len; $i++) {')
} else { }else{
g.writeln('.') g.writeln('for (int $i = 0; $i < ${atmp}.len; $i++) {')
}
if cond_type_is_ptr {
g.writeln('\t$styp $it.val_var = (($styp*)${atmp}->data)[$i];')
}else{
g.writeln('\t$styp $it.val_var = (($styp*)${atmp}.data)[$i];')
} }
g.write('data)[$i];')
g.stmts(it.stmts) g.stmts(it.stmts)
g.writeln('}') g.writeln('}')
} else if it.kind == .map { } else if it.kind == .map {
// `for key, val in map {` // `for key, val in map {`
g.writeln('// FOR IN') g.writeln('// FOR IN map')
key_styp := g.typ(it.key_type) key_styp := g.typ(it.key_type)
val_styp := g.typ(it.val_type) val_styp := g.typ(it.val_type)
keys_tmp := 'keys_' + g.new_tmp_var() keys_tmp := 'keys_' + g.new_tmp_var()
@ -590,7 +589,7 @@ fn (g mut Gen) for_in(it ast.ForInStmt) {
g.stmts(it.stmts) g.stmts(it.stmts)
g.writeln('}') g.writeln('}')
} else if table.type_is(it.cond_type, .variadic) { } else if table.type_is(it.cond_type, .variadic) {
g.writeln('// FOR IN') g.writeln('// FOR IN cond_type/variadic')
i := if it.key_var == '' { g.new_tmp_var() } else { it.key_var } i := if it.key_var == '' { g.new_tmp_var() } else { it.key_var }
styp := g.typ(it.cond_type) styp := g.typ(it.cond_type)
g.write('for (int $i = 0; $i < ') g.write('for (int $i = 0; $i < ')