Fix method resolution with pointers
This commit is contained in:
15
_test/method11.go
Normal file
15
_test/method11.go
Normal 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
|
||||||
@@ -48,13 +48,20 @@ func (interp *Interpreter) Gta(root *Node) {
|
|||||||
typeName = receiver.child[1].ident
|
typeName = receiver.child[1].ident
|
||||||
}
|
}
|
||||||
if typeName == "" {
|
if typeName == "" {
|
||||||
|
// The receiver is a pointer, retrieve typeName from indirection
|
||||||
typeName = receiver.child[1].child[0].ident
|
typeName = receiver.child[1].child[0].ident
|
||||||
elemtype := scope.getType(typeName)
|
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}
|
receiverType = &Type{cat: PtrT, val: elemtype}
|
||||||
elemtype.method = append(elemtype.method, n)
|
elemtype.method = append(elemtype.method, n)
|
||||||
} else {
|
} else {
|
||||||
receiverType = scope.getType(typeName)
|
receiverType = scope.getType(typeName)
|
||||||
if receiverType == nil {
|
if receiverType == nil {
|
||||||
|
// Add type if necessary, so method can be registered
|
||||||
scope.sym[typeName] = &Symbol{kind: Typ, typ: &Type{}}
|
scope.sym[typeName] = &Symbol{kind: Typ, typ: &Type{}}
|
||||||
receiverType = scope.sym[typeName].typ
|
receiverType = scope.sym[typeName].typ
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1499,6 +1499,28 @@ type Coord struct {
|
|||||||
// 25
|
// 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() {
|
func Example_method2() {
|
||||||
src := `
|
src := `
|
||||||
package main
|
package main
|
||||||
|
|||||||
Reference in New Issue
Block a user