Parser.java

package calculator.antlr;

import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;

import calculator.Expression;
import calculator.calculatorLexer;
import calculator.calculatorParser;

import org.antlr.v4.runtime.ANTLRErrorListener;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;

public class Parser {

	/**
	 * Analyze a string input and return an Expression object representing the
	 * parsed expression.
	 * 
	 */
	public Expression parse(String inputStr) {
		// Creation of a CharStream from the input string
		CharStream input = CharStreams.fromString(inputStr);

		// Lexer generated by ANTLR (calculatorLexer) to tokenize the input
		calculatorLexer lexer = new calculatorLexer(input);

		// Add error listener to throw exceptions on syntax error
		lexer.removeErrorListeners();
		lexer.addErrorListener(getBaseErrrorListener());

		CommonTokenStream tokens = new CommonTokenStream(lexer);

		// Parser generated by ANTLR (calculatorParser) to create a parse tree from the
		// tokens
		calculatorParser parser = new calculatorParser(tokens);

		parser.removeErrorListeners();
		parser.addErrorListener(getBaseErrrorListener());

		ParseTree tree = parser.complete();

		// Visit the tree to build the Expression
		ParserVisitor visitor = new ParserVisitor();
		return visitor.visit(tree);
	}

	private ANTLRErrorListener getBaseErrrorListener() {
		return new BaseErrorListener() {
			@Override
			public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
					int charPositionInLine, String msg, RecognitionException e) {
				throw new IllegalArgumentException(
						"Invalid expression at line " + line + ":" + charPositionInLine + " - " + msg);
			}
		};
	}
}