Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 8

[ 221 ]

Compiling and packaging an AST transformation


Within the code examples in this chapter, we have two categories of code,
the code implementing the AST transformations, for example, PrettyAwesome,
PrettyAwesomeASTTransformation, PrettyAwesomeTrait, and the code, which is
being transformed by the transform. However, when we try to run these examples,
we need to be aware of when in the compilation process each is used, so we can
package them appropriately.


The first thing to be aware of is that the AST transformation code is used in the
compilation process, and in effect, becomes an extension of the compiler. This means
that in order to use the AST transformation the compiler must already have access to
a compiled version of that code. So, we cannot simply have the AST transformation
code and the target class in the same source package and hope it will work. If we do
this, the AST transform will get compiled, but it will be invisible to the compiler at
that point and won't get applied to the target class.


If we take a look at the example code package, we can see how this is circumvented.
The example code is built using Gradle and has two distinct compilation tasks.
The first, compileGroovy compiles all sources in the src/main/groovy directories.
The second, compileTestGroovy compiles all sources in the src/test/groovy
directories.


For the purposes of the book examples, we only care if the AST transformations
are available in the test package. This means we can separate the two parts of
the code by placing the AST transformations in src/main and the target classes
in src/test. When we run the tests, the AST transformations are first compiled
by the compileGroovy task and then the target classes are complied by the
compileTestGroovy task at which point the AST transformations are available
for use.


When implementing your own AST transforms, you will want to package them
in such a way as they can be consumed as a dependency by your application. The
Groovy AST class files can be packaged into a separate JAR file. For a local AST, this
is all you need to do. For a global AST transformation, you need to tell the compiler
where to find your transformation. The compiler looks for the org.codehaus.
groovy.transform.ASTTransformation file in the META-INF/services directory
of your JAR file. This file should contain the fully qualified package and name of the
AST transformation class. So, for our state machine transformation, in the examples
pack this might be:


com.dearle.groovydsl.transforms.StateMachineASTTransformation
Free download pdf