Skip to content

Commit 5bf7d00

Browse files
committed
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 <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]>
1 parent 283fce2 commit 5bf7d00

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

cmd/callgraph/main.go

+20-4
Original file line numberDiff line numberDiff line change
@@ -109,9 +109,20 @@ Flags:
109109
110110
Caller and Callee are *ssa.Function values, which print as
111111
"(*sync/atomic.Mutex).Lock", but other attributes may be
112-
derived from them, e.g. Caller.Pkg.Pkg.Path yields the
113-
import path of the enclosing package. Consult the go/ssa
114-
API documentation for details.
112+
derived from them. For example:
113+
114+
- {{.Caller.Pkg.Pkg.Path}} yields the import path of the
115+
enclosing package; and
116+
117+
- {{(.Caller.Prog.Fset.Position .Caller.Pos).Filename}}
118+
yields the name of the file that declares the caller.
119+
120+
- The 'posn' template function returns the token.Position
121+
of an ssa.Function, so the previous example can be
122+
reduced to {{(posn .Caller).Filename}}.
123+
124+
Consult the documentation for go/token, text/template, and
125+
golang.org/x/tools/go/ssa for more detail.
115126
116127
Examples:
117128
@@ -238,7 +249,12 @@ func doCallgraph(dir, gopath, algo, format string, tests bool, args []string) er
238249
format = ` {{printf "%q" .Caller}} -> {{printf "%q" .Callee}}`
239250
}
240251

241-
tmpl, err := template.New("-format").Parse(format)
252+
funcMap := template.FuncMap{
253+
"posn": func(f *ssa.Function) token.Position {
254+
return f.Prog.Fset.Position(f.Pos())
255+
},
256+
}
257+
tmpl, err := template.New("-format").Funcs(funcMap).Parse(format)
242258
if err != nil {
243259
return fmt.Errorf("invalid -format template: %v", err)
244260
}

0 commit comments

Comments
 (0)