Archive

Posts Tagged ‘groovy;DSL’

Groovy DSL and example notes to myself

February 22, 2016 Leave a comment

most of this stuff is already out there but i wanted to try and make sure i’d understood command chaining and other tricks

so first off we note that groovy allows your to drop ‘()’ off methods where there are multiple attributes (its still required for no arg method though)

def method1 ()
def method2 (arg1, arg2=null)
def method3 (Map map, arg1, arg2=null, ...)

//then
method2 (someArg) //is equivalent to
method2 someArg

//also with mixed named/unamed attributes groovy collects all named
// attributes as into a 1st map attribute of the method

//these two are equivalent
method3 (address: "the house", 0143 222222, street: "south close")
method3 address: "the house", street: "south close", 0143 222222

Also if your function returns itself or another function (or a closure) then the dot invocation is optional, for the compiler can read this when we drop the ‘.’

def method4 () {
    println "hello"
return this
}
method4().method4 () //is equivalent to 
method4() method4()

so this gives rise to some interesting examples of using groovy to work to build
DSL facilities.

so we’ll build an example up as we go of a groovy script to show some of the options, using a simple robot like DSL which can go in some direction, travel some distance, at some speed.

first i added a couple of static imports for enums that come later in the script

import static Direction.*
import static DistanceUnit.*
import groovy.transform.TupleConstructor

i then defined a couple of enums for a DistanceUnit and Duration as we are going
to embellish Numbers with some additional method facilities

//using static import to get 'left' and 'right' direction  enums -
//see static imports above
enum Direction {
    forward, backward, left, right
}

enum DistanceUnit {
 centimeters ('cm', 0.01),
 meters ('m', 1),
 kilometers ('km', 1000)

 String abbreviation
 double multiplier

 DistanceUnit (String abbr, double mult) {
 this.abbreviation = abbr
 this.multiplier = mult}
}

enum Duration {
    millisecond ('ms', 0.001),
    second ('s', 1),
    hour ('h', 60),
    day ('d', 60*24)

    String abbreviation
    double multiplier

    Duration (String abbr, double mult) {
        this.abbreviation = abbr
        this.multiplier = mult}
}


//define a symbol for hour in script, used when getting a speed = dist/dur
def h = Duration.hour

We the want to create a couple of classes for Speed and Distance, but use the @TupleConstructor annotation so that we can avoid having to type ‘new’ when we wish to create some instances of these classes. Also as we wish to have something like ‘5.km/h’ we need to overload the div operator for the Distance class and return a Speed from this operation.

//avoid having to use new in declaration
@TupleConstructor
class Distance {
    Number amount
    DistanceUnit unit

    //added div overload so that we can have distance over unit of time
    Speed div (Duration dur) {
        new Speed (amount, unit, Duration.hour)
    }

    String toString () {"$amount $unit"}
}
@TupleConstructor
class Speed {
    Number amount
    DistanceUnit unit
    Duration duration

    String toString () {"$amount $unit/$duration.abbreviation"}
}

Now through metaprogramming we can embellish Numbers with some methods to get a Distance like this

//add new meta method to Number- return the number (delegate) as instance of Distance
//global change to Number though - probably want to limit this using categories but forces us to inject
//and use groovy shell evaluate to do the assessment
Number.metaClass.getMeters = {new Distance (delegate, DistanceUnit.meters)}

However this is a global change to Number, and we probably wish to limit the scope of these methods, so lets define a Category instead like this

//limit the scope of added methods to use closure
class DistanceCategory {
    static Distance getCentimetres (Number num) {
        new Distance (num, DistanceUnit.centimeters)
    }

    static Distance getMeters (Number num) {
        new Distance (num, DistanceUnit.meters)
    }

    static Distance getKilometers (Number num) {
        new Distance (num, DistanceUnit.kilometers)
    }

    //short form
    static getCm (Number num) {
        getCentimetres(num)
    }

    static getM (Number num) {
        getMeters(num)
    }

    static getKm (Number num) {
        getKilometers (num)
    }
}

So using the above our first go for a DSL might be to be to define a function like this

def move1 (Direction dir, Distance d) {
        println "move1: moving $dir by $d"
}

//works because 3.meters calls the new metamethod to return instance 
//of Distance.  
//wrap in 'use' closure if using category class
move1 left, 3.meters

thats not too bad, we have removed the parentheses, and invoked the getMeters()
metamethod to return a Distance.

This will print ‘move1: moving left by 3 meters’ on the console

we can get a bit more readable by defining our move method like this. Ive used
the category class this time, not the global addition of meta method to Number.

//when a method call is made with a mix of named and no named params, then grooy puts all
//the named params into a map - as first param, and the rest as unnamed param in the order seen
//so define a new move like this

def move2 (Map m, Direction dir) {
    println "move2: moving $dir by $m.by at $m.at"
}

//use the move DSL and Category to add metamethods
use (DistanceCategory) {
move2 right, by: 3.meters, at: 5.km / h
}

This works as groovy collects the named parameters and drops them into the map,
and provides the remaining attributes, after that.

This writes ‘move2: moving right by 3 meters at 5 kilometers/h’ to the console.

However it would be nice to drop the ‘,’ and the : in the maps to make this more
readable. so here is the last trick using command chains (return a callable class – here a closure for next call)

//using command chains now
def move3 (Direction dir) {
    [by: {Distance dist ->
        [at: {Speed speed ->
            println "move3: moving $dir by $dist, at $speed"
        }]
    }]
}

use (DistanceCategory) {
    move3 right by 3.meters at 5.km / h
    //is the same as
    move3 (right).by (3.meters).at(5.km/h)
}

now when you provide the direction to the move3 method, it returns a map with key ‘by’ and a single closure as its value which is invoked with 3.meters. This
immediately returns another map with key ‘at’, and another closure which is
invoked with the 5km/h (using the overloaded Distance class to pass in a Speed as the attribute to the closure, the ‘h’ property was defined previously in the script binding above.

This can make your head explode walking through the tautology, but if you step through what the compiler sees you should be able to ‘see’ what this does.

Lastly I tried this

def func (arg = null) {
    println "got args as " + arg ?: null
    if (!arg) {
        println "setting up no arg closure in map"
        [by : { -> println "no args closure: hello william "}()]
    }
    else {
        println "setting up with arg closure in map"
        [by: { mapArg -> println "with args closure : $mapArg" }]
    }
}

//println "calling no args on func : "
func() by

//println "calling with args on func : "
println "calling args on func : "
func("someArg") by 3

In the first case we call ‘func’ with no args, and the function definition defines a single map with key ‘by’ that has a closure with no args. as no args as passed you have to add the ‘()’ in the first map to execute the returned closure. In the second case you provide an attribute for func, which sets up a map with key ‘by’ that takes an argument. so you can trigger this with the by 3 and call that closure when it returns.

All this best done with a clear head and step each bit through at a time.

You can also provide the DSL boilerplating in one class and separate the language script in another through using groovy shell evaluate and injecting the compiler customisers, static imports and extended base script to that the evaluate method inherits all the DSL
definition parts like this

def binding = new Binding (//add some variables etc ) 

def importCustomizer = new ImportCustomizer()
importCustomizer.addStaticStars Direction.name //etc 

def conf = new CompilerConfiguration()
conf.addCompilationCustomers (importCustomizer)
conf.scriptBaseClass = SomeDSLBaseScript.name  //specify the script base class

def shell = new GroovyShell (this.class.classLoader, binding, config)
shell.evaluate '''
      move left...
'''
Categories: Groovy, Uncategorized Tags:
%d bloggers like this: