public IEnumerable <Token> Tokenize(TextReader reader) { var token = new StringBuilder(); int curr; while ((curr = reader.Read()) != -1) { var ch = (char)curr; var currType = DetermineType(ch); if (currType == TokenType.WhiteSpace) { continue; } if (currType == TokenType.Exeption) { ShuntingYardException ShuntingYardExeption = new ShuntingYardException("Wrong symbol", ch); continue; } token.Append(ch); var next = reader.Peek(); var nextType = next != -1 ? DetermineType((char)next) : TokenType.WhiteSpace; if (currType != nextType) { if (next == '(') { yield return(new Token(TokenType.Function, token.ToString())); } else { yield return(new Token(currType, token.ToString())); } token.Clear(); } } }
public IEnumerable <Token> ShuntingYard(IEnumerable <Token> tokens) { var stack = new Stack <Token>(); foreach (var tok in tokens) { switch (tok.Type) { case TokenType.Polynomial: case TokenType.Variable: yield return(tok); break; case TokenType.Function: stack.Push(tok); break; case TokenType.Comma: while (stack.Peek().Value != "(") { yield return(stack.Pop()); } break; case TokenType.Operator: while (stack.Any() && stack.Peek().Type == TokenType.Operator && CompareOperators(tok.Value, stack.Peek().Value)) { yield return(stack.Pop()); } stack.Push(tok); break; case TokenType.Parenthesis: if (tok.Value == "(") { stack.Push(tok); } else { if (stack.Count != 0) { while (stack.Peek().Value != "(") { yield return(stack.Pop()); } stack.Pop(); if (stack.Peek().Type == TokenType.Function) { yield return(stack.Pop()); } } } break; default: ShuntingYardException ShuntingYardExeption = new ShuntingYardException("Wrong token", tok); break; } } while (stack.Any()) { var tok = stack.Pop(); if (tok.Type == TokenType.Parenthesis) { ShuntingYardException ShuntingYardExeption = new ShuntingYardException("Mismatched parentheses"); continue; } yield return(tok); } }