Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 8

[ 191 ]

@GroovyASTTransformation (phase = CompilePhase.SEMANTIC_ANALYSIS)
class PrettyBasicASTTransformation implements ASTTransformation {
void visit(ASTNode[] nodes, SourceUnit source) {
if (!nodes) return
if (!(nodes[0] instanceof AnnotationNode)) return
if (!nodes[1] && !(nodes[1] instanceof ClassNode)) return
ClassNode classNode = nodes[1]

def methodStatement = new ExpressionStatement(
new MethodCallExpression(
new VariableExpression("this"),
new ConstantExpression("println"),
new ArgumentListExpression(
new ConstantExpression(
"I'm so pretty. Oh so pretty!")
)
)
)
def methodNode = new MethodNode(
'prettyPrint',
Modifier.PUBLIC,
null,
new Parameter[0],
null,
methodStatement
)
classNode.addMethod(methodNode)
}
}

Once we have verified that we are dealing with a class node of the AST, it's time to
decide what we want to do with it. In this case, we will add a node below the class
node for a new method called prettyPrint. This method node (MethodNode class)
contains a single expression statement (the ExpressionStatement class), which in
turn is comprised of a method call expression (the MethodCallExpression class),
and so on.


In effect, what we are programmatically doing is building the AST nodes that would
represent the following code:


public void prettyPrint() {
return this.println ( "I'm so pretty, Oh so pretty!")
}
Free download pdf