Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use ast to get all function calls in a function

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.

like image 754
Icy Creature Avatar asked Sep 08 '17 11:09

Icy Creature


1 Answers

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/

like image 144
Icy Creature Avatar answered Sep 24 '22 03:09

Icy Creature