private CommonF Factor() { Pow pow = new Pow(); CommonF power = Power(); if (!power.IsZero()) { pow.RaiseTo(power); } else { while (IsCaret(look)) { Match('^'); Power(); } return(new Constant(0)); } while (IsCaret(look)) { Match('^'); power = Power(); if (!power.IsZero()) { pow.RaiseTo(power); } else { if (pow.baseAndPower.Count > 1) { pow.baseAndPower.RemoveAt(pow.baseAndPower.Count - 1); while (IsCaret(look)) { Match('^'); Power(); } return(pow); } else { while (IsCaret(look)) { Match('^'); Power(); } return(new Constant(1)); } } } if (pow.baseAndPower.Count == 1) { return(pow.baseAndPower[0]); } else { return(pow); } }
private CommonF Term() { Mul mul = new Mul(); Constant constant = new Constant(1); CommonF factor = Factor(); if (!factor.IsZero()) { if (!(factor is Constant)) { mul *= factor; } else { constant *= (Constant)factor; } } else { while (IsMulOperator(look)) { switch (look) { case '*': Match('*'); break; case '/': Match('/'); break; } Factor(); } return(new Constant(0)); } while (IsMulOperator(look)) { switch (look) { case '*': Match('*'); factor = Factor(); if (!factor.IsZero()) { if (!(factor is Constant)) { mul *= factor; } else { constant *= (Constant)factor; } } else { while (IsMulOperator(look)) { switch (look) { case '*': Match('*'); break; case '/': Match('/'); break; } Factor(); } return(new Constant(0)); } break; case '/': Match('/'); factor = Factor(); if (!factor.IsZero()) { if (!(factor is Constant)) { mul /= factor; } else { constant /= (Constant)factor; } } else { throw new ArithmeticException("null division"); } break; default: throw new Exception("unexpected parser error"); } } if (constant.IsZero()) { return(new Constant(0)); } if (mul.operands.Count == 0) { return(constant); } if (mul.operands.Count == 1) { if (constant.Value == 1) { return(mul.operands[0]); } else { return(mul.operands[0] * constant); } } if (constant.Value == 1) { return(mul); } else { return(mul * constant); } }
//get expression as graph private CommonF Expression() { Sum sum = new Sum(); Constant constant = new Constant(0); CommonF term = null; if (!IsAddOperator(look)) { term = Term(); if (!term.IsZero()) { if (!(term is Constant)) { sum += term; } else { constant += (Constant)term; } } } while (IsAddOperator(look)) { switch (look) { case '+': Match('+'); term = Term(); if (!term.IsZero()) { if (!(term is Constant)) { sum += term; } else { constant += (Constant)term; } } break; case '-': Match('-'); term = Term(); if (!term.IsZero()) { if (!(term is Constant)) { sum -= term; } else { constant -= (Constant)term; } } break; default: throw new Exception(); } } if (sum.operands.Count == 0) { return(constant); } if (constant.Value != 0) { sum += constant; } return(sum); }