View Javadoc
1   package calculator.antlr;
2   
3   import org.antlr.v4.runtime.CharStream;
4   import org.antlr.v4.runtime.CharStreams;
5   import org.antlr.v4.runtime.CommonTokenStream;
6   import org.antlr.v4.runtime.tree.ParseTree;
7   
8   import calculator.Expression;
9   import calculator.calculatorLexer;
10  import calculator.calculatorParser;
11  
12  import org.antlr.v4.runtime.ANTLRErrorListener;
13  import org.antlr.v4.runtime.BaseErrorListener;
14  import org.antlr.v4.runtime.RecognitionException;
15  import org.antlr.v4.runtime.Recognizer;
16  
17  public class Parser {
18  
19  	/**
20  	 * Analyze a string input and return an Expression object representing the
21  	 * parsed expression.
22  	 * 
23  	 */
24  	public Expression parse(String inputStr) {
25  		// Creation of a CharStream from the input string
26  		CharStream input = CharStreams.fromString(inputStr);
27  
28  		// Lexer generated by ANTLR (calculatorLexer) to tokenize the input
29  		calculatorLexer lexer = new calculatorLexer(input);
30  
31  		// Add error listener to throw exceptions on syntax error
32  		lexer.removeErrorListeners();
33  		lexer.addErrorListener(getBaseErrrorListener());
34  
35  		CommonTokenStream tokens = new CommonTokenStream(lexer);
36  
37  		// Parser generated by ANTLR (calculatorParser) to create a parse tree from the
38  		// tokens
39  		calculatorParser parser = new calculatorParser(tokens);
40  
41  		parser.removeErrorListeners();
42  		parser.addErrorListener(getBaseErrrorListener());
43  
44  		ParseTree tree = parser.complete();
45  
46  		// Visit the tree to build the Expression
47  		ParserVisitor visitor = new ParserVisitor();
48  		return visitor.visit(tree);
49  	}
50  
51  	private ANTLRErrorListener getBaseErrrorListener() {
52  		return new BaseErrorListener() {
53  			@Override
54  			public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
55  					int charPositionInLine, String msg, RecognitionException e) {
56  				throw new IllegalArgumentException(
57  						"Invalid expression at line " + line + ":" + charPositionInLine + " - " + msg);
58  			}
59  		};
60  	}
61  }