ast, cgen: fix generic method str() overload (#12330)

pull/12298/head
yuyi 2021-10-29 00:03:17 +08:00 committed by GitHub
parent 475a2f9b43
commit 0e95e4d7b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 2 deletions

View File

@ -1186,6 +1186,11 @@ pub fn (t &TypeSymbol) has_method(name string) bool {
return true
}
pub fn (t &TypeSymbol) has_method_with_generic_parent(name string) bool {
t.find_method_with_generic_parent(name) or { return false }
return true
}
pub fn (t &TypeSymbol) find_method(name string) ?Fn {
for method in t.methods {
if method.name == name {
@ -1240,7 +1245,7 @@ pub fn (t &TypeSymbol) str_method_info() (bool, bool, int) {
mut has_str_method := false
mut expects_ptr := false
mut nr_args := 0
if sym_str_method := t.find_method('str') {
if sym_str_method := t.find_method_with_generic_parent('str') {
has_str_method = true
nr_args = sym_str_method.params.len
if nr_args > 0 {

View File

@ -144,6 +144,9 @@ fn (mut g Gen) get_str_fn(typ ast.Type) string {
str_fn_name = styp_to_str_fn_name(sym.name)
}
}
if sym.has_method_with_generic_parent('str') && mut sym.info is ast.Struct {
str_fn_name = g.generic_fn_name(sym.info.concrete_types, str_fn_name, false)
}
g.str_types << StrType{
typ: unwrapped
styp: styp
@ -157,7 +160,7 @@ fn (mut g Gen) final_gen_str(typ StrType) {
}
g.generated_str_fns << typ
sym := g.table.get_type_symbol(typ.typ)
if sym.has_method('str') && !typ.typ.has_flag(.optional) {
if sym.has_method_with_generic_parent('str') && !typ.typ.has_flag(.optional) {
return
}
styp := typ.styp

View File

@ -0,0 +1,15 @@
struct Gen<G> {
data G
id int
size int
}
fn (g Gen<G>) str() string {
return 'Gen<G> $g.id, $g.data, ${g.size}.'
}
fn test_generics_method_str_overload() {
mut g := Gen<string>{'Gen', 0, 10}
println(g)
assert '$g' == 'Gen<G> 0, Gen, 10.'
}