Go lang compiler is written in Go, so parsing source code and AST are available as packages.
Getting AST is "one line of code"
But the AST is using recursive pointers, and serializing to JSON requires some extra effort.
Here is a useful tool for that:
asty-org/asty: Converts golang AST to JSON and JSON to AST @GitHub
AST → JSON | JSON → AST
Marshals golang AST into JSON and unmarshals it back from JSON.
It allows building pattern matching, statistical analysis, language transformation, search/data-mine/anything algorithms for golang with any other language (I like to do it with python. Check out asty-python)
Demo:
Go-to-AST-JSON: Convert Go to AST-JSON instantly
how it works
Analyzing AST in Go with JSON tools - DEV Community
Basic AST Traversal in Go - zupzup
Here is a minimalistic example of using Go AST
Abstract syntax tree - Wikipedia
An abstract syntax tree (AST) is a data structure used in computer science to represent the structure of a program or code snippet. It is a tree representation of the abstract syntactic structure of text (often source code) written in a formal language. Each node of the tree denotes a construct occurring in the text. It is sometimes called just a syntax tree.
No comments:
Post a Comment