Download ANTLR Reference Manual

Transcript
class CalcLexer extends Lexer;
WS
:
|
|
|
(' '
'\t'
'\n'
'\r')
{ _ttype = Token.SKIP; }
;
LPAREN: '('
;
RPAREN: ')'
;
STAR:
'*'
;
PLUS:
'+'
;
SEMI:
';'
;
INT
:
;
('0'..'9')+
The trees generated by this recognizer are simple expression trees. For example, input "3*4+5"
results in a tree of the form #( + ( * 3 4 ) 5 ). In order to build a tree walker for trees of
this form, you have to describe its structure recursively to ANTLR:
class CalcTreeWalker extends TreeParser;
expr
:
|
|
;
#(PLUS expr expr)
#(STAR expr expr)
INT
Once the structure has been specified, you are free to embed actions to compute the
appropriate result. An easy way to accomplish this is to have the expr rule return an integer
result and then have each alternative compute the subresult for each subtree. The following tree
grammar and actions produces the desired effect:
class CalcTreeWalker extends TreeParser;
expr returns [int r]
{
int a,b;
r=0;
}
:
#(PLUS a=expr b=expr) {r = a+b;}
|
#(STAR a=expr b=expr) {r = a*b;}
|
i:INT
{r =
Integer.parseInt(i.getText());}
;
65