cgen: fix comptime for in field selector (#12457)

pull/12462/head
yuyi 2021-11-15 02:58:22 +08:00 committed by GitHub
parent 61b99e1915
commit fb997eb5fe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 0 deletions

View File

@ -810,6 +810,16 @@ fn (mut g Gen) method_call(node ast.CallExpr) {
if rec_type.has_flag(.shared_f) { if rec_type.has_flag(.shared_f) {
rec_type = rec_type.clear_flag(.shared_f).set_nr_muls(0) rec_type = rec_type.clear_flag(.shared_f).set_nr_muls(0)
} }
if node.left is ast.ComptimeSelector {
if node.left.field_expr is ast.SelectorExpr {
if node.left.field_expr.expr is ast.Ident {
key_str := '${node.left.field_expr.expr.name}.typ'
rec_type = g.comptime_var_type_map[key_str] or { rec_type }
g.gen_expr_to_string(node.left, rec_type)
return
}
}
}
g.get_str_fn(rec_type) g.get_str_fn(rec_type)
} else if node.name == 'free' { } else if node.name == 'free' {
mut rec_type := node.receiver_type mut rec_type := node.receiver_type
@ -1113,6 +1123,14 @@ fn (mut g Gen) fn_call(node ast.CallExpr) {
g.writeln('; ${c_name(print_method)}($tmp); string_free(&$tmp);') g.writeln('; ${c_name(print_method)}($tmp); string_free(&$tmp);')
} else { } else {
g.write('${c_name(print_method)}(') g.write('${c_name(print_method)}(')
if expr is ast.ComptimeSelector {
if expr.field_expr is ast.SelectorExpr {
if expr.field_expr.expr is ast.Ident {
key_str := '${expr.field_expr.expr.name}.typ'
typ = g.comptime_var_type_map[key_str] or { typ }
}
}
}
g.gen_expr_to_string(expr, typ) g.gen_expr_to_string(expr, typ)
g.write(')') g.write(')')
} }

View File

@ -0,0 +1,30 @@
fn print_field_values<T>(s T) {
mut value_list := []string{}
$for field in T.fields {
println(s.$(field.name))
value_list << s.$(field.name).str()
}
assert value_list.len == 4
assert value_list[0] == 'Simon'
assert value_list[1] == 'simon1234'
assert value_list[2] == 'simon@gmail.com'
assert value_list[3] == '15'
}
struct Foo {
name string
password string
email string
age int
}
fn test_comptime_for_in_field_selector() {
bar := Foo{
name: 'Simon'
password: 'simon1234'
email: 'simon@gmail.com'
age: 15
}
print_field_values<Foo>(bar)
}