[antlr-interest] Bounded Closures?

Wincent Colaiuta win at wincent.com
Tue Jun 26 13:41:22 PDT 2007


El 26/6/2007, a las 22:31, Johannes Luber escribió:

> Wincent Colaiuta wrote:
>> Doesn't the += notation you've used there only work in parser  
>> rules? I
>> don't think it works in lexer rules.
>
> I haven't tested that particular code snippet with appropriate input,
> but the compiler doesn't complain, so I guess that it works. Besides
> Terence himself acknowledged my code snippet and I don't believe  
> that he
> has overlooked "fragment" at the beginning.

I made a simple test grammar:

   grammar Simple;

   a : A EOF ;
   A: B ;
   fragment
   B : (foo+='a')+ {$foo;} ;

And the generated (Java) code for the "mB" method is as follows; note  
that list_foo is initialized to null and not modified when 'a' is  
matched:

     // $ANTLR start B
     public final void mB() throws RecognitionException {
         try {
             Token foo=null;
             List list_foo=null;
             // Simple.g:8:5: ( (foo+= 'a' )+ )
             // Simple.g:8:5: (foo+= 'a' )+
             {
             // Simple.g:8:5: (foo+= 'a' )+
             int cnt1=0;
             loop1:
             do {
                 int alt1=2;
                 int LA1_0 = input.LA(1);

                 if ( (LA1_0=='a') ) {
                     alt1=1;
                 }


                 switch (alt1) {
                 case 1 :
                     // Simple.g:8:6: foo+= 'a'
                     {
                     foo = input.LA(1);
                     match('a');

                     }
                     break;

                 default :
                     if ( cnt1 >= 1 ) break loop1;
                         EarlyExitException eee =
                             new EarlyExitException(1, input);
                         throw eee;
                 }
                 cnt1++;
             } while (true);

             list_foo;

             }

         }
         finally {
         }
     }
     // $ANTLR end B

If the += construct is used in a parser rule instead, then ANTLR does  
indeed generate code for updating list_foo upon each match:

             if (list_foo==null) list_foo=new ArrayList();
             list_foo.add(foo);

Cheers,
Wincent



More information about the antlr-interest mailing list