AST Transformations
[ 216 ]
This builder method is very similar to the buildClientStateGetter method. It
iterates all events in the model, creates the body of the method, then creates a new
method node with this body and adds it to the class node.
The final thing the StateMachineBuilder class needs to do is to create the state
classes themselves. We iterate each state in the model, create a state class, and add
event handlers for each event in the model:
def buildStateClasses() {
for (state in model.states) {
def stateNode = buildStateClass(state)
for (event in model.events) {
buildStateClassEventMethod(event, state, stateNode)
}
moduleNode.addClass(stateNode[1])
}
}
Building the state class is very similar to building the state context class. We use
ASTBuilder.buildFromString and provide a completed class definition minus
the event methods:
def buildStateClass(state) {
def stateClassNode = new AstBuilder().buildFromString
CompilePhase.SEMANTIC_ANALYSIS, true, """
class ${state}${className} {
def context
${state}${className}(context) {
this.context = context
}
String toString() {
"${state}"
}
}
"""
stateClassNode
}
Next, we add the event methods in the usual way. For the individual event methods
in states, we need to cater to the allowed transitions. If a state transition is allowed
for this state/event pair, then we need to insert the code for that as the method body:
def buildStateClassEventMethod(event, state, stateClassNode) {
def methodStatement = null
def nextState = model.getTransitionForState(event, state)
if (nextState) {
http://www.ebook3000.com