AST Object Operation Example

After a node of the ClassDecl type is obtained, the node can be added, deleted, modified, and queried. The code is as follows:

import std.ast.*
main() {
    let input: Tokens = quote(
        class Data {
            var a: Int32
            init(a_: Int32) {
                a = a_
            }
        }
    )
    let decl = parseDecl(input) // Obtains a **Decl** declaration node.
    var classDecl = match (decl as ClassDecl) { // Performs type conversion on **decl**, of which the specific type is **ClassDecl**.
        case Some(v) => v
        case None => throw Exception()
    }
    var identifier = classDecl.identifier
    // Adds a function to the node for obtaining the value of **a**.
    var funcdecl = FuncDecl(quote(func getValue() {a}))
    classDecl.body.decls.append(funcdecl)
    println("Identifier value is ${identifier.value}")
    println("ClassDecl body size is ${classDecl.body.decls.size}")
    0
}

Running result:

Identifier value is Data
ClassDecl body size is 3