Groovy web console

subscribe to the feed Subscribe
to this
site

Groovy DSL without Commas

Published 10 years ago by Hamlet D'Arcy with tags groovy dsl antlr ast
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import org.codehaus.groovy.control.*
import org.codehaus.groovy.antlr.*
import org.codehaus.groovy.syntax.*


class SourceModifierParserPlugin extends AntlrParserPlugin {
    Reduction parseCST(SourceUnit sourceUnit, Reader reader) throws CompilationFailedException {
        def text = addCommas(reader.text)
        StringReader stringReader = new StringReader(text)
        super.parseCST(sourceUnit, stringReader)
    }

    String addCommas(text) {
        def pattern = ~/(.*)(given|when|then) "([^"\\]*(\\.[^"\\]*)*)" \{(.*)/
        def replacement = /$1$2 "$3", {$4/
        (text =~ pattern).replaceAll(replacement)
    }
}

class SourcePreProcessor extends ParserPluginFactory {
    ParserPlugin createParserPlugin() {
        new SourceModifierParserPlugin()
    }
}

def parserPluginFactory = new SourcePreProcessor()
def conf = new CompilerConfiguration(pluginFactory: parserPluginFactory)

def binding = new Binding([
    given: { name, f -> print "given: $name\n  "; f() },
    when:  { name, f -> print "when: $name\n  ";  f() },
    then:  { name, f -> print "then: $name\n  ";  f() },
])

def shell = new GroovyShell(binding, conf)
shell.evaluate("""

    given "some data" {
        println '... setting expectations'
    }
    when "a method is called" {
        println '... calling some method'
    }
    then "some condition should exist" {
        println '... making an assertion'
    }
""")

println '\nSuccess!'