I'm trying to list all function call in a function using ast. But having trouble understanding how it is suppose to be used. I have been able to get this far.
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)
}
}
I have inspected funcs. I get to funcs[n1].Body.List[n2]
.
But after this i don't understand how i'm suppose to read the underlaying data.X.Fun.data.Sel.name
(got it from evaluation in gogland) to get name of the function being called.
Ok so what i found is that you have to a lot of casting to actually extract the data.
Here is an example on how to do extract the func call in a 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
}
}
}
}
}
I also found this with kind of help with finding out what you need to cast it to. http://goast.yuroyoro.net/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With