[antlr-interest] syntax predicates

Terence Parr parrt at jguru.com
Sat Sep 14 20:56:01 PDT 2002


On Thursday, September 12, 2002, at 04:09  PM, richardhensley99 wrote:

> I have a question about syntax predicates because I think I found a
> bug.
>
> I have the following grammar snippet
>
> startRule
> :   (   "create" (("or" "replace" "force" "view") => createView)?
>     |   skipTokens
>     )* EOF
> ;
>
> createView
>     :   (ID)* "view"
>     ;
>
> skipTokens
>     :   ~("create")
>     ;

The code below is correct.  ANTLR is being smart and putting in a quick 
sanity check before doing the backtrack.  ANTLR checks that the 
lookahead is reasonably (i.e., consistent with matching rule 
createView) before wasting time doing a predicate.  Note that the 
lookahead for createView is {ID,"view"} at k=1.  The "view" test does 
not come from the last token in the predicate.  BTW, the predicate you 
have makes no sense really.

> And it generates the following code in the startRule method
>
> case LITERAL_create :
>     {
>         AST tmp1_AST = null;
>         tmp1_AST = (AST) astFactory.create(LT(1));
>         astFactory.addASTChild(
>             currentAST,
>             tmp1_AST);
>         match(LITERAL_create);
>         {
>             boolean synPredMatched2949 = false;
>             if (((LA(1) == LITERAL_view
>                 || LA(1) == ID)
>                 && (_tokenSet_0.member(LA(2)))
>                 && (_tokenSet_0.member(LA(3)))
>                 && (_tokenSet_0.member(LA(4))))) {
>                 int _m2949 = mark();
>                 synPredMatched2949 = true;
>                 inputState.guessing++;
>                 try {
>                     {
>                         match(LITERAL_or);
>                         match(LITERAL_replace);
>                         match(LITERAL_force);
>                         match(LITERAL_view);
>                     }
>                 }
>                 catch (RecognitionException pe) {
>                     synPredMatched2949 = false;
>                 }
>                 rewind(_m2949);
>                 inputState.guessing--;
>             }
>
> The problem seems to be the following line of code:
>
> if (((LA(1) == LITERAL_view
>     || LA(1) == ID)
>
> Which is generated because of the syntax predicate, however the

Actually it's generated because that predicates createView.  Somewhere 
in a paper or something I show that ANTLR prevents unnecessary 
backtracking by doing a quick sanity check.

Hope this clears this up.

Ter
--
Co-founder, http://www.jguru.com
Creator, ANTLR Parser Generator: http://www.antlr.org


 

Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/ 



More information about the antlr-interest mailing list