2

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

Simon Kenyon Shepard
  • 849
  • 2
  • 11
  • 23

1 Answers1

6

... 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
  • 166,582
  • 36
  • 299
  • 288
  • 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 Jun 16 '10 at 14:13
  • @Simon, no, `?` by itself means "match the preceding once or none at all". – Bart Kiers Jun 16 '10 at 14:24
  • @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 Jun 16 '10 at 14:26
  • 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 Jun 16 '10 at 15:26
  • @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 Jun 16 '10 at 19:29