org.unlaxer.sample.calc.CalculatorImpl Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of calculator Show documentation
Show all versions of calculator Show documentation
a simple parser combinator inspired by RelaxNG
package org.unlaxer.sample.calc;
import java.math.BigDecimal;
import java.util.Optional;
import org.unlaxer.Parsed;
import org.unlaxer.StringSource;
import org.unlaxer.Token;
import org.unlaxer.context.ParseContext;
import org.unlaxer.parser.Parser;
import org.unlaxer.sample.calc.parser.FormulaParser;
import org.unlaxer.sample.calc.parser.operator.ExpressionOperator;
public class CalculatorImpl implements Calculator {
@Override
public CalculateResult calculate(CalculateContext calculateContext, String formula) {
ParseContext parseContext = new ParseContext(new StringSource(formula));
Parsed parsed = getParser().parse(parseContext);
try{
Token rootToken = parsed.getRootToken(true);
BigDecimal answer = ExpressionOperator.SINGLETON.evaluate(calculateContext,rootToken);
return new CalculateResult(parseContext , parsed, Optional.of(answer));
}catch (Exception e) {
e.printStackTrace();
return createResult(e , parseContext , parsed);
}finally{
parseContext.close();
}
}
private CalculateResult createResult(Exception e, ParseContext tokenizeContextPointer, Parsed parsed) {
Errors errors = new Errors(e);
return new CalculateResult(tokenizeContextPointer , parsed, Optional.empty() , errors);
}
@Override
public Parser getParser() {
return FormulaParser.SINGLETON;
}
}