Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

AST Transformations


[ 198 ]

Similarly, placing a string literal in our code without an assignment is mostly a
useless exercise. Pretty much the only use that you can make of this construct is
to return an immutable string from a method or closure. However, with an AST
transformation, we can query the content of the string and turn it into a syntactical
element of a DSL.


The assignment to next in the preceding code example would result in a compile
error if it were in any other scope because it would be interpreted as an assignment
to an undeclared variable. However, within a Groovy script is considered to be an
assignment to an undeclared variable in the binding scope, so it is legal.


We have some syntactically legal Groovy pseudo code that expresses how we would
like a state machine to work. Compiled as it is, it does nothing useful. However,
potentially, there are enough clues in this code for a clever DSL to be able to do the
rest and transform this into something useful. Let's try doing this, but first let's look
at a real piece of Groovy code that implements the toggle light switch state machine.


The state machine pattern


There are many state machine patterns we could use varying from complex to
relatively simple. We will implement the toggle switch state machine in a simple
pattern of Groovy classes. Once we have this pattern working, we will use this as a
target end point for the state machine DSL once it is generated. The pattern we are
using is based on the state pattern from the book: Design Patterns, Elements of Reusable
Object-Oriented Software, Addison Wesley.


Design Patterns, Elements of Reusable Object-Oriented Software, Addison
Wesley written by Erich Gamma, Richard Helm, Ralph Johnson, and
John Vlissides (ISBN: 0-201-63361-2).

What we will be aiming for is an AST transform that can parse the DSL at
compile time and generate the classes needed to implement this pattern. I find it
useful to build the target code that I expect from a transform first, so I have a full
understanding of what the expected transformed outcome should be. In fact, in the
example code pack, you will find three state machines implemented both in the
straight Groovy pattern and with the DSL.


Let's look at the first state machine in detail as a Groovy pattern implementation.
Our state machine has several elements as follows:



  • State context: The context is a holder for the current state of the machine.


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