Integrating It All
[ 336 ]
These assignments can occur anywhere within the event: block code. This means
they could be nested deep within the AST nodes we have saved. We have a
convenient method for finding each of them so we can transform them.
Once we have created a new BlockStatement object out of event statements, we can
visit all of the AST nodes in the block using the GroovyCodeVisitor class. To do so,
we need to implement our own visitor class:
class PageAssignmentTransformer extends CodeVisitorSupport {
def model
def source
PageAssignmentTransformer(model, source) {
this.model = model
this.source = source
}
@Override
void visitBinaryExpression(BinaryExpression expr) {
def var = expr.leftExpression
Token oper = expr.operation
def page = expr.rightExpression
if ( var instanceof VariableExpression &&
var.accessedVariable.name == 'page' &&
oper instanceof Token &&
oper.rootText == "=" &&
page instanceof ConstantExpression
) {
def next = page.value.toString()
if (!model.pages.contains(next)) {
addError "Reference to non existent state",
page, source
} else {
expr.rightExpression = new ConstructorCallExpression(
ClassHelper.make("${next}Page"),
new ArgumentListExpression(
new VariableExpression('session')
) ) } } } }
http://www.ebook3000.com