-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathMainListen.java
More file actions
76 lines (65 loc) · 2.49 KB
/
MainListen.java
File metadata and controls
76 lines (65 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/***
* Excerpted from "The Definitive ANTLR 4 Reference",
* published by The Pragmatic Bookshelf.
* Copyrights apply to this code. It may not be used to create training material,
* courses, books, articles, and the like. Contact us if you are in doubt.
* We make no guarantees that this code is fit for any purpose.
* Visit http://www.pragmaticprogrammer.com/titles/tpantlr2 for more book information.
***/
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Stack;
public class MainListen {
private static class Listener extends CalculatorBaseListener {
private Stack<Integer> stack = new Stack<Integer>();
public int getResult() {
return stack.peek();
}
@Override
public void exitMulDiv(CalculatorParser.MulDivContext ctx) {
int right = stack.pop();
int left = stack.pop();
int result;
if (ctx.op.getType() == CalculatorParser.MUL) {
result = left * right;
} else {
result = left / right;
}
stack.push(result);
}
@Override
public void exitAddSub(CalculatorParser.AddSubContext ctx) {
int right = stack.pop();
int left = stack.pop();
int result;
if (ctx.op.getType() == CalculatorParser.ADD) {
result = left + right;
} else {
result = left - right;
}
stack.push(result);
}
@Override
public void exitInt(CalculatorParser.IntContext ctx) {
stack.push(Integer.valueOf(ctx.INT().getText()));
}
}
public static void main(String[] args) throws Exception {
String inputFile = null;
if ( args.length>0 ) inputFile = args[0];
InputStream is = System.in;
if ( inputFile!=null ) is = new FileInputStream(inputFile);
ANTLRInputStream input = new ANTLRInputStream(is);
CalculatorLexer lexer = new CalculatorLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
//System.out.println(tokens.getText());
CalculatorParser parser = new CalculatorParser(tokens);
ParseTree tree = parser.expr(); // parse
ParseTreeWalker walker = new ParseTreeWalker();
Listener listener = new Listener();
walker.walk(listener, tree);
System.out.println(listener.getResult());
}
}