cgen: fixes for ... in with index (#11995)

pull/12006/head
André Diego Piske 2021-09-28 18:35:07 +02:00 committed by GitHub
parent 5d3795e876
commit 8dde9d4a7b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 43 additions and 1 deletions

View File

@ -2052,7 +2052,11 @@ fn (mut g Gen) for_in_stmt(node ast.ForInStmt) {
g.write('${g.typ(node.cond_type)} $t_expr = ')
g.expr(node.cond)
g.writeln(';')
g.writeln('while (1) {')
if node.key_var in ['', '_'] {
g.writeln('while (1) {')
} else {
g.writeln('for (size_t $node.key_var = 0;; ++$node.key_var) {')
}
t_var := g.new_tmp_var()
receiver_typ := next_fn.params[0].typ
receiver_styp := g.typ(receiver_typ)

View File

@ -0,0 +1,2 @@
for (size_t ix = 0;; ++ix) {
while (1) {

View File

@ -0,0 +1,9 @@
a.2
a.4
a.6
a.8
b.0=2
b.1=4
b.2=6
b.3=8
end

27
vlib/v/gen/c/testdata/for_in.vv vendored 100644
View File

@ -0,0 +1,27 @@
struct CustomIter {
mut:
idx int
}
fn new_custom_iter() CustomIter {
return CustomIter{ idx: 0 }
}
fn (mut a CustomIter) next() ?int {
if a.idx == 4 {
return error('')
} else {
a.idx++
return a.idx * 2
}
}
fn main() {
for x in new_custom_iter() {
println('a.$x')
}
for ix, val in new_custom_iter() {
println('b.$ix=$val')
}
println('end')
}