[antlr-interest] Help getting started with a calculator

Simon sidefxboy at gmail.com
Thu Dec 28 02:05:14 PST 2006


Hi folks,

I hope someone might be able to help a real newbie who's trying to get
started with a simple calculator example. I've worked through the basic
getting started links that deal with calculators and wanted to expand on
them. Specifically I'm using the concepts from the following 2:

http://www.cs.usfca.edu/~parrt/course/652/lectures/antlr.html

http://supportweb.cs.bham.ac.uk/docs/tutorials/docsystem/build/tutorials/antlr/antlrhome.html

I want to expand on the ideas of the first one, using some of the ideas of
the second one.  I'm also generating output in C# if that changes anything.
The thing I don't like about the grammar in the second example is that it
seems to require parenthases around all expressions?  For example it fails
to evaluate 12 as an input but (12) works fine.

In any case, my real question is why the following grammar seems to work
fine in the parser:

expr     : prodExpr ((PLUS^|MINUS^) prodExpr)* ;
prodExpr : atom ((MUL^|DIV^|MOD^) atom)* ;
atom     : INT | LPAREN! expr RPAREN! ;

whereas the following causes odd behaviour (seems to skip the last token
when building the AST or something?):

expr     : prodExpr ((PLUS^|MINUS^) prodExpr)* ;
prodExpr : powExpr ((MUL^|DIV^|MOD^) powExpr )* ;
powExpr  : atom (POW^ atom)? ;
atom     : INT | LPAREN! expr RPAREN! ;

using the following lexer:

class YATTLexer extends Lexer;

options {
    k=2; // needed for newline junk
    charVocabulary='\u0000'..'\u007F'; // allow ascii
}

PLUS  : '+' ;
MINUS : '-' ;
MUL   : '*' ;
DIV   : '/' ;
MOD   : '%' ;
POW   : '^' ;
LPAREN: '(' ;
RPAREN: ')' ;
INT   : ('0'..'9')+ ;
WS    : (' ' | '\t' | '\r' | '\n') {$setType(Token.SKIP);} ;



No doubt I'm missing something obvious, but I'd appreciate any
enlightenment. :)

cheers!
Simon
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20061228/2cf509d5/attachment.html 


More information about the antlr-interest mailing list