Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 8

[ 211 ]

ModuleNode moduleNode
ClassNode classNode
String className
ClassNode contextClass
String contextClassName

StatePatternBuilder(ASTNode[] nodes, stateMachineModel) {
this.model = stateMachineModel
moduleNode = nodes[0]
classNode = nodes[0].classes[0]
className = nodes[0].classes[0].nameWithoutPackage
}

void buildStatePattern() {
buildContextClass()
updateClientClass()
buildStateClasses()
}
void buildContextClass() {
....
}
void updateClientClass() {
...
}
void buildStateClasses() {
...
}
}

The StateMachinePattern class is initialized with the newly created model and the
ASTNode object passed into the transform. For convenience, we extract some objects
from the AST and save them locally. This will save us dereferencing them from the
AST later. In the pattern, the one class that is referenced across all three components
of the pattern is the StateContext class, so this is the first thing we will build:


void buildContextClass() {
def contextClassNode = new AstBuilder().buildFromString
CompilePhase.SEMANTIC_ANALYSIS, true, """
class ${className}Context {
}
"""

contextClass = contextClassNode[1]
moduleNode.addClass(contextClassNode[1])
Free download pdf