2015-12-02 86 views
0

我正在构建一个生成void方法的AST转换。我想检查传入的值是否已经等于另一个值,如果是,请尽早退出。该代码通常会是这样的:如何在Groovy AST转换中创建一个void return语句?

if(param.is existing) { 
    return 
} 

ReturnStatement类有检查,看看返回的表达式是null属性returningNullOrVoid,所以我尝试了明显的方法:

ifS(sameX(paramEx, existingEx), returnS(constX(null)) 

如此制编译转换类时出现异常:

BUG! exception in phase 'instruction selection' in source unit 'Annotated.groovy' Unexpected return statement at -1:-1 return null 

如何插入返回语句早退出?

回答

2

ReturnStatement类有一个名为RETURN_NULL_OR_VOID常数:

/** 
* Only used for synthetic return statements emitted by the compiler. 
* For comparisons use isReturningNullOrVoid() instead. 
*/ 
public static final ReturnStatement RETURN_NULL_OR_VOID = new ReturnStatement(ConstantExpression.NULL); 

此特定情况下Groovy编译器检查,以产生一个空洞return;。当创建一个AST语句块中包含return语句,你的发言“由编译器发出的合成return语句”,你应该使用常数:

ifS(sameX(paramEx, existingEx), ReturnStatement.RETURN_NULL_OR_VOID)