1. 配置IDE(可选)

2. 加减法示例

编写expr.g4

 grammar AddMinus;

 expr: Minus Number     #minusNum
| expr op=('+'|'-') expr #regular
| Number #single
;
Number:[-]+;
Minus:'-';
WS : [ \t\n\r]+ ->skip ;
Add:'+';

生成文件

实现listener 完成遍历

 public static class AddMinusListener extends AddMinusBaseListener{
private Stack<Integer> stack = new Stack<>(); /**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterMinusNum(AddMinusParser.MinusNumContext ctx) {
System.out.println("enter minus: " + ctx.getText());
System.out.println(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitMinusNum(AddMinusParser.MinusNumContext ctx) {
stack.push(Integer.valueOf(ctx.getText()));
}
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterRegular(AddMinusParser.RegularContext ctx) {
System.out.println("enter regular text: " + ctx.getText());
}
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitRegular(AddMinusParser.RegularContext ctx) {
if( ctx.op.getText().equals("+")){
stack.push(stack.pop() + stack.pop());
}else if( ctx.op.getText().equals("-")){
Integer peek = stack.pop();
stack.push(stack.pop() - peek);
} }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterSingle(AddMinusParser.SingleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitSingle(AddMinusParser.SingleContext ctx) { stack.push(Integer.valueOf(ctx.getText()));
} /**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitTerminal(TerminalNode node) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitErrorNode(ErrorNode node) { } public Integer getResult(){
if (stack.size() == 1){
return stack.peek();
}
return 0;
}
}

测试代码如下:

        CharStream stream = CharStreams.fromString("2+3-4");
AddMinusLexer lexer = new AddMinusLexer(stream);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
AddMinusParser parser = new AddMinusParser(tokenStream);
//parser.setBuildParseTree(true); AddMinusParser.ExprContext ctx = parser.expr();
System.out.println(ctx.toStringTree());
System.out.println("------------------ up string tree-------");
ParseTreeWalker walker = new ParseTreeWalker();
AddMinusListener listener = new AddMinusListener();
walker.walk(listener,ctx);
System.out.println(listener.getResult());
05-11 13:27