checker: fix generic sumtype method (#11565)

pull/11568/head
yuyi 2021-09-21 21:19:43 +08:00 committed by GitHub
parent 95136cbfc7
commit d6fa6a459c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 3 deletions

View File

@ -2278,9 +2278,17 @@ pub fn (mut c Checker) method_call(mut node ast.CallExpr) ast.Type {
method = m
has_method = true
} else {
if left_type_sym.info is ast.Struct {
if left_type_sym.info.parent_type != 0 {
type_sym := c.table.get_type_symbol(left_type_sym.info.parent_type)
if left_type_sym.kind in [.struct_, .sum_type, .interface_] {
mut parent_type := ast.void_type
if left_type_sym.info is ast.Struct {
parent_type = left_type_sym.info.parent_type
} else if left_type_sym.info is ast.SumType {
parent_type = left_type_sym.info.parent_type
} else if left_type_sym.info is ast.Interface {
parent_type = left_type_sym.info.parent_type
}
if parent_type != 0 {
type_sym := c.table.get_type_symbol(parent_type)
if m := c.table.type_find_method(type_sym, method_name) {
method = m
has_method = true

View File

@ -0,0 +1,32 @@
struct Empty {}
struct Node<T> {
value T
left Leaf<T>
right Leaf<T>
}
type Leaf<T> = Empty | Node<T>
// return size(number of nodes) of BST
fn (leaf Leaf<T>) size<T>() int {
return match leaf {
Empty { 0 }
Node<T> { 1 + leaf.left.size() + leaf.right.size() }
}
}
fn test_generic_sumtype_method() {
r := Node<int>{
value: 20
left: Empty{}
right: Empty{}
}
tree := Leaf<int>(Node<int>{
value: 10
left: Empty{}
right: r
})
println(tree.size())
assert tree.size() == 2
}