定义返回void的AST转换

时间:2015-02-02 20:11:12

标签: groovy

这是我的AST转换

@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
public class ASTExampleTransformation implements ASTTransformation {

    public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
        astNodes.findAll {
            node -> node instanceof ClassNode
        }.each {
            classNode ->

                println("classNode")
                def useMethodBody = new AstBuilder().buildFromCode {
                    println(">>useMethodBody")
                }


                def useMethod = new MethodNode (
                        'useMethod', ACC_PUBLIC, ClassHelper.VOID_TYPE, [] as Parameter[], [] as ClassNode[], useMethodBody[0]
                )

                classNode.addMethod(useMethod)
        }
    }



}

当我编译时,我收到此错误

[groovyc] General error during class generation: Cannot use return statement with an expression on a method that returns void

如何构建代码然后返回void?谢谢。

1 个答案:

答案 0 :(得分:0)

我从未使用过AstBuilder所以我无法帮助你。我猜想问题是AST构建器支持Groovy样式的隐式返回和默认返回Object,或类似的东西?

以下是直接使用AST构建器代码构建println方法调用语句的示例。老实说,我不确定这是否也最终会回报。但我假设使用低级AST语法构建的原始语句不会添加隐式返回。有一个单独的类来制作返回语句 - ReturnStatement。所以试一试:)

Statement useMethodBody = new ExpressionStatement(
  new MethodCallExpression(
    new VariableExpression("this"),
    new ConstantExpression("println"),
    new ArgumentListExpression(
      new ConstantExpression(">>useMethodBody")
    )
  )
)

然后将useMethodBody[0]更改为useMethodBody。希望它能够工作,但我实际上没有测试过,所以可能会有错误:)

相关问题