Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

AST Transformations


[ 208 ]

We should have two or more states and at least one event declared. You will
also notice in the handleWhen method we encountered previously, we detect
if a nonexistent state is referenced and add an error for that:


def handleBaseErrors(node) {
if (model.states.size() < 2)
addError "State machine must have at least two states",
node, source
if (!model.events)
addError "State machine must have at least one event",
node, source
}

If we then build a toggle state machine that accidentally omits a state and then
references that state, we will cause two compile errors to be generated:


state: "ON"

event: "toggle"
when: "ON"
next = "OFF"

This will provide the following output:


ErrorState.groovy: -1: State machine must have at least two states


@ line -1, column -1.


ErrorState.groovy: 7: Reference to non existent state


@ line 7, column 16.


next = "OFF"


^


Declaring a when: clause without a state, or with a nonexistent state, or failing to use
a String constant to represent, the state should cause an error:


def handleWhenErrors(state, event, statement) {
if (!state)
addError "Expected state value after when:",
statement, source
if (state && !model.states.contains(state))
addError "Cannot transition from a non existant state",
statement.expression, source
if (!event)
addError "when: must follow event:", statement, source
}

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