Posted By:
Andres_Chaves
Posted On:
Friday, January 9, 2004 06:08 AM
Hello, im a beginner in Antlr. Im trying to do a parser/lexer for arithmetic expressions. I took the beginner's example from the Getting Started with antlr, and modified it, for variable support. The .g file is this: options { language = "CSharp"; } class CalcParser extends Parser; options { buildAST=true; } expr: mexpr ((PLUS^|MINUS^) mexpr)* ; mexpr : atom ((STAR^|DIVIDE^) atom)* ; atom: INT | LPAREN! expr RPAREN! | VARIABLE ; class CalcLexer extends Lexer; options { k=2; // needed for newline junk charVocabulary='u0000'..'u007F'; // allow ascii } LPAREN:
More>>
Hello, im a beginner in Antlr. Im trying to do a parser/lexer for arithmetic expressions. I took the beginner's example from the Getting Started with antlr, and modified it, for variable support. The .g file is this:
options {
language = "CSharp";
}
class CalcParser extends Parser;
options {
buildAST=true;
}
expr: mexpr ((PLUS^|MINUS^) mexpr)*
;
mexpr
: atom ((STAR^|DIVIDE^) atom)*
;
atom: INT
| LPAREN! expr RPAREN!
| VARIABLE
;
class CalcLexer extends Lexer;
options {
k=2; // needed for newline junk
charVocabulary='u0000'..'u007F'; // allow ascii
}
LPAREN: '(' ;
RPAREN: ')' ;
PLUS : '+' ;
MINUS : '-' ;
STAR : '*' ;
DIVIDE : '/';
INT : ('0'..'9')+ ;
VARIABLE
: ('a'..'z'|'A'..'Z')+
;
WS : ( ' '
| '
' '
'
| '
'
| ' '
)
{$setType(Token.SKIP);}
;
class CalcTreeParser extends TreeParser;
options {
importVocab=CalcParser;
}
expr returns [double r=0]
{ double a,b; }
: #(PLUS a=expr b=expr) {r = a+b;}
| #(MINUS a=expr b=expr) {r = a-b;}
| #(STAR a=expr b=expr) {r = a*b;}
| #(DIVIDE a=expr b=expr) {r = a/b;}
| i:INT {r = (int)Int32.Parse(i.getText());}
| j:VARIABLE {r = 2;}
;
The parser is so cool, but give me a valid response with expressions like (a+b))-c, moreover if you enter (3+4))-3 you get a result equal to 7...
What can i do to solve this problem?
Thanks in Advance,
Andres
<<Less