grammar Expr;
prog: stat+;
stat: expr NEWLINE
| ID '=' expr NEWLINE
| CLEAR NEWLINE
| NEWLINE
;
expr: expr op=('*'|'/') expr
| expr op=('+'|'-') expr
| INT
| ID
|'(' expr ')';
MUL :'*';
DIV :'/';
ADD :'+';
SUB :'-';
ID :[a-zA-Z]+;// match identifiers
INT :[0-9]+;// match integers
NEWLINE:'\r'?'\n';// return newlines to parser (is end-statement signal)
WS :[ \t]+-> skip ;// toss out whitespace
自定义Visitor:
//EvalVistor.javaimport java.util.HashMap;import java.util.Map;publicclassEvalVisitorextendsLabeledExprBaseVisitor<Integer>{
/** "memory" for our calculator; variable/value pairs go here */
Map<String, Integer> memory =newHashMap<String, Integer>();/** ID '=' expr NEWLINE */@Overridepublic Integer visitAssign(LabeledExprParser.AssignContext ctx){
String id = ctx.ID().getText();// id is left-hand side of '='int value =visit(ctx.expr());// compute value of expression on right
memory.put(id, value);// store it in our memoryreturn value;}/** expr NEWLINE */@Override<