🌳Depth-First Traversal
Depth-First Traversal in AST
Depth-first traversal is a method of exploring a tree structure, such as an Abstract Syntax Tree (AST), by diving deep into each branch before backtracking. In go-fAST, this is the default traversal strategy used when implementing custom visitors.
This page walks through what depth-first traversal means in practice, using a JavaScript example and mapping it to the order of AST node visitation.
📘 What It Means
In a depth-first traversal:
You visit a node
Then recursively visit its children
Then move on to the next sibling
This pattern is ideal for AST processing because it naturally follows the syntactic structure of code.
📄 JavaScript Example
Here’s a simple JavaScript program:
var a = 1;
var b = 2;
function foo(d, e) {
return d + e;
}
console.log(foo(a, b));🔍 Traversal Order
The depth-first traversal would look like this:
Program (root)
VariableDeclaration (var a = 1)
VariableDeclarator
Identifier
aNumberLiteral
1
VariableDeclaration (var b = 2)
VariableDeclarator
Identifier
bNumberLiteral
2
FunctionDeclaration
fooIdentifier
fooParameterList
Identifier
dIdentifier
e
BlockStatement
ReturnStatement
BinaryExpression
d + eIdentifier
dIdentifier
e
ExpressionStatement (console.log(...))
CallExpression
MemberExpression
console.logIdentifier
consoleIdentifier
log
Arguments
CallExpression
foo(a, b)Identifier
fooIdentifier
aIdentifier
b
💡 Visualization Tip
Imagine the tree as a nested structure:
✅ Summary
go-fAST performs depth-first traversal by default via
VisitWith()This means each node is visited before its siblings, and all its children are visited first
Last updated