Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

🌳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:

  1. Program (root)

  2. VariableDeclaration (var a = 1)

    • VariableDeclarator

      • Identifier a

      • NumberLiteral 1

  3. VariableDeclaration (var b = 2)

    • VariableDeclarator

      • Identifier b

      • NumberLiteral 2

  4. FunctionDeclaration foo

    • Identifier foo

    • ParameterList

      • Identifier d

      • Identifier e

    • BlockStatement

      • ReturnStatement

        • BinaryExpression d + e

          • Identifier d

          • Identifier e

  5. ExpressionStatement (console.log(...))

    • CallExpression

      • MemberExpression console.log

        • Identifier console

        • Identifier log

      • Arguments

        • CallExpression foo(a, b)

          • Identifier foo

          • Identifier a

          • Identifier 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