Fix method resolution with pointers

This commit is contained in:
Marc Vertes
2018-09-21 17:00:32 +02:00
parent 5b05e06dca
commit 7eced03d66
3 changed files with 44 additions and 0 deletions

15
_test/method11.go Normal file
View File

@@ -0,0 +1,15 @@
package main
func main() {
o := &Coord{3, 4}
println(o.dist())
}
func (c *Coord) dist() int { return c.x*c.x + c.y*c.y }
type Coord struct {
x, y int
}
// Output:
// 25

View File

@@ -48,13 +48,20 @@ func (interp *Interpreter) Gta(root *Node) {
typeName = receiver.child[1].ident
}
if typeName == "" {
// The receiver is a pointer, retrieve typeName from indirection
typeName = receiver.child[1].child[0].ident
elemtype := scope.getType(typeName)
if elemtype == nil {
// Add type if necessary, so method can be registered
scope.sym[typeName] = &Symbol{kind: Typ, typ: &Type{}}
elemtype = scope.sym[typeName].typ
}
receiverType = &Type{cat: PtrT, val: elemtype}
elemtype.method = append(elemtype.method, n)
} else {
receiverType = scope.getType(typeName)
if receiverType == nil {
// Add type if necessary, so method can be registered
scope.sym[typeName] = &Symbol{kind: Typ, typ: &Type{}}
receiverType = scope.sym[typeName].typ
}

View File

@@ -1499,6 +1499,28 @@ type Coord struct {
// 25
}
func Example_method11() {
src := `
package main
func main() {
o := &Coord{3, 4}
println(o.dist())
}
func (c *Coord) dist() int { return c.x*c.x + c.y*c.y }
type Coord struct {
x, y int
}
`
i := NewInterpreter(Opt{Entry: "main"})
i.Eval(src)
// Output:
// 25
}
func Example_method2() {
src := `
package main