Monday, April 28, 2008

Use Scope definition instead of rule parameters in ANTLR3

In the SimpleC to LLVM translation project, I need to pass a parameter as a flag variable into a parser rule.  However, if I add a parameter to the rule declaration, I have to change all the references to that rule into rule[args].

As an alternative solution, I use Scope definition and put that flag variable in to the declared scope.  Whenever I need that flag variable, I can import that global scope within the parser rule to get reference to that variable.  

In this case:
grammar G;
assignment
scope {boolean isLeftHandSide;}
    :  {$assignment::isLeftHandSide=true;}ID '=' 
       {$assignment::isLeftHandSide=false;}ID
    ;
...
expression 
    :  ID {if($assignment::isLeftHandSide) doSomething();}
    ;

Reference: The Definitive ANTLR Reference, chapter 4.5