[antlr-interest] Problem on left associative for AST

Jack Jack jackantlr at gmail.com
Fri Aug 7 08:59:38 PDT 2009


I have spent a lot of time on this issue, but failed to find a solution,
really hope that some kind soul could help.

Following is the definition of the grammar
Expr::=
                CONST
                |Expr>Expr //OUTPUT(left associative)
                |Expr<Expr //INPUT(right associative)
                |Expr;Expr //SEQUENCE(left associative)
                |if Expr then Expr else Expr //IF
CONST::=Boolean|Number|String

">" is right associative, "<" and ";" are left associative, the syntactic
constructs of Expr are ordered by precedence, from highest to lowest,
For examples "Expr>Expr" has higher precedence then "Expr<Expr"

Some examples
"if true then 1 else 1>1" will be interpreted as "if true then 1 else (1>1)"
"1>1>if true then 1 else 1" will be interpreted as "1>(1>if true then p else
1)"
"1<1<if true then 1 else 1" will be interpreted as "(1<1)<if true then p
else 1"
"1;2;if true then 1 else 1" will be interpreted as "((1;2); if true then 1
else 1);

I am having problem in defining left associative for AST, what I can achieve
is only right associative, following is the ANTLR grammar that defined by
me:
//====ANTLR GRAMMAR START===
grammar ORCTree;

options
{
    output=AST;
    ASTLabelType=CommonTree;
    backtrack = true;
    memoize=true;
}


tokens {
    OUTPUT_NODE;
    INPUT_NODE;
    SEQUENCE_NODE;
    IF_NODE;
}


expr
    : ifExpr
    ;

ifExpr
    : 'if' s1=expr 'then' s2=expr 'else' s3=expr ->^(IF_NODE $s1 $s2 $s3)
    | sequenceExpr
    ;

sequenceExpr
    : s1=inputExpr (';'^ s2=expr)*
    | inputExpr
    ;

inputExpr
    : p=outputExpr ('<'^ e=expr)*
    | outputExpr;

outputExpr
    : p=constExpr ('>'^ e=expr)*
    | constExpr;

constExpr
    :
    |CONST
    | '('! expr ')'!
    ;


WS  :  (' '|'\r'|'\t'|'\u000C'|'\n') {$channel=HIDDEN;} ;

fragment
STRING
    :  '"' (~('"') )* '"';

fragment
NUM
    : ('0'..'9')'.'('0'..'9')+
    |    ('1'..'9')('0'..'9')*
    ;
fragment
BOOL
    : 'true'
    |    'false'
    ;

CONST
    :    BOOL
    |    STRING
    |    NUM;
//====ANTLR GRAMMAR END===

outputExpr and sequenceExpr both are currently right associative(which is
not correct), may I know how to make them left associative?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20090807/2db88719/attachment.html 


More information about the antlr-interest mailing list