-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimpleInfixCalculator.java
56 lines (51 loc) · 1.92 KB
/
SimpleInfixCalculator.java
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
/*
* SimpleInfixCalculator.java -- Interprets simple arithmetic expressions.
*
* Examples of usage:
* $ echo 5 | java SimpleInfixCalculator
* 5
*
* $ echo "2 + 3" | java SimpleInfixCalculator
* 5
*
* $ echo "(3 * 2 + 1) * 5 | java SimpleInfixCalculator
* 35
*
* Michael McThrow
* CS 152 -- Section 06
* San José State University
* Fall 2021
*/
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import java.io.*;
public class SimpleInfixCalculator {
public static void main(String[] args) throws IOException {
// 1. Read input from standard input, creating a character stream.
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
CharStream inputStream = CharStreams.fromReader(in);
// 2. Perform lexical analysis on the character stream. The purpose
// of the error listener is to throw an exception whenever the lexer
// encounters a syntax error.
SimpleArithLexer lexer = new SimpleArithLexer(inputStream);
lexer.addErrorListener(new BaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> r, Object o, int l, int c,
String msg, RecognitionException e) {
throw new RuntimeException(e);
}
});
CommonTokenStream commonTokenStream = new CommonTokenStream(lexer);
// 3. Parse the stream of tokens generated by the lexer by calling
// the expr() method, which corresponds to SimpleArith's expr rule.
SimpleArithParser parser = new SimpleArithParser(commonTokenStream);
parser.setErrorHandler(new BailErrorStrategy());
ParseTree tree = parser.expr();
// 4. Given the resulting parse tree, evaluate it.
SimpleArithEvaluator evaluator = new SimpleArithEvaluator();
Integer result = evaluator.visit(tree);
// 5. Print result
System.out.println(result);
}
}