Building Domain-Specific Languages in JRuby
But why would you want to do this? There are many possible answers, some of these are: repetitive tasks can be simplified; boiler-plate code can be encapsulated; or an API can be better express the intent of the code. No matter what your particular reason, all DSLs should deliver a clear value to your project.
The approach explored in the presentation was to create a JRuby DSL that is utilized from within Java classes. As byte code generated from JRuby will run in the JRE, the DSL is categorized as "internal" - which uses a general programming language to create a specific programming language. The alternative is an "external" DSL that requires an external compiler and generator, making the integration much more difficult.
The benefit in this approach is in creating the DSL, and several JRuby language techniques were presented to make developing DSLs easier:
- Operator overloading - overloading operator allows the DSL to provide a natural syntax
- Hashes and symbols - using hashes and symbols make it easy to express relationships and identify objects
- Blocks - blocks encapsulate executable logic, and allow the logic to be stored (in hashes) for later execution
- Dynamic type extension - methods can be added dynamically to classes and objects
- Method missing - when a method is called that doesn't exists it can be trapped, avoiding the need to know all the operations in advance
- Integration - take advantage to existing Java code
To take full advantage of using JRuby in creating the DSL, tips on style were provided:
- Ensure that you are not writing Java code in a dynamic language
- Build up the DSL from common building blocks
- Identify the problem and then create a syntax to express the solution
- Provide metadata and behavior - don't let DSLs become configuration files
- Think the ruby way: use type extensions; use blocks; use methods on objects
- Keep the scope limited; address a small part of your domain and don't try to make the DSL a general programming language
For developers, DSLs are another tool that can be utilized. By investing a little time upfront, large time savings can be achieved.
Groovy, an other option
Doc List Oct 25, 2014