Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package expression;
- /**
- * @author Bogdan Timchenko
- */
- public class CheckedParser implements Parser{
- private String unparse;
- private int left;
- private int len;
- public TripleExpression parse(String str) throws RuntimeException {
- unparse = str;
- left = 0;
- len = unparse.length();
- TripleExpression exp;
- exp = PlusMinus();
- unparse = "";
- len = 0;
- left = 0;
- return exp;
- }
- private TripleExpression PlusMinus() throws RuntimeException {
- TripleExpression acc = MulDiv();
- TripleExpression res;
- while (len > left) {
- delSpaces();
- char sign = unparse.charAt(left);
- if (!(sign == '+' || sign == '-')) {
- break;
- }
- left++;
- res = MulDiv();
- if (sign == '+') {
- acc = new CheckedAdd(acc, res);
- } else {
- acc = new CheckedSubtract(acc, res);
- }
- }
- if (len > left) {
- throw new RuntimeException("Cannot parse: " + '"' + unparse.substring(left) + '"');
- }
- return acc;
- }
- private TripleExpression MulDiv() throws RuntimeException {
- TripleExpression acc = Bracket();
- TripleExpression res;
- while (true) {
- delSpaces();
- if (left == len) {
- return acc;
- }
- char sign = unparse.charAt(left);
- if (!(sign == '*' || sign == '/')) {
- return acc;
- }
- left++;
- res = Bracket();
- if (sign == '*') {
- acc = new CheckedMultiply(acc, res);
- } else {
- acc = new CheckedDivide(acc, res);
- }
- }
- }
- private TripleExpression Bracket() throws RuntimeException {
- delSpaces();
- char firstCh = unparse.charAt(left);
- if (firstCh == '(') {
- left++;
- TripleExpression res = PlusMinus();
- if (unparse.charAt(left) != ')') {
- throw new RuntimeException("Missing ')'");
- }
- left++;
- return res;
- }
- return ConstVar();
- }
- private TripleExpression ConstVar() throws RuntimeException {
- delSpaces();
- String var = unparse.substring(left, left + 1);
- if (var.equals("x") || var.equals("y") || var.equals("z")) {
- left++;
- return new Variable(var);
- }
- return Minus();
- }
- private TripleExpression Minus() throws RuntimeException {
- delSpaces();
- if (unparse.charAt(left) == '-') {
- if (len - left > 1 && !Character.isDigit(unparse.charAt(left + 1))) {
- left++;
- return new CheckedNegate(Bracket());
- }
- }
- return Num();
- }
- private TripleExpression Num() throws RuntimeException {
- delSpaces();
- int i = 0;
- if (unparse.charAt(left) == '-') {
- i++;
- }
- while (i < len - left && Character.isDigit(unparse.charAt(left + i))) {
- i++;
- }
- if (i == 0) {
- throw new RuntimeException("Unexpected symbol: '" + unparse.charAt(left) + "'");
- }
- int num = Integer.parseInt(unparse.substring(left, left + i));
- left += i;
- return new Const(num);
- }
- private void delSpaces() {
- while (left < len) {
- if (!Character.isWhitespace(unparse.charAt(left))) {
- break;
- }
- left++;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement