Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

AST Transformations


[ 204 ]

In order to understand this code better, let's first remind ourselves of the syntax of
our state machine DSL. The DSL can represent several different elements of the state
machine as follows:



  • States: The different states are declared with a label and a constant string.
    So, we are looking in the AST for statements that are constant expressions
    and have a label state:.

  • Events: The events are declared with a label and string. So here, once again
    we are looking for constant expressions that have a label event:.

  • Transitions: For each event, we need to define some transitions. We can have
    a default transition for an event, in which case the event: clause should
    be followed immediately by an assignment to next. Otherwise, it should
    be followed by one or more when: clauses, which define the individual
    allowable transitions.


Our StateMachineParser.visitMethod method looks like this. The Groovy script
class that represents our DSL will have a run method, which represents the main
body of code in the script itself. We limit our AST parsing to this method since this is
where we expect to find the DSL code:


@Override
void visitMethod(MethodNode node) {
if (node.name == "run") {
def event = null
def when = null
collectStates(node)
collectEvents(node)
handleBaseErrors(node)
node.code.statements.each { stmnt ->
def param = getLabelParam(stmnt)

switch (stmnt.statementLabel) {
case 'event':
event = param
when = null
break
case 'when':
handleWhenErrors(param, event, stmnt)
when = param
break
default:
if (event) {
handleWhen(stmnt, event, when)
} else {
addError "Inappropriate syntax.",
stmnt, source
}

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