[antlr-interest] Is this stylistically good Antlr code?
mzukowski at yci.com
mzukowski at yci.com
Tue Dec 3 08:41:12 PST 2002
Typically you would use the token type to tell whether it was PLUS or MINUS
instead of testing the text itself.
PLUS: "+"
MINUS:"-"
addexpr returns [float f=0]: {float m=0;}
f=mulexpr
(PLUS m=mulexpr { f += m; }
| MINUS m=mulexpr { f -=m; }
)* ;
Otherwise it looks good to me.
Monty
-----Original Message-----
From: Philip Hunt [mailto:Philip.Hunt at advent-comm.co.uk]
Sent: Tuesday, December 03, 2002 7:58 AM
To: 'antlr-interest at yahoogroups.com'
Subject: [antlr-interest] Is this stylistically good Antlr code?
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.
Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.
Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
More information about the antlr-interest
mailing list