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

master
yuyi 2022-04-24 18:30:13 +08:00 committed by GitHub
parent 9355048b6c
commit c819f0f86f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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)
}