Fro*_*gon 6 abstract-syntax-tree go
我正在尝试使用ast列出函数中的所有函数调用.但无法理解如何使用它.我已经能够做到这一点.
set := token.NewFileSet()
packs, err := parser.ParseFile(set, serviceFile, nil, 0)
if err != nil {
fmt.Println("Failed to parse package:", err)
os.Exit(1)
}
funcs := []*ast.FuncDecl{}
for _, d := range packs.Decls {
if fn, isFn := d.(*ast.FuncDecl); isFn {
funcs = append(funcs, fn)
}
}
Run Code Online (Sandbox Code Playgroud)
我检查了功能.我到了funcs[n1].Body.List[n2].但在此之后,我不明白我是如何阅读底层的data.X.Fun.data.Sel.name(从gogland的评估中得到它)来获取被调用函数的名称.
好吧,我发现你必须进行大量的转换才能真正提取数据。
以下是有关如何在 func 中提取 func 调用的示例。
for _, function := range funcs {
extractFuncCallInFunc(function.Body.List)
}
func extractFuncCallInFunc(stmts []ast.Stmt) {
for _, stmt := range funcs {
if exprStmt, ok := stmt.(*ast.ExprStmt); ok {
if call, ok := exprStmt.X.(*ast.CallExpr); ok {
if fun, ok := call.Fun.(*ast.SelectorExpr); ok {
funcName := fun.Sel.Name
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我还发现这对找出您需要将其投射到的内容有一定帮助。 http://goast.yuroyoro.net/