4

I have this kind of a grammar,

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

What is the way to do it? I tried with this one

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

But with this one the generated code gives compile Error. Because that method loactionapth doesn't have throws clues at method signature.

user1201210
  • 3,801
  • 22
  • 25
andunslg
  • 781
  • 14
  • 38

1 Answers1

3

Only one way to do this: throw an unchecked exception:

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

If the compiler still complains (I can't remember, and I'm not able to test right now), add an if(true) in front of it:

locationPath returns [CustomParser xpathParser]  
 : ^(LOCATION_PATH relativeLocationPath) {if(true) throw new RuntimeException("No way!");}
 | ^(LOCATION_PATH absoluteLocationPath {$xpathParser=$absoluteLocationPath.xpathParser;})
 ;
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • OK I think this will work. But I tried with locationPath returns [CustomParser xpathParser] throws MyCustom Exception Then the method is generated with throws clause. But Antlr works say the grammar is incorrect. – andunslg Oct 09 '12 at 01:32
  • It works when I extend my Exception class form runtime exception. Thanks for the help. – andunslg Oct 09 '12 at 01:40