Adding @GrailsCompileStatic to all production grails code (not test grails code)

When coding Groovy, @CompileStatic can help to spot errors and improve performance of production code. Unfortunately, @CompileStatic is optional and hence easy to forget, but thankfully Groovy has documented a way to make @CompileStatic for all production code: http://docs.groovy-lang.org/latest/html/documentation/#_static_compilation_by_default
(Test code is not affected, because it is nice with flexibility when testing.)

However, with Grails you really want to use @GrailsCompileStatic instead of @CompileStatic, because it saves you from adding @CompileDynamic all the places that dynamic Grails functionality is used while still ensuring that your own code is @CompileStatic. Unfortunately, the above solution cannot be used for applying @GrailsCompileStatic to all production code. This is due to @GrailsCompileStatic is not available at the Compile Configuration and trying to @Grab it from grails-core only yields new dependency problems.

Eventually, I realised that @GrailsCompileStatic is just @CompileStatic with some extensions – those can be included in the Compile Configuration manually and then it works as expected.

This is my src/groovyCompile/groovyConfig.groovy:

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

// Extensions are copied from @GrailsCompileStatic due to that @GrailsCompileStatic is not available in the Compile Configuration
List extensions = ['org.grails.compiler.ValidateableTypeCheckingExtension',
'org.grails.compiler.HttpServletRequestTypeCheckingExtension',
'org.grails.compiler.WhereQueryTypeCheckingExtension',
'org.grails.compiler.DynamicFinderTypeCheckingExtension',
'org.grails.compiler.DomainMappingTypeCheckingExtension',
'org.grails.compiler.RelationshipManagementMethodTypeCheckingExtension']
ASTTransformationCustomizer grailsCompileStatic = new ASTTransformationCustomizer([extensions: extensions], CompileStatic)
configuration.addCompilationCustomizers(grailsCompileStatic)

At build.gradle, I also added the following:

compileGroovy.groovyOptions.configurationScript = file('src/groovyCompile/groovycConfig.groovy')

Let me know if this works for you – feedback is the best motivator!

Leave a Reply

Your email address will not be published. Required fields are marked *