打印Go调用树



给定这样的文件:

package main
func A() {}
func B() {
A()
}
func C() {
A()
}
func D() {
B()
}
func E() {
B()
}
func F() {
C()
}
func G() {
C()
}
func main() {
D()
E()
F()
G()
}

我想打印一个程序的调用树,像这样:

main
D
B
A
E
B
A
F
C
A
G
C
A

我找到了callgraph程序[1],但它没有创建树:

PS C:prog> callgraph .
prog.A  --static-4:5--> prog.C
prog.A  --static-5:5--> prog.D
prog.main       --static-19:5-->        prog.A
prog.B  --static-9:5--> prog.E
prog.B  --static-10:5-->        prog.F
prog.main       --static-20:5-->        prog.B

有什么方法可以做到这一点吗?

  1. https://github.com/golang/tools/blob/master/cmd/callgraph

所以我确实找到了一个包,它似乎可以处理从命令行[1]。然而,我又想了想,还有一棵印刷的树可能不是解决我问题的最佳方案。我想做的是返回我的一个函数出错。然而,要做到这一点,我需要宣传错误一直到main。因为这可能有好几层,我想如果我从main开始,一路努力达到所需的效果,那将是最好的作用这样,如果需要的话,我可以分阶段进行工作。问题是,我该怎么做得到这些函数的有序列表吗?我用tsort[2]找到了一个解决方案:

PS C:> callgraph -format digraph . | coreutils tsort
"init/test.main"
"init/test.D"
"init/test.E"
"init/test.F"
"init/test.G"
"init/test.B"
"init/test.C"
"init/test.A"

但我可能并不总是想要整个调用图。接下来我想添加panic:

func A() {
panic(1)
}

但这不会为您提供所有分支,只会提供指向目标的第一条路径功能:

main.A(...)
C:/test.go:4
main.B(...)
C:/test.go:8
main.D(...)
C:/test.go:16
main.main()
C:/test.go:32 +0x45

最后,我编写了自己的排序函数,将任意目的地作为输入,并按从CCD_ 6到目标函数的顺序打印所有路径

package main
func tsort(graph map[string][]string, end string) []string {
var (
b = make(map[string]bool)
l []string
s = []string{end}
)
for len(s) > 0 {
n := s[len(s) - 1]
b[n] = true
for _, m := range graph[n] {
if ! b[m] {
s = append(s, m)
}
}
if s[len(s) - 1] == n {
s = s[:len(s) - 1]
l = append(l, n)
}
}
return l
}

示例:

package main
import (
"bytes"
"fmt"
"os/exec"
)
func main() {
b := new(bytes.Buffer)
c := exec.Command("callgraph", "-format", "digraph", ".")
c.Stdout = b
c.Run()
m := make(map[string][]string)
for {
var parent, child string
_, e := fmt.Fscanln(b, &parent, &child)
if e != nil { break }
m[child] = append(m[child], parent)
}
for n, s := range tsort(m, `"init/test.A"`) {
fmt.Print(n+1, ". ", s, "n")
}
}

结果:

1. "init/test.main"
2. "init/test.G"
3. "init/test.F"
4. "init/test.C"
5. "init/test.D"
6. "init/test.E"
7. "init/test.B"
8. "init/test.A"
  1. https://github.com/soniakeys/graph/blob/master/treevis/treevis.go
  2. https://github.com/uutils/coreutils

最新更新