2015-12-02 82 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)