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"]) ...
Get Groovy for Domain-specific Languages - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.