From 5bf7d005299769e9d476813f09efd2a4296d5fe9 Mon Sep 17 00:00:00 2001 From: Alan Donovan Date: Thu, 29 Feb 2024 08:13:55 -0500 Subject: [PATCH] cmd/callgraph: add 'posn' template helper 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 LUCI-TryBot-Result: Go LUCI --- cmd/callgraph/main.go | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/cmd/callgraph/main.go b/cmd/callgraph/main.go index 33f7dfa8098..7853826b8fc 100644 --- a/cmd/callgraph/main.go +++ b/cmd/callgraph/main.go @@ -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: @@ -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) }