concept CompilerConfiguration in category groovy

appears as: CompilerConfiguration, CompilerConfiguration
Groovy in Action, Second Edition

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

9 Whether classes are checked for runtime updates can be controlled by the CompilerConfiguration, which obeys the system property groovy.recompile by default. See the API documentation for details.

We used the Binding class to pass variables to scripts and to retrieve modified or new variables defined during the evaluation of the script. We can further configure our GroovyShell instance by passing two other objects in the constructor: a parent ClassLoader and/or a CompilerConfiguration.

As you can see, this option requires a configuration file that’s itself a Groovy script. This configuration file will give you access to the CompilerConfiguration instance that the groovyc command creates internally, giving you a chance to plug in your compilation customizers. This compiler configuration instance is exposed in the configuration script using the config variable. This means that you can write this in the configuration file:

import groovy.transform.Log
import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer

config.addCompilationCustomizers(new ASTTransformationCustomizer(Log))

This configuration option is also available on the groovy command, as well as in the Ant task. All files compiled will therefore use the configuration as modified by the script. But what’s really nice is that this configuration script also exposes a nice DSL to customize the configuration, dramatically reducing the amount of code that’s required to tweak the CompilerConfiguration. This DSL is a builder for compilation customizers, which is automatically bound to the withConfig method:

In this example, we’re explicitly changing the base script class from Script to BaseScript. This makes all the methods from the BaseScript class directly callable from the script text when we call evaluate. setScriptBaseClass is just one example of what the CompilerConfiguration class has to offer in terms of customization of the compilation process.