Book on Domain-Specific Languages with Groovy
You can have a look at our books section listing Fergal Dearle's book titled "Groovy for Domain-Specific Languages" published by Packt Publising.
Tutorial on DSLs
Guillaume Laforge and John Wilson presented a tutorial on Groovy DSLs at the QCon 2007 conference in London.
Matt Secoske presented a session on Implementing DSLs in Groovy at the OSCON 2007 conference.
Groovy features enabling DSLs
Groovy is particularly well suited for writing a DSL: Domain-Specific Language. A DSL is a mini-language aiming at representing constructs for a given domain. Groovy provides various features to let you easily embed DSLs in your Groovy code:
- the builder concept lets you write tree structured languages
- you can add new methods and properties on arbitrary classes through categories or custom metaclasses, even numbers: 3.euros, 5.days, etc, as shown in this article explaining how to write a unit handling mini-DSL
- most operators can be overloaded: 5.days + 6.hours, myAccount += 400.euros
- passing maps to methods makes your code look like methods have named parameters: move( x: 500.meters, y: 1.kilometer )
- you can also create your own control structures by passing closures as the last argument of a method call: ifOnce( condition )
{ ... }; inTransaction { ... } - it is also possible to add dynamic methods or properties (methods or properties which don't really exist but that can be intercepted and acted upon) by implementing GroovyObject or creating a custom MetaClass
Guillaume Laforge gave some thoughts and examples on that topic on his blog. John Wilson has implemented a DSL in his Google Data Support to make operations on dates easier.
Joachim Baumann wrote an article showing how to implement a small DSL for measurement calculation, which uses some of the techniques like adding properties to numbers, or overloading operators. Guillaume Laforge also wrote an article on representing units using the JScience library.
Andy Glover also plays with internal DSLs in Groovy by producing a behavior testing DSL.
Inspired by an article from Bruce Tate IBMs Alphaworks a couple of samples were written in groovy.
- Chris vanBuskirk uses arrays and maps to model the injection of the state transitions.
- Edward Sumerfield uses closures to inject the state transitions.
Inspired by RSpec (and also by random episodes of Family Guy) an example of a unit testing DSL using Groovy
- Clifton Craig uses Builders in Groovy to create GSpec.
When Groovy's not enough
If you have the need to write your own language completely, consider using a compiler compiler. There are many to choose from, e.g. Antlr, JavaCC, SableCC, Coco/R, Cup/JLex/JFl;ex, BYacc/J, Beaver, etc. See wikipedia for an interesting list. Some of these can even benefit from Groovy. Here is a groovy example for JParsec.