[antlr-interest] Usage of scopes in v3

Kay Roepke kroepke at classdump.org
Sat Oct 21 02:42:01 PDT 2006


Hi Ter,*!

I have played around with dynamic rule scopes over the last week or  
so and was wondering what the current best-practice was.
If you consider the symtab example for v3 below, I was wondering how  
you would go ahead in an implementation of a symbol table while using  
scopes.

A naïve approach would be the @finally action below, which fails  
because right before the comment the current Symbol scope would be  
popped from the block. You would naturally need to access the Symbol  
scope to enter its entries into your program's symbol table which  
would not go away when the rule exits. The obvious solution is to add  
an action to the end of the rule block to do the transition so it  
doesn't execute when the rule fails.
Is this actually the recommended way or is there something I  
overlook? The downside with the @finally route is of course that it  
gets executed regardless whether the rule failed or not, so you'd  
have to guard against that manually. Same goes for backtracking.

cheers,
-k

grammar SymtabTestParser;

/* Scope of symbol names.  Both globals and block rules need to push  
a new
* symbol table upon entry and they must use the same stack.  So, I must
* define a global scope and say that globals and block use this by  
saying
* 'scope Symbols;' in those rule definitions.
*/
scope Symbols {
   List names;
}
[...]
block
scope Symbols;
@init {
     level++;
     $Symbols::names = new ArrayList();
}
@finally {
         // is $Symbols::names still valid here?
}
     :   '{' (decl)* (stat)* '}'
         {
         System.out.println("level "+level+" symbols: "+ 
$Symbols::names);
         level--;
         }
     ;
[...]


-- 
Kay Röpke <kroepke at classdump.org>
classdump Software
Key fingerprint = A849 0F2C C322 4022 379E  8661 7E1B FE0D 4CD2 A6D0





More information about the antlr-interest mailing list