在编译groovy DSL脚本期间不调用编译自定义程序

在编译groovy DSL脚本期间不调用编译自定义程序,groovy,abstract-syntax-tree,Groovy,Abstract Syntax Tree,我想用以下语法编写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 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和实际源代码之间创建不匹配。

问题是您的代码在语法上无效。编译自定义程序无法解决这一问题:要获得自定义程序将使用的AST,必须生成语法正确的代码。一种选择是使用不同的
AntlrParserPlugin
,但通常我不建议这样做,因为它会在解析之前修改源,因此会在AST和实际源之间创建不匹配