package org.sc3d.apt.sss.v3; import java.io.*; import java.math.BigInteger; /** This class is a worked example of how to use SSS in general, and the tools provided in this Java package in particular. It is not itself a particularly useful tool. To get the most out of this example, read its source code. *
This class uses an SSS syntax to implement an interactive arbitrary precision integer calculator, using the java.math.BigInteger class as the back-end. If you really wanted to write a calculator, there are easier ways of doing it than using SSS. Having said that:
* sign ::= {Minus {"-"}} * atom ::= {Number {sign* NUMBER} Bracket {sign* Round(sum)}} * multiplicand ::= {Multiply {"*" atom} Divide {"/" atom}} * product ::= {Product {atom multiplicand*}} * summand ::= {Add {"+" product} Subtract {"-" product}} * sum ::= {Sum {product summand*}} * ROOT sum **/ public static final Grammar SUM = GrammarParser.fromString( "sign ::= {Minus {\"-\"}}\n"+ "atom ::= {Number {sign* NUMBER} Bracket {sign* ROUND(sum)}}\n"+ "multiplicand ::= {Multiply {\"*\" atom} Divide {\"/\" atom}}\n"+ "product ::= {Product {atom multiplicand*}}\n"+ "summand ::= {Add {\"+\" product} Subtract {\"-\" product}}\n"+ "sum ::= {Sum {product summand*}}\n"+ "ROOT sum" ); /** Evaluates an arithmetic expression. If the expression is not syntactically correct, this method attaches appropriate error messages to 'expression' and returns 'null'. */ public BigInteger evaluate(Sentence expression) { final Expression expr = (Expression)this.parse(expression); return expr==null ? null : expr.evaluate(); } /** Converts a Tree representing the parse-tree of an 'atom', 'product' or 'sum' into an Expression. If the Tree contains errors, this method annotates the Tokens it contains with error messages and returns 'null'.*/ public Expression postProcessExpression(Tree.Production raw) { if (raw.name.equals("Sum") || raw.name.equals("Product")) { Expression ans = this.postProcessExpression(raw.getP(0)); final Tree.NonTerminal summands = raw.getNT(1); for (int i=0; i