From Binary Trees to ASTs: Parsing and Traversing Code
I was exploring the source code of SQLc, which used to make Go code from sql queries.
SQLc generates code using AST (Abstract Syntax Trees) so i started learing about it.
But while learning about AST, I started revising Binary Trees again.
In a generic tree, a node can have multiple children.
But in a binary tree, every node can have at most two children:
- Left child
- Right child
A node can have zero, one, or two children.
Nodes also have relationships:
- Parent: A node directly above another node.
- Child: A node directly below its parent.
- Siblings: Two nodes that share the same parent.
For example:
A
↙ ↘
B C
Here, A is the parent, while B and C are its children and siblings to each other.
There’s also something called a subtree.
A subtree is a tree formed by taking a node and all its descendants.
For example, B and everything below it form a subtree of A.
One interesting thing: ASTs use tree structures to represent source code.
An expression like a + b * c can be represented as a tree where operators and operands become nodes.
Understanding trees makes it much easier to understand how compilers and tools like SQL parsers work.
Back to the basics 🙂
With the tree basics fresh again, I went back to my original question: what exactly is an AST?
So I read about AST (Abstract Syntax Tree).
AST is an intermediate representation of source code in a tree structure.
Simply, compilers don’t directly understand source code as plain text. They parse the code and convert its structure into an AST, making it easier to analyze, understand relationships between expressions, and perform further compilation steps.
A compiler has two main parts:
Frontend: Reads and understands the source code.
Backend: Takes the representation produced by the frontend and generates machine code.
The frontend reads the raw code and creates a tree representation (AST) so the next stages of the compiler can work with it.
Means:
Your code → Compiler frontend reads it → Creates an AST → Backend processes it → Machine code.
There are many tools built with this concept that we use eveyday, not just language compilers. For example, Prettier, Oxlint, and Babel.
If you’ve worked with the JS ecosystem, especially React, you might have come across Babel.
What does Babel do? It takes the latest JavaScript syntax you write and transforms it into code that is compatible with older browsers.
But why does an AST use a tree structure and not something else? 🤔
Because nesting and operator precedence become explicit in a tree structure.
Go also provides standard libraries (like go/ast, go/perser, go/token almost everything..) to experiment with and build tools around ASTs.
One thing I’ve realized is how important these things are in our daily development, yet we’re often unaware of how they work behind the scenes.
Hats off to the programmers who built these things without Claude. 😂
Ok, enough theory. Let’s see how this works in Go.
I’ve been reading Go AST docs to play around with ASTs in Go.
In a binary tree, just like siblings, we have ancestors too.
Simply put, a node’s ancestors are its parent, grandparent, great-grandparent, and so on.
For example, if A is the parent of B and B is the parent of C, then the ancestors of C are B and A.
Ancestor: Parent, grandparent, great-grandparent, and so on.
Go’s ast package provides a very important method called Inspect.
We can use it to traverse the AST of the source code. It traverses in Depth-First Order.
ast.Inspect(node, func(n ast.Node) bool {...})
- The first argument is the starting node from where we start traversing.
- The second argument is a callback function that runs while visiting all the nodes.
ast.Node is an interface provided by Go. So, the node can be nil too.
After visiting all the children, it calls the callback function with nil (f(nil)).
That’s why, in the callback, we need to first check if the node is nil, otherwise it can trigger a panic.
But how do we get the starting node? 🤔
Go provides token package,
Using token.NewFileSet(), we can create an empty file set.
Then, using parser.ParseFile(fset, "demo.go", src, 0), we can parse our source code. It returns the node that we can use to inspect the whole AST.
We may not need the Inspect method in every case because, since Go 1.23, Go provides Preorder and PreorderStack, which are more convenient to use.
Preorder returns an iterator that takes a root node as an argument.
This is useful because:
- We don’t need to check for nil.
- We can instantly break if we find our target node.
But there’s one limitation: you can’t skip any subtree.
Getting the node isn’t enough every time. We need the full context of a node, like its parent, ancestors, and so on.
That’s where PreorderStack is useful.
It provides the full context of the node. It also works like the Inspect method, where you can use a callback function and return a boolean to skip a subtree.