public override TokenStream Rewrite(TokenStream tokens)
{
// Token stream needs to be in infix notation.
if (tokens.Notation != TokenNotation.Infix)
{
throw new MathExpressionException("Token stream is not in infix notation.");
}
List<Token> result = new List<Token>();
for (int index = 0; index < tokens.Count; index++)
{
Token token = tokens[index];
if (token.Type == TokenType.Subtraction)
{
// Is this the first token?
if (index == 0)
{
// Replace this token with a negation.
result.Add(new Token(TokenType.Negation, "-"));
}
// Previous token an operator?
else if (index > 0 && tokens[index - 1].IsOperator())
{
// Replace this token with a negation.
result.Add(new Token(TokenType.Negation, "-"));
}
// Previous token an opening parenthesis.
else if (index > 0 && tokens[index - 1].Type == TokenType.OpeningParenthesis)
{
// Replace this token with a negation.
result.Add(new Token(TokenType.Negation, "-"));
}
else
{
result.Add(token);
}
}
else
{
result.Add(token);
}
}
return new TokenStream(result, TokenNotation.Infix);
}