From 248c4de29c0ca3000df55ebe8ae42e0a2a465392 Mon Sep 17 00:00:00 2001 From: luoliwoshang <2643523683@qq.com> Date: Tue, 30 Apr 2024 09:51:52 +0800 Subject: [PATCH] test:info.OverloadOf --- x/typesutil/check_test.go | 72 +++++++++++++++++++++++++++++++++++++++ x/typesutil/gopinfo.go | 9 +++-- 2 files changed, 78 insertions(+), 3 deletions(-) diff --git a/x/typesutil/check_test.go b/x/typesutil/check_test.go index e933a3b26..86f8a6674 100644 --- a/x/typesutil/check_test.go +++ b/x/typesutil/check_test.go @@ -196,3 +196,75 @@ func TestBadFile(t *testing.T) { _ = checker.Files([]*goast.File{{Name: goast.NewIdent("main")}}, []*ast.File{{Name: ast.NewIdent("main")}}) } + +func TestCheckOverload(t *testing.T) { + fset := token.NewFileSet() + info, ginfo, err := checkFiles(fset, "main.gop", ` +type foo struct { +} + +func (a *foo) mulInt(b int) *foo { + return a +} + +func (a *foo) mulFoo(b *foo) *foo { + return a +} + +func (foo).mul = ( + (foo).mulInt + (foo).mulFoo +) +func addInt0() { +} + +func addInt1(i int) { +} + +func addInt2(i, j int) { +} + +var addInt3 = func(i, j, k int) { +} + +func add = ( + addInt0 + addInt1 + addInt2 + addInt3 + func(a, b string) string { + return a + b + } +) + +var a, b *foo +var c = a.mul(100) +var d = a.mul(c) + +func init() { + add 100, 200 + add 100, 200, 300 + add("hello", "world") +} +`, "", "", "", "") + if err != nil || info == nil || ginfo == nil { + t.Fatalf("check failed: %v", err) + } + for use, ovDeclObj := range info.Overloads { + o := info.ObjectOf(use) + declObj, ovObjs := info.OverloadOf(use) + if ovDeclObj != declObj { + t.Fatal("bad overload", o) + } + found := false + for _, ovObj := range ovObjs { + if o == ovObj { + found = true + break + } + } + if !found { + t.Fatal("bad overload", o) + } + } +} diff --git a/x/typesutil/gopinfo.go b/x/typesutil/gopinfo.go index e0fb06622..d1ff9a79d 100644 --- a/x/typesutil/gopinfo.go +++ b/x/typesutil/gopinfo.go @@ -170,9 +170,12 @@ func (info *Info) TypeOf(e ast.Expr) types.Type { // Returns the overloaded function declaration corresponding to the ident and its overloaded function members func (info *Info) OverloadOf(id *ast.Ident) (types.Object, []types.Object) { - if sig, ok := info.Overloads[id].Type().(*types.Signature); ok { - if _, objs := gogen.CheckSigFuncExObjects(sig); len(objs) > 1 { - return info.Overloads[id], objs + overdecl := info.Overloads[id] + if overdecl != nil { + if sig, ok := overdecl.Type().(*types.Signature); ok { + if _, objs := gogen.CheckSigFuncExObjects(sig); len(objs) > 1 { + return overdecl, objs + } } } return nil, nil