AST Transformations
[ 202 ]
Global AST transformations are potentially expensive in terms of CPU resources.
The visit method of the global transformation will be called for every single AST
node it encounters during compilation. For this reason, we want to limit our
processing to just the module that contains our state machine DSL. In the preceding
example, we check that the file ends with State.groovy. Another valid approach
would be to limit the AST transformation to just sources from a particular source
folder. Alternatively, the Groovy compiler does allow us to use custom
file extensions.
The StateMachineASTTransformation class next creates an empty data model.
The data model object is populated during parsing by a StatePatternParser object.
Once the data model is populated, it will contain the list of states available in the
state machine along a list of all the available events and what transitions are possible
in response to these events:
class StateMachineModel {
def states
def events
def StateMachineModel() {
states = []
events = [:]
}
def getInitialState() {
states[0]
}
def addState( state ) {
if (!states.contains(state))
states << state
}
def addEvent(event) {
events[ "$event" ] = [:]
}
def addTransition(event, transition, next) {
events["$event"]["$transition"] = next
}
def getEvents() {
events.keySet()
}
def getTransitionForState(event, state) {
def transition = events["$event"]["_all"]
if (!transition)
transition = events["$event"]["$state"]
transition
}
}
http://www.ebook3000.com