Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

AST Transformations


[ 206 ]

As we traverse the statements in the module, we also record the occurrence of
event: and when: clauses. This allows us to correctly handle the transition
statement when we encounter it. A transition is declared by assigning a state to
next, for example, next = "ON". The handleWhen method handles both the default
transition case where no when: clause is provided and the when: clause itself.


def handleWhen(statement, event, transition) {
if (statement instanceof ExpressionStatement &&
statement.expression instanceof BinaryExpression) {
BinaryExpression expr = statement.expression
def var = expr.leftExpression
Token oper = expr.operation
def state = expr.rightExpression

if ( var instanceof VariableExpression &&
var.accessedVariable.name == 'next' &&
oper instanceof Token &&
oper.rootText == "=" &&
state instanceof ConstantExpression
) {
def next = state.value.toString()
if (!model.states.contains(next))
addError "Reference to non existent state",
state, source
if (event && transition) {
model.addTransition event, transition, next
} else {
model.addTransition event, '_all', next
}
} else {
handleBadWhenExpression var, expr, state
}
} else {
addError "when: or next = 'state' is allowed here",
statement, source
}
}

http://www.ebook3000.com
Free download pdf