Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 12

[ 333 ]

moduleNode.addClass(pageNode[1])
}

}

Much of the code for building these classes will be familiar already.
One new construct we encounter is the generation of the conditional. The
setClosureDelegates method that is added to the class has a conditional block
based on the value of the session property. This is built with an IfStatement
object that accepts a BooleanExpression object as the condition, and two
BlockStatements for the if block and the else block. A basic if statement is
constructed as an IfStatement with an EmptyStatement as the else block:


def buildPageClass(page) {
def pageClassNode = new AstBuilder().buildFromString
CompilePhase.SEMANTIC_ANALYSIS, true, """
class ${page}Page extends com.dearle.game.engine.ast.PlayerService{
def session
${page}Page(session) {
this.session = session
setClosureDelegates()
}
String toString() {
"${page}"
}
}
"""
def closureDelegateStatements = [
new ExpressionStatement(
new BinaryExpression(
new PropertyExpression(
new VariableExpression("getPlayer"),
new ConstantExpression("delegate")
),
new Token(Types.EQUALS, "=", -1, -1),
new VariableExpression("session")
)
)]
for (event in model.events) {
def closureDelegateStatement = new ExpressionStatement(
new BinaryExpression(
new PropertyExpression(
new VariableExpression("$event"),
new ConstantExpression("delegate")
),
Free download pdf