[antlr-interest] Fw: a newbie question

Jim Idle jimi at temporal-wave.com
Wed Mar 25 09:01:51 PDT 2009


william yuan wrote:
> i am right here waitting for an answer ,thanks
>
> ----- Original Message ----- 
> From: "william yuan" <ordinarybackstreetmoldywilliam at gmail.com>
> To: <antlr-interest at antlr.org>
> Sent: Wednesday, March 25, 2009 11:23 PM
> Subject: a newbie question
>
>
>   
>> Hi ALL,
>> I have met another problem when i am tring to understand the antlr tree. 
>> here is my example
>> Cozily.g
>>
>> grammar Cozily;
>> options {
>>    output=AST;
>>    ASTLabelType=CommonTree; // type of $stat.tree ref etc...
>> }
>>
>> expr:    INT '+'^ INT
>> | INT '-'^ INT
>> |  INT '*'^ INT
>> |   INT '%'^ INT
>>    ;
>> INT :   '0'..'9'+ ;
>> WS  :   (' '|'\t'|'\n'|'\r')+ {skip();} ;
>> // END:tokens
>>
>> and the tree here CozilyTree.g
>>
>> tree grammar CozilyTree;
>>
>> options {
>>    tokenVocab=Expr;
>>    ASTLabelType=CommonTree;
>> }
>> prog:   expr{System.out.println($expr.value);} ;
>>
>> expr returns [int value]
>>    :   ^('+' a=INT b=INT) {$value = 
>> Integer.parseInt($a.text)+Integer.parseInt($a.text);}
>>    |   ^('-' a=INT b=INT) {$value = 
>> Integer.parseInt($a.text)-Integer.parseInt($a.text);;}
>>    |   ^('*' a=INT b=INT) {$value = 
>> Integer.parseInt($a.text)*Integer.parseInt($a.text);;}
>>    | ^('%' a=INT b=INT) {$value = 
>> Integer.parseInt($a.text)/Integer.parseInt($a.text);;}
>>    ;
>>
>> // END:expr
>>
>> I wanna make a calculator, only to get evaluate the expressions like '1+1' 
>> or '2*3' and of this sort,
>> but output is here
>> .....\CozilyTree.g: node from line 1:1 no viable alternative at input '+' 
>> when i inputted 1+1
>>
>> so what is the root cause ?
Stop using the literals '+' and so on and declare them as tokens in the 
parser/lexer combination:

PLUS : '+' ; ...etcc

Then make sure you generate the tree parser after you have generated the 
lexer/parser combined grammar. UNles you are not calling the code 
correctly, your tokens are probably out of sync.

Jim


More information about the antlr-interest mailing list