【问题标题】:Compilation customizer is not called during compilation of groovy DSL script在 groovy DSL 脚本编译期间不调用编译定制器
【发布时间】:2016-04-13 15:05:28
【问题描述】:

我想用语法写一个 groovy DSL:

returnValue when booleanCondition

我想使用编译定制器将此表达式转换为使用 AST 转换的典型 if return 语句。

对于这个脚本:

2 when 1 == 1

我收到异常消息:

MultipleCompilationErrorsException: startup failed:
Script1.groovy: 1: expecting EOF, found '1' @ line 1, column 8.

我不明白为什么我的编译定制器根本没有被调用? 我需要在编译之前调用它,这样我才能把它变成一个有效的 groovy 代码。

如果脚本包含有效的 groovy 代码,则调用我的编译定制器。

我的代码:

class MyDslTest {

    public static void main(String[] args) {
        String script = '''2 when 1 == 1
'''
        def compilerConfig = new CompilerConfiguration()
        compilerConfig.addCompilationCustomizers(new MyCompilationCustomizer())
        GroovyShell groovyShell = new GroovyShell(compilerConfig)
        groovyShell.evaluate(script)
    }
}

class MyCompilationCustomizer extends CompilationCustomizer {

    MyCompilationCustomizer() {
        super(CompilePhase.CONVERSION)
    }

    @Override
    void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {
        println 'in compilation customizer'
    }
}

【问题讨论】:

    标签: groovy abstract-syntax-tree


    【解决方案1】:

    问题是您的代码在语法上无效。编译定制器无法解决这个问题:为了能够获得定制器将在其上工作的 AST,您必须生成语法正确的代码。一种选择是使用不同的AntlrParserPlugin,但一般我不建议这样做,因为它会在解析之前修改源,因此会在 AST 和实际源之间造成不匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多