Use ast to get all function calls in a function

I am trying to list the entire function call in a function using ast. But not understanding how it should be used. I could go that 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 checked the funky. I get to funcs[n1].Body.List[n2]. But after that, I don’t understand how I should read the litter data.X.Fun.data.Sel.name(obtained from the assessment in the hogland) to get the name of the function being called.

+4
source share
2 answers

Ok, so I found that you need a lot of casting to extract the data.

Here is an example of how to make a func call in 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 some help to figure out what you need to do. http://goast.yuroyoro.net/

0

ast.Inspect node.

for _, fun := range funcs {
    ast.Inspect(fun, func(node ast.Node) bool {
        switch n := node.(type) {
            case *ast.CallExpr:
                fmt.Println(n) // prints every func call expression
        }
        return true
    })
}
0

Source: https://habr.com/ru/post/1685301/


All Articles