[antlr-interest] match parser rule inside every rule (compile time reflections)

Daniels, Troy (US SSA) troy.daniels at baesystems.com
Mon Jan 10 12:59:52 PST 2011


It seems likely your grammar has a form like:

start: class+ ;

class: CLASS NAME LP declarations* methods* RP;

declaration: TYPE NAME (COMMA NAME)* SEMI;

method: NAME argList LP statement* RP;

statement: assign | methodCall | returnStatement | ifStatement | whileLoop | ... ;

Followed by rules that are fairly specific.  Assuming that there are reasonable restrictions on where the reflection calls can go, you should be able to rewrite the above as 

start: class+ ;

class: FORALL argList LP class RP |
	   CLASS NAME LP declarations* methods* RP;

declaration: FORALL argList LP declaration RP |
			 TYPE NAME (COMMA NAME)* SEMI;

method: FORALL argList LP method RP | 
		NAME argList LP statement* RP;

statement: FORALL argList LP statement RP | 
		   assign | methodCall | returnStatement | ifStatement | whileLoop | ... ;

But then the rules I skipped do not need to be aware of the FORALL construct.  OTOH, if you can do things like

	x = 3 + #for_all($m,Test at intVars) { $m + } y; // x = 3 + i + j + y;

Then you might need to spread the details for FORALL throughout the grammar.  Think about where the reflection commands can go in the most abstract terms, then create rules for those situations. 

Troy
> -----Original Message-----
> From: antlr-interest-bounces at antlr.org 
> [mailto:antlr-interest-bounces at antlr.org] On Behalf Of Alexander Herz
> Sent: Friday, January 07, 2011 7:59 AM
> To: antlr-interest at antlr.org
> Subject: Re: [antlr-interest] match parser rule inside every 
> rule (compile time reflections)
> 
> Hi,
> 
> I'm trying to implement compile time reflections, so inside 
> the language (imagine java) there is a preprocessor like 
> language which can access static properties of elements 
> defined in the language:
> 
> Example:
> 
> class Test
> {
>      int i,j;
> 
>      Test()
>      {
>          //iterates over all members of Test
>          #for_all($m,Test at members)
>          {
>              $m=0;
>          }
>          //will be evaluated to:
>          i=0;
>          j=0;
>      }
> }
> 
> It doesn't make sense to implement this in a preprocessor 
> since the full AST is needed to process the #for_all directive.
> Therefore, I'd like to implement it in the grammar of the 
> language. Now, the problem is that the #for_all (and other 
> related directives) can be placed anywhere (outside of 
> classes, etc). So I would need to put the rule for #for_all 
> into all the rules inside my grammar which seems ugly and cumbersome.
> 
> Any ideas how to solve this?
> 
> Thx,
> Alex
> 
> 
> 
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: 
> http://www.antlr.org/mailman/options/antlr-interest/your-email-address
> 


More information about the antlr-interest mailing list