Tuesday, June 10, 2008

Fowler's DSL example with Xtext

In his recent DSL related blog entries (ParseFear and Syntactic Noise), Martin Fowler mentioned a DSL example he's using in his upcoming DSL book. Here you can see how it is implemented using Antlr and a lot of Java.

This is how it can be done using Xtext and openArchitectureWare.
1) Download the oAW distro from itemis
2) Create a new Xtext Project
3) Paste the following Xtext grammar into the opened editor:

Statemachine :
'events'
(events+=Event)*
'end'
'commands'
(commands+=Command)*
'end'
(states+=State)*;

Event :
(resetting?='resetting')? name=ID code=ID;

Command :
name=ID code=ID;

State :
'state' name=ID
('actions' '{' (actions+=[Command])+ '}')?
(transitions+=Transition)*
'end';

Transition :
event=[Event] '=>' state=[State];

4) start the generator (right click on generate.oaw Run->oaw workflow)
your're done.

You not only get an Antlr based parser but also get an EMF based AST (SemanticModel), and a fully fledged eclipse editor.

Of course it's up to you whether you want to interpret models or generate some code out of them. I choosed to write a small Xpand template file, generating a "controller".
Here it is.