[antlr-interest] Problems with semantic predicates

Haralambi Haralambiev hharalambiev at gmail.com
Thu Apr 17 10:03:01 PDT 2008


Hello Johannes,

So, if I understand correctly, you suggest to have the following (using a
scope):

r2
: {$r::flag}? Token1 -> ^(NODE Token1)
| Token1
;

If the above is a correct assumption, then how can I set the scope variable,
as I could only think of the following way:

r
scope {
  boolean flag;
}
: Token1^ Token2!
    {$r::flag = true;}
    r2
| Token1^
  {$r::flag = false;}
  r2
;

This solution, however, will fail, as the action for setting the scope
variable will not be executed until the backtracking is over. But I need
this variable set, as it will be used as a predicate for the parsing. Thus,
we have a catch-22 situation.

A solution I could think of is not to have two alternatives for r2, but
rather construct the CommonTree manually with java code and within to use
the knowledge of the boolean flag. But I dislike this solution and am open
to suggestions.

Hari



On 4/17/08, Johannes Luber <jaluber at gmx.de> wrote:
>
> 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20080417/c7312554/attachment.html 


More information about the antlr-interest mailing list