How to get the methods list for each struct in golang.org/x/tools/go/ssa?

135 views
Skip to first unread message

Xudong SUN

unread,
Jul 24, 2020, 5:44:08 PM7/24/20
to golang-nuts
Hello everyone,

I am trying to use golang.org/x/tools/go/ssa to get the methods list of each struct type when doing static analysis on Kubernetes.
This is the code I wrote to print out the method sets for each struct or interface type.

cfg := packages.Config{Mode: packages.LoadAllSyntax}
initial, err := packages.Load(&cfg, pattern)
if err != nil {
   
log.Fatal(err)
}
prog, _ := ssautil.AllPackages(initial, 0)
prog.Build()

for _, pkg := range prog.AllPackages() {
   
if pkg.Pkg.Path() == pattern {
     
for _, member := range pkg.Members {
         fmt
.Println(member)
         
if m, ok := member.(*ssa.Type); ok {
           
fmt.Println(prog.MethodSets.MethodSet(m.Type()))
         
}
     
}
   
}
}


I checked everything printed by fmt.Println(member) but it only contains the pkg-level functions instead of struct methods.
I also checked everything printed by fmt.Println(prog.MethodSets.MethodSet(m.Type())) and the method set for each struct/interface only contains the abstract methods and their implementations. Many other methods (which are not the implementation of some abstract methods) are missing here.

In one word, I am able to get all the pkg-level functions in the program but I am NOT able the get the complete method list of any struct type in the program.

Here is what I want:
I want to get the complete method list (a list of *ssa.Function pointing to the method) by calling some API with the struct type (or name)

I googled around and read the related documents here: https://pkg.go.dev/golang.org/x/tools/go/ssa?tab=doc but didn't find any clue to solve the problem.
I also read the golang.org/x/tools/go/ssa code but failed to find any API to do so.

Could anyone help to let me know how to do solve it in golang.org/x/tools/go/ssa?
Thank you so much!








xudongsun...@gmail.com

unread,
Jul 26, 2020, 12:31:25 PM7/26/20
to golang-nuts
The reason may be that I was using

prog.MethodSets.MethodSet(m.Type())

However, in golang the receiver of a method could be a struct type or a pointer to a struct type.
If the receiver of the method is a pointer, then only

prog.MethodSets.MethodSet(types.NewPointer(tm.Type()))

can return the methods.
Reply all
Reply to author
Forward
0 new messages