Book Image

Groovy for Domain-Specific Languages, Second Edition

By : Fergal Dearle
Book Image

Groovy for Domain-Specific Languages, Second Edition

By: Fergal Dearle

Overview of this book

Table of Contents (20 chapters)
Groovy for Domain-specific Languages Second Edition
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Free Chapter
1
Introduction to DSLs and Groovy
Index

Global AST transformations


Next, we will look at a global AST transformation. Unlike the local transformations we have just encountered, which are targeted at a specific part of the Groovy code, a global transformation is invoked for all AST nodes in the compiled code. Let's take a look at a fully worked global AST transformation example.

A finite state machine DSL

We will be a bit brave with this transformation. In fact, the transformed AST code for this transformation will look nothing like the original compiled code. The goal of this AST transformation is to provide a mini DSL for defining finite state machines. The syntax we are aiming for takes its queue from Spock and uses labels and string literals to be part of the DSL syntax.

Let's start with a simple state machine example, a light controlled by a toggle switch. If the light is off and the switch is pressed, the light turns on and vice versa. Let's first of all express this in pseudo code:

state: "OFF"
state: "ON"

event: "toggle"
...