Search

Dark theme | Light theme

November 19, 2013

Groovy Goodness: Set Script Class with BaseScript Annotation

Groovy is of course great for writing DSLs. We can write our own Script class to implement a DSL that can be used when we evaluate a script. We can set the custom Script class via CompilerConfiguration. Since Groovy 2.2 we can use a new AST transformation @BaseScript. We must use this annotation in the script and set it on the custom script class. The name of the variable is not important, but the type must by the custom script class.

In the following DSL script we use the @BaseScript instead of the CompilerConfiguration as shown in previous blog post.

// Simple Car class to save state and distance.
class Car {
    String state
    Long distance = 0
}

// Custom Script with methods that change the Car's state.
// The Car object is passed via the binding.
abstract class CarScript extends Script {
    def start() {
        this.binding.car.state = 'started'
    }

    def stop() {
        this.binding.car.state = 'stopped'
    }

    def drive(distance) {
        this.binding.car.distance += distance
    }
}


// Define Car object here, so we can use it in assertions later on.
def car = new Car()
// Add to script binding (CarScript references this.binding.car).
def binding = new Binding(car: car)

// Configure the GroovyShell.
def shell = new GroovyShell(this.class.classLoader, binding)

// Simple DSL to start, drive and stop the car.
// The methods are defined in the CarScript class.
def carDsl = '''
start()
drive 20
stop()
'''


// Run DSL script.
shell.evaluate """
// Use BaseScript annotation to set script
// for evaluating the DSL.
@groovy.transform.BaseScript CarScript carScript

$carDsl
"""

// Checks to see that Car object has changed.
assert car.distance == 20
assert car.state == 'stopped'

Code written with Groovy 2.2.