AST Transformations
[ 192 ]
This is not really what we want yet for a proper PrettyPrint transformation,
but it is a fully functioning AST transformation implementing an annotation
@PrettyBasic. If we apply this transformation to a class, we can see it in action.
The Spock test we wrote earlier should now be working.
Using ASTBuilder
In the previous example, we used methods on the AST nodes themselves such as
addMethod to build up the new code in the AST. This can get laborious if we try
and add any more sophisticated code. Even the simple prettyPrint method would
be quite difficult to implement with this mechanism. Fortunately, there are other
options that will make our lives a bit easier.
Build from code
Let's build another AST transformation, which uses a useful helper class ASTBuilder
to add the prettyPrint method to our class. Once again we will need to define an
interface for our annotation class and the AST transformation class itself:
@Target([ElementType.TYPE])
@Retention(RetentionPolicy.SOURCE)
@GroovyASTTransformationClass(["PrettySimpleASTTransformation"])
public @interface PrettySimple {
}
@GroovyASTTransformation (phase = CompilePhase.SEMANTIC_ANALYSIS)
class PrettySimpleASTTransformation implements ASTTransformation {
void visit(ASTNode[] nodes, SourceUnit source) {
ClassNode classNode = nodes[1]
def astNodes = new AstBuilder().buildFromCode {
this.properties.sort { it.key }.each {
if (it.key != 'prettyPrint' && it.key != 'class')
println it.key + ": " + it.value
}
}
def methodStatement = astNodes[0]
def methodNode = new MethodNode(
'prettyPrint',
Modifier.PUBLIC,
null,
new Parameter[0],
http://www.ebook3000.com