[antlr-interest] distinguishing between int and double in a tree grammar

Anders Hessellund anders.hessellund at gmail.com
Mon Mar 16 03:12:02 PDT 2009


Hi,

I've written a little tree grammar for an expression language. There are
three basic types int, double and boolean. My problem is that I can not
figure out how to distinguish between int and double without getting the
following error:

[fatal] rule compareExpr has non-LL(*) decision due to recursive rule
invocations reachable from alts 1,2.  Resolve by left-factoring or using
syntactic predicates or using backtrack=true option.

It is important to distinguish between these types because integer division
and double division return very different results. I guess someone must have
looked at this when doing type conversions/coercions. Here is my tree
grammar:

tree grammar Eval;
options {
    tokenVocab=Expr;
    ASTLabelType=CommonTree;
}
expr returns [boolean value]
    : boolExpr {$value=$boolExpr.value;}
    ;
boolExpr returns [boolean value]
    :    ^(OR bool1=boolExpr bool2=boolExpr) {$value=bool1||bool2;}
    |    ^(AND bool1=boolExpr bool2=boolExpr) {$value=bool1&&bool2;}
    |    ^(EQ bool1=boolExpr bool2=boolExpr) {$value=bool1==bool2;}
    |    ^(NEQ bool1=boolExpr bool2=boolExpr) {$value=bool1!=bool2;}
    |    ^(UNARY NOT bool1=boolExpr) {$value=!bool1;}
    |    BOOLEAN {$value=Boolean.parseBoolean($BOOLEAN.text);}
    |    compareExpr {$value=$compareExpr.value;}
    ;
compareExpr returns [boolean value]
    :    ^(EQ real1=realExpr real2=realExpr) {$value=real1==real2;}
    |    ^(EQ int1=intExpr int2=intExpr) {$value=int1==int2;}
    ;
realExpr returns [double value]
    :    ^(UNARY PLUS real1=realExpr) {$value=real1;}
    |    ^(UNARY MINUS real1=realExpr) {$value=-real1;}
    |    ^(DIV real1=realExpr real2=realExpr) {$value=real1/real2;}
    |    REAL {$value=Double.parseDouble($REAL.text);}
    ;
intExpr returns [int value]
    :    ^(UNARY PLUS int1=intExpr) {$value=int1;}
    |    ^(UNARY MINUS int1=intExpr) {$value=-int1;}
    |    ^(DIV int1=intExpr int2=intExpr) {$value=(int)int1/int2;}//truncate
    |    INTEGER {$value=Integer.parseInt($INTEGER.text);}
    ;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20090316/5d4979b3/attachment.html 


More information about the antlr-interest mailing list