specifying a grammar rule of "appearing in any order but only at most once"

Viewed 330

Say I have three symbols A, B, C.

In ANTLR, how do I specify that in a sentence, A, B, and C can appear at most once and that they can occur in any order. (For eg., ABC, BCA are both legit)

I tried

(A | B | C)*

knowing it'd only take care of the "any order" part, but couldn't think of a way to say it can only appear at most once.

Edited: I've tried using boolean flags, which worked but seems too hairy - there has to be a simpler way, yes?

myrule;
   {
       boolean aSeen = false;
       boolean bSeen = false;
       boolean cSeen = false;
   }
   :

   (   A { if (aSeen) throw RuntimeException("alraedy seen") else aSeen = true; }
   |   B { if (bSeen) throw RuntimeException("alraedy seen") else bSeen = true; }
   |   C { if (cSeen) throw RuntimeException("alraedy seen") else cSeen = true; }
   )*
   ;
1 Answers
Related