concept compile - time metaprogramming in category groovy

appears as: compile-time metaprogramming
Groovy in Action, Second Edition

This is an excerpt from Manning's book Groovy in Action, Second Edition.

This chapter covers compile-time metaprogramming or AST transformations. You’ll learn a bit about the concept and its importance. Then we’ll explore most of the transformations Groovy ships with, such as @ToString, @EqualsAndHashCode, and @Lazy, and show you how these keep your code lean and clean. Next, we’ll dive into more details about how AST transformations work and ways to create AST data structures. Then you’ll write your own local and global AST transformations before we look at tools available for viewing and testing AST data structures. As a final step, you’ll see some of the common mistakes and limitations encountered with compile-time metaprogramming.

Compile-time metaprogramming is an exciting area of the language. There are many new libraries and frameworks for Groovy that generate verbose, boilerplate code directly into the .class files instead of forcing all the users to write extra source code. Code generation is no longer limited to those brave developers willing to download and build the source code for the Groovy compiler: it’s available to anyone using Groovy. If you have a great idea for a new language feature then it’s possible to write it today as a library. This powerful technique creates a living language, where you’re allowed to extend the language in the direction best suited to your project. Many of Groovy’s features are implemented on top of the AST transformation framework. For example, the @Delegate, @Immutable, and @Log annotations all hook into the compiler and affect the final .class file. @Bindable is the secret to UI property binding in the Griffon framework (or writing Groovy Swing in general). The Spock and GContracts libraries both leverage AST transforms, providing useful and productivity-boosting results. Compile-time metaprogramming is used by these libraries to produce more readable tests and more correct runtime behavior.