Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

AST Transformations provides Groovy with improved compile-time metaprogramming capabilities allowing powerful flexibility at the language level, without a runtime performance penalty.

Annotation based AST Transformations

One hook for accessing this capability is via annotations. In your Groovy code you can make use of one of more annotations to mark a class for receiving an AST transformation during compilation. Behind the scenes, an AST processor relevant to the annotation you are using is inserted into the compiler phases at the appropriate point.

There are a number of standard Annotations that cause AST transformations to be performed.

Standard Annotations

Children Display
alltrue

Grape also provides its own transformation with @Grab.

 

Implementing your own AST Transformations

 

There are two kinds of transformations: global and local transformations.

  • Global transformations are applied to by the compiler on the code being compiled, wherever the transformation apply. A Compiled classes that implement global tranasformations are in a JAR added to the classpath of the compiler should and contain a service locator file at META-INF/services/org.codehaus.groovy.transform.ASTTransformation with a line with the name of the transformation class. The transformation class must have a no-args constructor and implement the org.codehaus.groovy.transform.ASTTransformationinterface. It will be run against every source in the compilation, so be sure to not create transformations which scan all the AST in an expansive and time-consuming manner, to keep the compiler fast.

  • Local transformations are transformations applied locally by annotating code elements you want to transform. For this, we reuse the annotation notation, and those annotations should implement org.codehaus.groovy.transform.ASTTransformation. The compiler will discover them and apply the transformation on these code elements.

One hook for accessing this capability is via annotations (for local AST transformations). In your Groovy code you will make use of one of more annotations. Behind the scenes, an AST processor relevant to the annotation you are using is inserted into the compiler phases at the appropriate point. You can explore some of the more popular Annotations below:

Children Display
alltrue

Grape also provides its own transformation with @Grab.

Implementing your own AST Transformations

There are two kinds of AST Transformations, local and global transformations:

When writing an AST Transformation, you may find the following guides helpful:

See Also