Created
August 2, 2013 17:48
-
-
Save icholy/6141864 to your computer and use it in GitHub Desktop.
playing around with go's ast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"go/ast" | |
"go/parser" | |
"go/token" | |
) | |
const src = ` | |
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func main() { | |
fmt.Println(math.Pi) | |
} | |
` | |
type Dependencies struct { | |
Packages map[string][]string | |
} | |
func (d *Dependencies) Has(p, n string) bool { | |
if pk, ok := d.Packages[p]; ok { | |
for _, name := range pk { | |
if n == name { | |
return true | |
} | |
} | |
} | |
return false | |
} | |
func (d *Dependencies) Visit(node ast.Node) ast.Visitor { | |
switch v := node.(type) { | |
case *ast.SelectorExpr: | |
var p string | |
if ident, ok := v.X.(*ast.Ident); ok { | |
p = ident.Name | |
} else { | |
break | |
} | |
n := v.Sel.Name | |
if pk, ok := d.Packages[p]; ok { | |
if !d.Has(p, n) { | |
d.Packages[p] = append(pk, n) | |
} | |
} else { | |
d.Packages[p] = []string{n} | |
} | |
} | |
return ast.Visitor(d) | |
} | |
func main() { | |
// src is the input for which we want to print the AST. | |
// Create the AST by parsing src. | |
fset := token.NewFileSet() // positions are relative to fset | |
f, err := parser.ParseFile(fset, "", src, 0) | |
if err != nil { | |
panic(err) | |
} | |
v := &Dependencies{make(map[string][]string)} | |
ast.Walk(v, f) | |
fmt.Printf("%#v", *v) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment