Chapter 8
[ 189 ]
Local AST transformations
When discussing AST transformations in Groovy, we refer to local and global AST
transformations. A local transformation is one that is targeted at a specific "local"
piece of code. Currently, the only way to tell the Groovy compiler to implement a
local transformation is to use an annotation. The annotation gives the compiler the
clue as to what part of the compiled code should be transformed. Annotations can be
placed next to any part of the Groovy source code, but are typically bound to a class,
field, or method.
Let's start out by implementing a very simple annotation based on an AST
transformation. Ultimately, we will evolve this example into an AST that implements
the pretty printing functionality we built back in Chapter 7, Power Groovy DSL
Features, as both an Expando closure method and via a trait. However, let's start
simple and just add a method to a class that prints a string.
The functionality we want to implement can be captured in the following Spock
specification. Assuming we have an annotation called @PrettyBasic, then adding
this annotation to a class as follows will add a prettyPrint method to the class:
@PrettyBasic class Basic {
}
given:
def target = new Basic()
when:
target.prettyPrint()
then:
"I'm so pretty. Oh so pretty!" == output()
The examples in this chapter are relatively complex. In many cases,
you are seeing sections of class files described here rather than the
fully worked source. Many dependent imports are omitted for brevity
and long package names are excluded. You should download the
source pack instead of typing these examples in yourself. The source
pack contains the full sources and dependencies.