[antlr-interest] Rule question.

John B. Brodie jbb at acm.org
Sun Apr 9 15:51:34 PDT 2006


Greetings!

>I have a question regarding Parser rules.
>Let's say, I have the following rules in my lexer.
>
>A : 'a';
>B : 'b';
>C ; 'c';
>
>These three rules are all mandatory and must be present in the source file.
>BUT the order of appearance in the source file is of no importance. One
>could enter abc or cba or bca, cab in the source file.
>
>How do I describe that in my parser rules?

Two ways that seem fairly common...

1) enumerate all six of the possibilities in a single (left-factored)
   rule, something similar to:

   the_abcs:
        ( A ( ( B C ) | ( C B ) ) )
      | ( B ( ( A C ) | ( C A ) ) )
      | ( C ( ( A B ) | ( B A ) ) )
      ;

or

2) allow any combination and use action code to enforce the single
   appearance rule, for example:

   the_abcs: { int a = 0; int b = 0; int c = 0; }
         ( A { ++a; } | B { ++b; } | C { ++c; } )+
         { if ((a!=1) || (b!=1) || (c!=1)) { ...generate error here... } }
         ;

hope this helps...
    -jbb


More information about the antlr-interest mailing list