Don’t try to do that in the grammar. Allow as many of each as possible,
then reject additional ones via semantics – see antlr.markmail.org for many
past answers as to why, but basically you will have:



Error @line 4, offset 34: Additional b construct is illegal, only one is
allowed….



Instead of:



Syntax error @line 4, offset 34: Found ‘b’, expecting one of a, c



The first is a lot easier for your users to understand:



opt

@init

{

  boolean haveA = false;

}

: (a { if (haveA) { /* error  message **/} else {haveA = true;} } | b | c)**

;



In general this is the best way to handle most errors – push them as far
down the tool chain as you can so that you report more errors in one
execution of the tool chain.



Jim



*From:* [email protected] [mailto:[email protected]] *On
Behalf Of *Mike Lischke
*Sent:* Wednesday, April 18, 2012 8:32 AM
*To:* ANTLR Mailing Mailing List
*Subject:* [antlr-dev] Single optional alternatives



Hi,



I'm looking for a grammatical construct that allows me to have several
optional alternatives, but only once each. When I use



opt: ( a | b | c)*;



then I can have each alternative in any order (good) but they can appear
more than once (bad). How would I define this to allow each of the only
once or not at all, in any order? I could of of course define any possible
permutation, but there must be a better way (especially when we come to 10+
alternatives).



Any idea?



Mike
-- 
www.soft-gems.net
_______________________________________________
antlr-dev mailing list
[email protected]
http://www.antlr.org/mailman/listinfo/antlr-dev

Reply via email to