Example of Traversing AST Objects Using a User-defined Access Function

Defining the behavior of accessing the variable declaration node: Inherit Visitor, re-write the access function, find the undefined variable, and store lexical units of the variable.

import std.ast.*

class MyVisitor <: Visitor {
    public var unitializedVars = Tokens() // Stores the lexical units of the variable.
    override public func visit(varDecl: VarDecl) {
        try {
            varDecl.expr
        } catch (e: ASTException) {
            unitializedVars.append(varDecl.identifier)
        }
        breakTraverse() // The subnodes of **varDecl** are not traversed.
        return
    }
}

main(): Int64 {
    let input = quote(
        var a : Int64
    )
    let varDecl = parseDecl(input)
    let visitor = MyVisitor() // The processing for the **varDecl** node is defined in **MyVisitor**.
    varDecl.traverse(visitor) // Processes the **varDecl** node.
    println("Unitialized VarDecl size is ${visitor.unitializedVars.size}")
    0
}

Running result:

Unitialized VarDecl size is 1