我有这种语法,

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不会抛出方法签名的线索。

最佳答案

仅有的一种方法:抛出未检查的异常:

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;})
 ;

08-05 17:15