views:

28

answers:

1

In Antlr, if I have a rule for example:

someRule : TOKENA TOKENB;

it would accept : "tokena tokenb"

if I would like TOKENA to be optional, I can say,

someRule : TOKENA* TOKENB;

then I can have : "tokena tokenb" or "tokenb" or "tokena tokena tokenb"

but this also means it can be repeated more that once. Is there anyway I can say this token can be there 1 or less times but not more than one? so it would accept:

"tokena tokenb" or "tokenb" BUT NOT "tokena tokena tokenb"?

Many thanks

+3  A: 

... Is there anyway I can say this token can be there 1 or less times but not more than one? ...

Here's how:

someRule 
  :  TOKENA? TOKENB
  ;

or:

someRule 
  :  TOKENA TOKENB
  |  TOKENB
  ;
Bart Kiers
I understand the second option, I didn't think of being able to do that, my fail. The documentation says the the '?' is a 'semantic predicate' can you explain what a semantic predicate is?
Simon Kenyon Shepard
@Simon, no, `?` by itself means "match the preceding once or none at all".
Bart Kiers
@Simon, I was just leaving, but do you want me to post a follow up on what a semantic predicate is? If so, just leave a comment here and I'll post a reply later this evening.
Bart Kiers
@Bart K, that would be great I was using http://www.antlr.org/wiki/display/ANTLR3/ANTLR+Cheat+Sheet but it doesn't really explain what a semantic predicate is, and neither did googling it, so I assumed it was something else...
Simon Kenyon Shepard
@Simon, I posted a separate question (and answer) about semantic predicates here: http://stackoverflow.com/questions/3056441/what-is-a-semantic-predicate-in-antlr
Bart Kiers