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

🧱Visitor API

The visitor API is the core mechanism for traversing and transforming ASTs in go-fAST. It allows you to declaratively walk the tree and perform logic at each node type.

This page explains how the visitor pattern works, how to define your own visitor, and gives examples of common traversal use cases.


🧱 Visitor Interface

The Visitor interface defines a method for every AST node type. Implement any subset of these methods in your own struct to perform custom logic when those node types are encountered.

type Visitor interface {
    VisitProgram(*ast.Program)
    VisitIdentifier(*ast.Identifier)
    VisitExpression(*ast.Expression)
    VisitIfStatement(*ast.IfStatement)
    VisitVariableDeclaration(*ast.VariableDeclaration)
    // ...and so on for all supported nodes
}

You don’t need to implement all methods—only those you're interested in. You can embed ast.NoopVisitor to automatically forward unimplemented visits to children.

✨ Example: Logging All Identifiers

type IdentifierPrinter struct {
    ast.NoopVisitor
}

func (v *IdentifierPrinter) VisitIdentifier(n *ast.Identifier) {
    fmt.Println("Found identifier:", n.Name)
}

func main() {
    src := `let a = b + c;`
    p, _ := parser.ParseFile(src)
    
    visitor := &IdentifierPrinter{}
    visitor.V = visitor
    p.VisitWith(visitor)
}

This will print:


🪄 Example: Collecting All Literals

🔁 Recursive Traversal

The VisitChildrenWith(visitor) method is available on every node, and called automatically by the default NoopVisitor implementation.

You may override it if you need to:

  • Modify traversal order (e.g. pre-order vs post-order)

  • Short-circuit based on conditions

🔍 Full List of Visitor Methods

The following are all available visitor methods you can override in your own struct:

💡 Tip: Look at ast/gen_visit.go or use NoopVisitor as a reference for the full set.

Last updated