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

💡Manipulating ASTs

The go-fAST library provides a powerful and flexible mechanism to walk and transform Abstract Syntax Trees (ASTs). This guide explains how you can safely and correctly modify ASTs during traversal using custom visitors.

💡 Key Concepts

Node Replacement Rules

When modifying the AST, it’s critical that replacement nodes conform to the expected type. For example:

  • You can replace an *ast.Expression with another *ast.Expression wrapping a different inner Expr.

  • Since you must replace nodes with their equivilent types, as an example what you cannot do is replace an *ast.ForStatement with an *ast.Identifier.

Statement vs Expression

All nodes in the AST are either:

  • A statement, implementing the ast.Stmt interface.

  • An expression, implementing the ast.Expr interface.

Always ensure you're replacing nodes with compatible interface types.

🔁 Example: Replacing Number Literals with Strings

Below is an example demonstrating how to replace every number literal with a string literal containing "foo":

goCopyEdittype ExampleVisitor struct {
    ast.NoopVisitor
}

func (v *ExampleVisitor) VisitExpression(n *ast.Expression) {
    // Step 1: Visit child expressions first
    n.VisitChildrenWith(v)

    // Step 2: Check if this is a number literal
    _, isNumberLiteral := n.Expr.(*ast.NumberLiteral)
    if !isNumberLiteral {
        return // Not a number literal; no replacement needed
    }

    // Step 3: Create a new string literal expression
    replacement := "foo"
    *n = ast.Expression{
        Expr: &ast.StringLiteral{
            Value:   replacement,
        },
    }
}

🔍 Input JavaScript (Before Visitor)

🔄 Transformed JavaScript (After Visitor)

Notes:

  • The VisitChildrenWith(v) call ensures recursive traversal before mutation (to ensure children of this Expression are visited and replaced)

  • The replacement assigns directly to *n, ensuring the parent retains the correct *ast.Expression type.

Statement & Expression Types

If a node is a statement, it will implement the ast.Stmt interface. If it is an expression, it will implement the ast.Expr interface.

Last updated