cgen: fix reference variable str() method call (#21753)

This commit is contained in:
yuyi 2024-06-28 20:47:35 +08:00 committed by GitHub
parent 17e32d051b
commit 4a7c70c909
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 23 additions and 1 deletions

View File

@ -1678,7 +1678,12 @@ fn (mut g Gen) method_call(node ast.CallExpr) {
// TODO2 // TODO2
// g.generate_tmp_autofree_arg_vars(node, name) // g.generate_tmp_autofree_arg_vars(node, name)
if !node.receiver_type.is_ptr() && left_type.is_ptr() && node.name == 'str' { if !node.receiver_type.is_ptr() && left_type.is_ptr() && node.name == 'str' {
if left_type.is_int_valptr() {
g.write('ptr_str(') g.write('ptr_str(')
} else {
g.gen_expr_to_string(node.left, left_type)
return
}
} else if node.receiver_type.is_ptr() && left_type.is_ptr() && node.name == 'str' } else if node.receiver_type.is_ptr() && left_type.is_ptr() && node.name == 'str'
&& !left_sym.has_method('str') { && !left_sym.has_method('str') {
g.gen_expr_to_string(node.left, left_type) g.gen_expr_to_string(node.left, left_type)

View File

@ -0,0 +1,17 @@
@[heap]
struct Foo {
bar string = 'bar'
baz string = 'baz'
}
fn (foo Foo) str() string {
return 'bar: ${foo.bar}, baz: ${foo.baz}'
}
fn test_reference_variable_str() {
mut many_foos := []&Foo{len: 3, init: &Foo{}}
println(many_foos.map(it.str()).join('\n'))
println(many_foos)
assert many_foos.map(it.str()) == ['&bar: bar, baz: baz', '&bar: bar, baz: baz',
'&bar: bar, baz: baz']
}