Integrating It All
[ 338 ]
In order to create an instance of the game engine class, we use GloovyClassLoader.
parseClass to parse the class from a local file. If the AST transform is available
in the compiler's classpath, that's all we need to do to cause the DSL script to be
transformed. For a simple DSL implementation, such as the state machine DSL in
Chapter 8, AST Transformations, this is all we need to do:
GroovyClassLoader classLoader = new GroovyClassLoader()
stateMachineClass = classLoader.parseClass(
new File("pathto/SomeState.groovy"))
def stateMachine = stateMachineClass.newInstance()
Class loading issues
All the dependent classes created in this DSL are generated in the original
script model for the state machine DSL. So it is entirely self-contained in the
parsed module. The game engine DSL makes use of existing classes such as
PersistableSession, PlayerService and the trait GameEngineTraits. These
classes need to be resolved on the class path when the AST transform is generating
code that depends on them.
We can resolve this by creating the GroovyClassLoader with a parent ClassLoader
and any class reference that the compiler cannot resolve in the GroovyClassLoader
will be delegated to the parent class loader seeking a reference. The three classes we
need are already in the class path of the Spock specification via the ast.jar file, we
will see how this is built in a moment. We can get hold of the default class loader for
the specification via the test specification's own class, which is referenced in the test
via this.class.classLoader.
When we are building our own AST transformations, it is important to understand
that the transformation itself becomes part of the compilation process. The transform
won't work if you put the AST transformation sources into your main application
code because the transform is compiled at the same time as the application.
We managed to avoid this issue in the Chapter 8, AST Transformations examples. All
the AST examples in the Chapter 8, AST Transformations exercise were transforms via
Spock tests. The transforms were compiled to classes in the Gradle compile phase
and then made use of in the testCompile phase.
Gradle subprojects
In order to make use of the game engine AST transform, we will need to compile
it into a separate JAR file which is made available in the classpath when we
compile the main application code. A handy way to do this is via a Gradle
multi-project build.
http://www.ebook3000.com