cgen: move the condition of an iterator to a temp var (#8989)

pull/8992/head
spaceface 2021-02-26 21:51:01 +01:00 committed by GitHub
parent 4ad95cfeaf
commit 51fae95339
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 4 deletions

View File

@ -1480,16 +1480,20 @@ fn (mut g Gen) for_in_stmt(node ast.ForInStmt) {
return
}
ret_typ := next_fn.return_type
t_expr := g.new_tmp_var()
g.write('${g.typ(node.cond_type)} $t_expr = ')
g.expr(node.cond)
g.writeln(';')
g.writeln('while (1) {')
t := g.new_tmp_var()
receiver_styp := g.typ(next_fn.params[0].typ)
receiver_typ := next_fn.params[0].typ
receiver_styp := g.typ(receiver_typ)
fn_name := receiver_styp.replace_each(['*', '', '.', '__']) + '_next'
g.write('\t${g.typ(ret_typ)} $t = ${fn_name}(')
if !node.cond_type.is_ptr() {
if !node.cond_type.is_ptr() && receiver_typ.is_ptr() {
g.write('&')
}
g.expr(node.cond)
g.writeln(');')
g.writeln('$t_expr);')
g.writeln('\tif (!${t}.ok) { break; }')
val := if node.val_var in ['', '_'] { g.new_tmp_var() } else { node.val_var }
val_styp := g.typ(node.val_type)

View File

@ -34,3 +34,11 @@ fn test_for_in_empty_iterator() {
}
assert vals == []
}
fn test_for_in_iterator_with_tmp_expr() {
mut vals := []int{}
for val in doubler(2, 64) {
vals << val
}
assert vals == [2, 4, 8, 16, 32, 64]
}