cgen: fix comptime for_in methods call (#12741)

pull/12743/head
yuyi 2021-12-06 16:55:27 +08:00 committed by GitHub
parent 3ab82a23c5
commit d85111e3dd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 29 additions and 2 deletions

View File

@ -3003,6 +3003,10 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
left.obj.typ = var_type
}
}
} else if val is ast.ComptimeCall {
key_str := '${val.method_name}.return_type'
var_type = g.comptime_var_type_map[key_str] or { var_type }
left.obj.typ = var_type
}
is_auto_heap = left.obj.is_auto_heap
}

View File

@ -1146,12 +1146,12 @@ fn (mut g Gen) fn_call(node ast.CallExpr) {
// g.generate_tmp_autofree_arg_vars(node, name)
// Handle `print(x)`
mut print_auto_str := false
if is_print && node.args[0].typ != ast.string_type { // && !free_tmp_arg_vars {
if is_print && (node.args[0].typ != ast.string_type || g.comptime_for_method.len > 0) { // && !free_tmp_arg_vars {
mut typ := node.args[0].typ
if typ == 0 {
g.checker_bug('print arg.typ is 0', node.pos)
}
if typ != ast.string_type {
if typ != ast.string_type || g.comptime_for_method.len > 0 {
expr := node.args[0].expr
typ_sym := g.table.get_type_symbol(typ)
if typ_sym.kind == .interface_ && (typ_sym.info as ast.Interface).defines_method('str') {

View File

@ -0,0 +1,23 @@
struct Foo {}
fn (f Foo) a() int {
return 1
}
fn (f Foo) b() int {
return 2
}
fn test_comptime_for_method_call() {
f := Foo{}
mut rets := []string{}
$for method in Foo.methods {
x := f.$method()
println(x)
rets << x.str()
}
assert rets.len == 2
assert rets[0] == '1'
assert rets[1] == '2'
}