Created
August 2, 2016 03:38
-
-
Save sethmcl/6056556d9ae4123c462c911095a81201 to your computer and use it in GitHub Desktop.
Print ast node types using golang with otto
This file contains hidden or 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 parse | |
| import ( | |
| "fmt" | |
| "github.com/robertkrimen/otto/ast" | |
| "github.com/robertkrimen/otto/parser" | |
| "io/ioutil" | |
| "reflect" | |
| ) | |
| func ParseFile(filename string) error { | |
| src, err := ioutil.ReadFile(filename) | |
| if err != nil { | |
| return err | |
| } | |
| program, err := parser.ParseFile(nil, filename, src, parser.StoreComments) | |
| if err != nil { | |
| return err | |
| } | |
| for _, node := range program.Body { | |
| fmt.Printf("Node type: %s\n", getNodeType(node)) | |
| } | |
| return nil | |
| } | |
| func isExpressionStatement(node ast.Node) bool { | |
| return getNodeType(node) == "ExpressionStatement" | |
| } | |
| func isFunctionStatement(node ast.Node) bool { | |
| return getNodeType(node) == "FunctionStatement" | |
| } | |
| func getNodeType(node ast.Node) string { | |
| val := reflect.ValueOf(node).Elem() | |
| return val.Type().Name() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment