public void One_Plus_One_Should_Evaluate_To_Two() { var expression = new OperationExpression( new ParameterExpression(1.0d), Operand.Plus, new ParameterExpression(1.0d)); var result = expression.Evaluate(); result.Should().Be(2d); }
public IExpression Parse() { var left = new Stack<IExpression>(); var operands = new Stack<Operand>(); var right = new Stack<IExpression>(); while (HasMoreChars) { var c = _expression.Peek(); if (char.IsDigit(c)) { var parameter = ReadParameterExpression(); var expression = ParseParameterExpression(parameter); if (left.Count == right.Count) { left.Push(expression); } else { right.Push(expression); } } else if (IsOperand(c)) { var operand = ParseOperand(_expression.Pop()); if (right.Any() && (operand == Operand.Divide || operand == Operand.Multiply)) { left.Push(right.Pop()); } while (operands.Any() && left.Any() && right.Any()) { var expression = new OperationExpression(left.Pop(), operands.Pop(), right.Pop()); if (left.Count == right.Count) { left.Push(expression); } else { right.Push(expression); } } operands.Push(operand); } else if (IsOpeningBracket(c)) { _expression.Pop(); var expression = Parse(); if (left.Count == right.Count) { left.Push(expression); } else { right.Push(expression); } } else if (IsClosingBracket(c)) { _expression.Pop(); while (operands.Any()) { var expression = new OperationExpression(left.Pop(), operands.Pop(), right.Pop()); if (left.Count == right.Count) { left.Push(expression); } else { right.Push(expression); } } return left.Pop(); } else if (char.IsWhiteSpace(c)) { _expression.Pop(); } else { throw new NotImplementedException($"Cannot parse char '{c}'"); } } while (operands.Any()) { var expression = new OperationExpression(left.Pop(), operands.Pop(), right.Pop()); if (left.Count == right.Count) { left.Push(expression); } else { right.Push(expression); } } return left.Pop(); }