4

我有这种语法,

locationPath returns [CustomParser xpathParser]  
    :^(LOCATION_PATH relativeLocationPath {**Want to throw a exception if this condition matches**})
    |^(LOCATION_PATH absoluteLocationPath {$xpathParser=$absoluteLocationPath.xpathParser;})
    ;

这样做的方法是什么?我试过这个

locationPath returns [CustomParser xpathParser]  
    :^(LOCATION_PATH relativeLocationPath {throw new Exception})
    |^(LOCATION_PATH absoluteLocationPath {$xpathParser=$absoluteLocationPath.xpathParser;})

但是使用这个生成的代码会产生编译错误。因为该方法 loactionapth 在方法签名处没有抛出线索。

4

1 回答 1

3

只有一种方法可以做到这一点:抛出未经检查的异常:

locationPath returns [CustomParser xpathParser]  
 : ^(LOCATION_PATH relativeLocationPath) {throw new RuntimeException("No way!");}
 | ^(LOCATION_PATH absoluteLocationPath {$xpathParser=$absoluteLocationPath.xpathParser;})
 ;

如果编译器仍然抱怨(我不记得了,而且我现在无法测试),请if(true)在它前面添加一个:

locationPath returns [CustomParser xpathParser]  
 : ^(LOCATION_PATH relativeLocationPath) {if(true) throw new RuntimeException("No way!");}
 | ^(LOCATION_PATH absoluteLocationPath {$xpathParser=$absoluteLocationPath.xpathParser;})
 ;
于 2012-10-08T21:51:16.243 回答