Skip to content

Instantly share code, notes, and snippets.

@sethmcl
Created August 2, 2016 03:38
Show Gist options
  • Select an option

  • Save sethmcl/6056556d9ae4123c462c911095a81201 to your computer and use it in GitHub Desktop.

Select an option

Save sethmcl/6056556d9ae4123c462c911095a81201 to your computer and use it in GitHub Desktop.
Print ast node types using golang with otto
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