Expression Grammar question
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

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

Re: Expression Grammar question

Posted By:   Monty_Zukowski  
Posted On:   Monday, January 12, 2004 10:04 AM

You need to have EOF specified at the end of your top level rule expr. It is seeing the RPAREN, realizing it can't be matched, and then exiting the parser. Try this:

expr: mexpr ((PLUS^|MINUS^) mexpr)* EOF
;
About | Sitemap | Contact