Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 12

[ 337 ]

The PageAssignmentTransformer class extends CodeVisitorSupport and
overrides the visitBinaryExpression method. CodeVisitorSupport has methods
for every type of statement and expression you could possibly encounter. As it
happens, the only type of expression we care about is BinaryExpression where
the left expression is the page variable and the right is a constant.


We can therefore target all the places where the statement page = constant occurs.
We can then make a direct assignment to rightExpression and replace the constant
with the appropriate ConstructorCallExpression for a page class.


Apart from some cleanup to remove the unwanted methods from the engine class,
that is the full AST transformation completed.


Testing the DSL


In theory, we should now be able to make use of the game engine DSL. Let's see if
the original Spock test will still work if we convert it using the DSL instead of the
pattern classes. To do so, we need to load the DSL code from somewhere:


given:
CompilerConfiguration config = new CompilerConfiguration()
config.addCompilationCustomizers(
new ASTLogCompilationCustomizer(
CompilePhase.SEMANTIC_ANALYSIS,
System.out
))
GroovyClassLoader classLoader = new GroovyClassLoader(
this.class.classLoader, config)
engineClass = classLoader.parseClass(
new File("pathto/TicTacToeEngine.groovy"))
def gameEngine = engineClass.newInstance()

expect:
!gameEngine.session

when:
def savedSession = gameEngine.game_start()
then:
gameEngine.session
gameEngine.page == 'players'
gameEngine.session.players.size() == 2
Free download pdf