[antlr-interest] Formula parser and optional brackets
Stritzel.Nils at infineon.com
Stritzel.Nils at infineon.com
Sun Apr 16 23:18:26 PDT 2006
Hi,
I am trying to implemend a formula parser with antlr. The formulas are
from an already existant database. The fact that brackets are optinal
gives me some headaches. So far I created this grammar which works for
some cases, but it does not work for formulas like "(1)" and furthermore
it does work for formulas "0+1)" which it should not do. If somebody can
give me a hint what's wrong with this, I would greatful.
Regards,
Nils
The grammar:
class ExpressionParser extends Parser;
options {
buildAST = true;
}
expr : (sumBaseExpr) => (LPAREN^ sumBaseExpr RPAREN! (PLUS^ |
MINUS^ |MULT^ |DIV^) sumBaseExpr)
|(complexExpr) => (LPAREN^ sumBaseExpr
RPAREN!) | sumBaseExpr ;
complexExpr : LPAREN^ sumBaseExpr RPAREN!;
sumBaseExpr : prodBaseExpr ((PLUS^|MINUS^) prodBaseExpr)* ;
prodBaseExpr : powBaseExpr ((MUL^|DIV^|MOD^) powBaseExpr)* ;
powBaseExpr : atomBase (POW^ atomBase)? ;
atomBase : INT | complexExpr;
class ExpressionLexer extends Lexer;
PLUS : '+' ;
MINUS : '-' ;
MUL : '*' ;
DIV : '/' ;
MOD : '%' ;
POW : '^' ;
SEMI : ';' ;
LPAREN : '(' ;
RPAREN : ')' ;
protected DIGIT : '0'..'9' ;
INT : (DIGIT)+ ;
WS :
(' '
| '\t'
| '\r' '\n' {newline(); }
| '\n' {newline(); }
)
{ $setType(Token.SKIP); };
class ExpressionTreeWalker extends TreeParser;
expr returns [double r]
{ double a, b; r=0 ;}
: #(PLUS a=expr b=expr) { r = a + b;}
| #(MINUS a=expr b=expr) { r = a - b;}
| #(MUL a=expr b=expr) { r = a * b;}
| #(DIV a=expr b=expr) { r = a / b;}
| #(MOD a=expr b=expr) { r = a % b;}
| #(POW a=expr b=expr) { r = Math.Pow(a, b);}
| #(LPAREN a=expr) { r=a;}
|i :INT { r=(double) Int32.Parse(i.getText());}
;
More information about the antlr-interest
mailing list