finding the call graph of a method

267 views
Skip to first unread message

Jochen Voss

unread,
Apr 18, 2023, 3:34:30 PM4/18/23
to golang-nuts
Dear all,

I'm trying to find the callgraph of a method, using the following code:

package main

import (
"log"

"golang.org/x/tools/go/callgraph"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/go/ssa/ssautil"
)

func main() {
cfg := &packages.Config{Mode: packages.LoadSyntax}
initial, err := packages.Load(cfg, "seehuhn.de/go/pdf")
if err != nil {
log.Fatal(err)
} else if packages.PrintErrors(initial) > 0 {
log.Fatalf("packages contain errors")
}

prog, pkgs := ssautil.Packages(initial, 0)
if len(pkgs) != 1 {
log.Fatalf("expected 1 package, got %d", len(pkgs))
}
pkg := pkgs[0]
pkg.Build()

reader := pkg.Members["Reader"]

f := prog.LookupMethod(reader.Type(), pkg.Pkg, "readXRef")
g := callgraph.New(f)
_ = g
}

(Also on the playgound at https://go.dev/play/p/_S-oKAJ6YNO, but resulting in some fancy error messages there.)

This fails with the following error message: panic: seehuhn.de/go/pdf.Reader has no method seehuhn.de/go/pdf.readXRef

What am I doing wrong?

All the best,
Jochen

Jochen Voss

unread,
Apr 19, 2023, 4:45:06 AM4/19/23
to golang-nuts
Ah, found it!  If I write types.NewPointer(reader.Type()) instead of just reader.Type(), things work better.
Reply all
Reply to author
Forward
0 new messages