checker, cgen: fix printing in 'for v in a' (#14146)

yuyi 2022-04-24 18:30:13 +08:00 committed by Jef Roosens
parent f3dff7c1c0
commit 6690dfa208
Signed by: Jef Roosens
GPG Key ID: B75D4F293C7052DB
4 changed files with 48 additions and 3 deletions

View File

@ -95,6 +95,9 @@ fn (mut c Checker) for_in_stmt(mut node ast.ForInStmt) {
node.scope.update_var_type(node.key_var, key_type)
}
mut value_type := c.table.value_type(typ)
if sym.kind == .string {
value_type = ast.byte_type
}
if value_type == ast.void_type || typ.has_flag(.optional) {
if typ != ast.void_type {
c.error('for in: cannot index `${c.table.type_to_str(typ)}`', node.cond.pos())

View File

@ -299,14 +299,15 @@ fn (mut g Gen) for_in_stmt(node ast.ForInStmt) {
} else {
node.cond
}
field_accessor := if node.cond_type.is_ptr() { '->' } else { '.' }
i := if node.key_var in ['', '_'] { g.new_tmp_var() } else { node.key_var }
g.write('for (int $i = 0; $i < ')
g.expr(cond)
g.writeln('.len; ++$i) {')
g.writeln('${field_accessor}len; ++$i) {')
if node.val_var != '_' {
g.write('\tbyte ${c_name(node.val_var)} = ')
g.write('\tu8 ${c_name(node.val_var)} = ')
g.expr(cond)
g.writeln('.str[$i];')
g.writeln('${field_accessor}str[$i];')
}
} else if node.kind == .struct_ {
cond_type_sym := g.table.sym(node.cond_type)

View File

@ -0,0 +1,11 @@
97
98
99
abc
23
77
abc
> k: abc | v: xyz
> k: def | v: jkl
abc
abc

View File

@ -0,0 +1,30 @@
interface Any {}
fn abc(a Any) {
if a is string {
for x in a {
println(x)
}
}
if a is []u8 {
for x in a {
println(x)
}
}
if a is map[string]string {
for k, v in a {
println('> k: $k | v: $v')
}
}
println(@FN)
}
fn main() {
abc('abc')
abc([u8(23), 77])
abc({
'abc': 'xyz'
'def': 'jkl'
})
abc(123)
}