[antlr-interest] Formula Parser once again

Stritzel.Nils at infineon.com Stritzel.Nils at infineon.com
Wed Apr 19 04:08:17 PDT 2006


Hi,

I am currently implementing kind of a formula parser, after some start
problems I thought that I got the thing going. Now I am stuck again, all
the basic stuff multiplication and addition etc. was working fine, but
now want to call a function to calculate the the absolute value of
value. 
Actually this kind of thing should be rather easy, but my solution is
not working. I stepped through the code and there is a
RecognitionException after it found the functionCall token. I have spend
some hours on this problem, but still have no idea, maybe some can give
me a hint. 

Thank you,

Nils

options {
	language = "CSharp";
	namespace  =  "FormulaParsing";
}

class ExpressionParser extends Parser;
options {
	buildAST = true;	// uses CommonAST by default
	k = 3;
}

imaginaryTokenDefinitions :
	SIGN_MINUS
	SIGN_PLUS
;

expr : formula ;
formula : 
	BATCHCSID ASSIGN^ batchExpr EOF
	;
	

batchExpr :sumExpr ;
sumExpr  : prodExpr ((PLUS^|MINUS^) prodExpr)* ; 
prodExpr : baseExpr ((MULT^|DIV^|MOD^) baseExpr)* ;

baseExpr : primaryExpr | signedExpr;
signedExpr: 
         (m:
         MINUS^ {#m.setType(SIGN_MINUS);}
         |p:
         PLUS^  {#p.setType(SIGN_PLUS);})         
	baseExpr;
	

	
primaryExpr
  : DOUBLE
  | (LPAREN^ batchExpr RPAREN! )
  | functionCall
  ;
  
  
functionCall : CSIGN^ LPARENT^ batchExpr RPARENT!      
  	     ;
  	


class ExpressionLexer extends Lexer;

options {
	k = 4;
}

PLUS  : '+' ;
MINUS : '-' ;
MULT   : '*' ;
DIV   : '/' ;
MOD   : '%' ;
POW   : '^' ;
SEMI  : ';' ; 
LPAREN : '(' ;
RPAREN : ')' ;
protected DIGIT : '0'..'9' ;
protected LETTER: ('a'..'z') ;
protected IDENT : LETTER (('_')* (LETTER|DIGIT))? ;
WS :
	(' '
	| '\t'
	| '\r' '\n' {newline(); }
	| '\n'	{newline(); }
	)
	{ $setType(Token.SKIP); };
	
DOUBLE 		:	(DIGIT)+ ('.' (DIGIT)+)? ('e' (MINUS|PLUS)?
(DIGIT)+ )? ;	

ASSIGN		:       '=' ;

BATCHCSID	:	"bsc." IDENT ;


CABS	:  "c_abs";




class ExpressionTreeWalker extends TreeParser;

expr returns [EvalResult result]
  { string a; double b; result = null; }
  : #(ASSIGN batchId :BATCHCSID b=batchExpr) {result = new
BatchEvalResult(batchId.getText(),b); } ;


bracketExpr returns [double r]
{double a; r=0; }
: #(LPAREN a=batchExpr) {r=a; }
;
batchExpr returns [double r]
  { double a, b; r=0 ; string c;}
  : #(PLUS  a=batchExpr b=batchExpr) { r = a + b;}
  | #(MINUS a=batchExpr b=batchExpr) { r = a - b;}
  | #(MULT   a=batchExpr b=batchExpr) { r = a * b;}
  | #(DIV   a=batchExpr b=batchExpr) { r = a / b; }
  | #(LPAREN a=batchExpr) { r=a;}
  | #(SIGN_MINUS a=batchExpr)   { r=-1*a; } 
  | #(SIGN_PLUS  a=batchExpr)   { r=a; }
  | #(CABS a=batchExpr) { r= Math.Abs(a); }
  |i :DOUBLE  { r=(double) Double.Parse(i.getText());}
  ;
  


More information about the antlr-interest mailing list