I'm attempting to do some static analysis on function calls in a Go project using the go/parse
, go/token
and go/ast
modules, but I can't figure out how to determine the type of a given ast.Ident
object.
For instance if parse something like this:
textToContain := bytes.NewBuffer([]byte{})
// lots of other code
text := textToContain.String() // <- I care about this function call
(this is parsed from here: file)
EDIT: It took a lot of code to parse this so I didn't post it here, but you can find it as a gist at: https://gist.github.com/EricChiang/6735340c5fa3d2de2b73
I get the following code printed using the ast.Print
function
0 *ast.CallExpr {
1 . Fun: *ast.SelectorExpr {
2 . . X: *ast.Ident {
4 . . . Name: "textToContain"
5 . . . Obj: *ast.Object {
6 . . . . Kind: var
7 . . . . Name: "textToContain"
8 . . . . Decl: *ast.AssignStmt {
9 . . . . . Lhs: []ast.Expr (len = 1) {
10 . . . . . . 0: *ast.Ident {
12 . . . . . . . Name: "textToContain"
13 . . . . . . . Obj: *(obj @ 5)
14 . . . . . . }
15 . . . . . }
17 . . . . . Tok: :=
18 . . . . . Rhs: []ast.Expr (len = 1) {
19 . . . . . . 0: *ast.CallExpr {
20 . . . . . . . Fun: *ast.SelectorExpr {
21 . . . . . . . . X: *ast.Ident {
23 . . . . . . . . . Name: "bytes"
24 . . . . . . . . }
25 . . . . . . . . Sel: *ast.Ident {
27 . . . . . . . . . Name: "NewBuffer"
28 . . . . . . . . }
29 . . . . . . . }
31 . . . . . . . Args: []ast.Expr (len = 1) {
32 . . . . . . . . 0: *ast.CompositeLit {
33 . . . . . . . . . Type: *ast.ArrayType {
35 . . . . . . . . . . Elt: *ast.Ident {
37 . . . . . . . . . . . Name: "byte"
38 . . . . . . . . . . }
39 . . . . . . . . . }
42 . . . . . . . . }
43 . . . . . . . }
44 . . . . . . . Ellipsis: -
46 . . . . . . }
47 . . . . . }
48 . . . . }
49 . . . }
50 . . }
51 . . Sel: *ast.Ident {
53 . . . Name: "String"
54 . . }
55 . }
57 . Ellipsis: -
59 }
But I can't see where I could infer the type of textToContain
I know a bunch of tools that can do this, for instance this example from the go blog, but I think I'm going in the wrong direction.