[antlr-interest] Problems with semantic predicates

Johannes Luber jaluber at gmx.de
Thu Apr 17 09:55:08 PDT 2008


Haralambi Haralambiev schrieb:
> Hello,
> 
> First of all, thanks for the magnificent tool. I 
> consider myself new to advanced stuff, as I have been working with it for less than a month.
> 
> So, the problem that I currently cannot resolve is described by the 
> following test grammar:
> 
> ----------
> grammar test;
> 
> options {
> output=AST;
> ASTLabelType=CommonTree;
> backtrack=true;
> memoize=true;
> }
> 
> tokens
> {
> NODE;
> }
> 
> r : Token1^ Token2! r2[true]
> | Token1^ r2[false]
> ;
> r2[boolean flag]
> : {flag}? Token1 -> ^(NODE Token1)
> | Token1
> ;
> 
> Token1 : 'TOKEN1';
> Token2 : 'TOKEN2';
> ----------
> 
> The general idea is that depending on how one rule matches, I would like 
> a subrule to generate the AST differently.
> 
> I decided to do this with some boolean flag, but 
> the problem is that the generated Java parser class cannot compile.
> In the example above - the method *synpred2_fragment()* contains a 
> statement */if ( !(flag) )/* but the variable flag cannot be resolved.
> 
> So, if you could please guide me how to resolve this problem. Maybe I 
> have missed something fundamental in my understandings for developing 
> the grammar.

The problem is that flag is in a hoisted method which doesn't know about 
flag. You have to use either a member variable or a scope to workaround 
this problem.

Johannes


More information about the antlr-interest mailing list