AST Transformations
[ 212 ]
contextClassName = "${className}Context"
contextClassNode[1].addProperty(
new PropertyNode(
"state",
Modifier.PUBLIC,
ClassHelper.DYNAMIC_TYPE,
ClassHelper.make (contextClassName),
new ConstructorCallExpression(
ClassHelper.make(
"${model.initialState}${className}"
),
new ArgumentListExpression(
new VariableExpression('this')
)
),
null,
null
)
)
}
The first thing you will notice here is we use ASTBuilder.buildFromString. This
is yet another mechanism in the ASTBuilder class that is available to us. Using
this method, we can formulate the code we need in text and pass it in. ASTBuilder
will take care of the parsing of this into whatever AST nodes it contains. In this
case, this is a ClassNode object for the context class. We then make use of this class
node with the regular APIs to add the state property, the StateContext class.
Note that the actual class name of the context class will be derived from the DSL
script class name. So, for instance, the toggle example will produce a class called
LEDToggleStateContext.
The reason we need to use the base APIs here is down to the code we need to
generate for the initialization of the state property. We need to add the expression
def state = new InitialState(this). The InitialState class will be the class
for whatever the initial state should be. In the case of the toggle switch, it will be
OFFState. The problem is that we don't have that class created anywhere yet. If
we tried to build the entire state context class using ASTBuilder.buildFromCode,
then we will get a class not found exception for InitialState.
http://www.ebook3000.com