Skip to content

Commit

Permalink
cmd/callgraph: add 'posn' template helper
Browse files Browse the repository at this point in the history
This change adds a helper function to the template environment
to make it easier to compute the token.Position of an ssa Function.

Also, improve the documentation.

Fixes golang/go#65980

Change-Id: I16d4cc87bb6f96985684da5ce027be296f22a601
Reviewed-on: https://go-review.googlesource.com/c/tools/+/567838
Reviewed-by: Robert Findley <rfindley@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
  • Loading branch information
adonovan committed Feb 29, 2024
1 parent 283fce2 commit 5bf7d00
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions cmd/callgraph/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,20 @@ Flags:
Caller and Callee are *ssa.Function values, which print as
"(*sync/atomic.Mutex).Lock", but other attributes may be
derived from them, e.g. Caller.Pkg.Pkg.Path yields the
import path of the enclosing package. Consult the go/ssa
API documentation for details.
derived from them. For example:
- {{.Caller.Pkg.Pkg.Path}} yields the import path of the
enclosing package; and
- {{(.Caller.Prog.Fset.Position .Caller.Pos).Filename}}
yields the name of the file that declares the caller.
- The 'posn' template function returns the token.Position
of an ssa.Function, so the previous example can be
reduced to {{(posn .Caller).Filename}}.
Consult the documentation for go/token, text/template, and
golang.org/x/tools/go/ssa for more detail.
Examples:
Expand Down Expand Up @@ -238,7 +249,12 @@ func doCallgraph(dir, gopath, algo, format string, tests bool, args []string) er
format = ` {{printf "%q" .Caller}} -> {{printf "%q" .Callee}}`
}

tmpl, err := template.New("-format").Parse(format)
funcMap := template.FuncMap{
"posn": func(f *ssa.Function) token.Position {
return f.Prog.Fset.Position(f.Pos())
},
}
tmpl, err := template.New("-format").Funcs(funcMap).Parse(format)
if err != nil {
return fmt.Errorf("invalid -format template: %v", err)
}
Expand Down

0 comments on commit 5bf7d00

Please sign in to comment.