Book Image

Groovy for Domain-Specific Languages, Second Edition

By : Fergal Dearle
Book Image

Groovy for Domain-Specific Languages, Second Edition

By: Fergal Dearle

Overview of this book

Table of Contents (20 chapters)
Groovy for Domain-specific Languages Second Edition
About the Author
About the Reviewers
Free Chapter
Introduction to DSLs and Groovy

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:

public @interface PrettySimple {

@GroovyASTTransformation (phase = CompilePhase.SEMANTIC_ANALYSIS)
class PrettySimpleASTTransformation implements ASTTransformation {

    void visit(ASTNode[] nodes, SourceUnit source) {
  ClassNode classNode...