[antlr-interest] Is this stylistically good Antlr code?

Philip Hunt Philip.Hunt at advent-comm.co.uk
Tue Dec 3 07:58:07 PST 2002


I am starting to use Antlr. As an exercise, I have written an expression
calculator that does 4 functions plus parentheses. It works, but I'm not
sure whether it is well-written.

Could someone look at it please, and tell me whether it is stylistically
good 
Antlr code? The code follows:


/* philcalc.g = Phil's example calculator parser */
/*------------------------------------------------------------------*/

class CalcLexer extends Lexer;

protected DIGIT: '0'..'9';

INT: (DIGIT)+;

ADD_OP : '+' | '-';

MUL_OP : '*' | '/' ;

CR : '\n' | '\r' ;

WS : (' '|'\t') { _ttype = Token.SKIP; };


/*------------------------------------------------------------------*/
class CalcParser extends Parser;


stmt returns [float f=0]:
f=expr nl;

nl : (CR)*;

expr returns [float f=0]: 
f=addexpr ;

addexpr returns [float f=0]: {float m=0;}
f=mulexpr
(s:ADD_OP m=mulexpr
{
   if (s.getText().equals("+")){
      f += m;
   } else {
      f -= m;   
   }
}
)* ;

mulexpr returns [float f=0]: {float t=0;}
f=term
(s:MUL_OP t=term 
{
   if (s.getText().equals("*")){
      f *= t;
   } else {
      f /= t;
   }
}
)* ;

term returns [float f=0]: 
"(" f=expr ")"
| 
f=atom ;

atom returns [float f=0]: 
s:INT { f = (float)Integer.parseInt(s.getText()); }
;

/*------------------------------------------------------------------*/


-- 
Philip Hunt, <Philip.Hunt at advent-comm.co.uk>
This message is intended for the addressee only. It must not be disclosed
to, altered, copied or used by anyone other than the addressee(s). If you
have received this message in error, please notify our email administrator
at   postmaster at advent-comm.co.uk <mailto:postmaster at advent-comm.co.uk> and
destroy the message, removing it completely from your computer system. 
Thank you for your assistance. 

Mail Virus Warning
-------------------------------

This email and any attachment are believed to be free from viruses which
might affect any system into which they are received or opened, it is the
responsibility of the recipient to ensure that they are virus free.
 Advent Communications accepts no liability whatsoever for any direct,
indirect or consequential loss or damage arising in any way from receipt,
opening or use.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20021203/7b34c344/attachment.html


More information about the antlr-interest mailing list