DevOps / Apache Groovy Interview questions
Explain the lifecycle of an AST transformation during Groovy compilation?
Groovy's compiler processes source code through several sequential phases - initialization, parsing, and building an initial Abstract Syntax Tree (AST) that represents the program's structure before any transformation-specific work happens.
Local AST transformations, triggered by an annotation like @ToString placed directly on a class, are registered to run at a specific compilation phase, commonly CANONICALIZATION, and are invoked by the compiler once the AST reaches that phase, receiving a reference to the relevant AST node - the annotated class - to modify.
The transformation implementation directly manipulates the AST - for example, @ToString's transformation adds a new MethodNode representing a generated toString() method into the class's AST - as ordinary tree edits, not as source-code string generation.
Because this happens before bytecode generation, the modified AST, including the newly added method, is what the compiler actually turns into bytecode in the subsequent code-generation phase, so the generated method behaves identically to one that had been hand-written in the original source.
Global AST transformations, not tied to a specific annotation, are also possible, registered via a service-provider file so they run automatically on every compilation unit the compiler processes, useful for org-wide compiler-level policies rather than per-class opt-in behavior.
flowchart LR
A[Source code] --> B[Parse to initial AST]
B --> C{Annotation triggers local AST transformation?}
C -- Yes --> D[Transformation edits AST: adds/modifies nodes]
C -- No --> E[AST unchanged]
D --> F[Bytecode generation from final AST]
E --> F
More Related questions...