I am building an AST transformation that generates a void
method. I want to check whether the value passed in is already equal to another value, and if so, exit early. The code would ordinarily look like this:
if(param.is existing) {
return
}
The ReturnStatement
class has a property returningNullOrVoid
that checks to see whether the return expression is null
, so I tried the obvious approach:
ifS(sameX(paramEx, existingEx), returnS(constX(null))
This produced an exception when compiling the transformed class:
BUG! exception in phase 'instruction selection' in source unit 'Annotated.groovy' Unexpected return statement at -1:-1 return null
How can I insert the return statement for the early exit?
The ReturnStatement
class has a constant named 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);
The Groovy compiler checks for this specific instance to generate a void return;
. When creating an AST statement block that includes a return statement, your statement is "a synthetic return statement emitted by the compiler", and you should use that constant:
ifS(sameX(paramEx, existingEx), ReturnStatement.RETURN_NULL_OR_VOID)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.