Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 8

[ 207 ]

Here, we are looking in the AST for a binary expression where the left operand is a
variable called next, the right operand is a constant and the operator is equals. If we
find code in the AST that matches this, then we add the appropriate transitions to the
model. In the preceding code you can clearly see how the AST is structured as a tree.
If we do find the expression we are looking for—that is, next = "ON", then this is
composed in the tree as follows:


ExpressionStatement next = "ON"
|_BinaryExpression next = "ON"
|_VariableExpression next
|_Token =
|_ConstantExpression "ON"

Handling errors – compile errors


Even though state machine DSL written in Groovy is a mini language in its own
right. If we add inappropriate code into the source, it can have undesired effects.
It's also possible for many potential syntax errors to occur, which could cause
the transformed code to behave incorrectly or to fail to transform at all. As far
as possible, we should predict all these potential error conditions and respond
accordingly. The appropriate response in this case would be to generate compiler
errors with an appropriate message and identify the location in the code, which
is incorrect.


To help us with generating compiler errors, we are using a helper method in
the StateMachineParser class, addError. This method is borrowed from the
LogASTTransformation, which is part of the core Groovy sources. This helper
method will produce a compile error in the compiler output that looks just like a
regular groovyc compiler error:


def addError(String msg, ASTNode expr, SourceUnit source) {
int line = expr.lineNumber
int col = expr.columnNumber
SyntaxException se =
new SyntaxException(msg + '\n', line, col)
SyntaxErrorMessage sem = new SyntaxErrorMessage(se, source)
source.errorCollector.addErrorAndContinue(sem)
}

In the interest of brevity, this DSL example does not contain all the possible error
handling we could do. Here are some of the ones we do handle. I'm sure you can
think of more.

Free download pdf