groovy DSL 脚本编译期间未调用编译定制程序

Compilation customizer is not called during compilation of groovy DSL script

我想写一个 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'
    }
}

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