Chapter 12
[ 323 ]
// X O X
// O X O
// Expect next X play to win
when:
engine = new GameEngineClient()
engine.play_round([player: 'X'], savedSession)
then:
engine.page == 'game_over'
We now have a Groovy class-based pattern, which implements our game engine.
The DSL will be implemented with an AST transform, which generates classes in
that pattern. So we can now focus on building the AST transform. We know we have
successfully built the AST transformation when the DSL version works with the
preceding test.
Implementing the AST transform
As with all the previous AST transforms, our work begins with writing an
ASTTransformation class:
@GroovyASTTransformation (phase = CompilePhase.SEMANTIC_ANALYSIS)
class GameEngineASTTransformation implements ASTTransformation,
CompilationUnitAware {
def parser
def builder
def compilationUnit
void visit(ASTNode[] nodes, SourceUnit source) {
if (!nodes) return
if (!(nodes[0] instanceof ModuleNode)) return
if (!source?.name?.endsWith('Engine.groovy')) {
return
}
def gameEngineModel = new GameEngineModel()
parser = new EnginePatternParser(gameEngineModel, source)
builder = new EnginePatternBuilder(nodes,
gameEngineModel, source, compilationUnit)
for (ClassNode classNode : nodes[0].classes) {
classNode.visitContents(parser)
}
builder.buildEnginePattern()
}
@Override