/
Token.cs
317 lines (293 loc) · 12.6 KB
/
Token.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Token.cs, 07.11.2019
// Copyright (C) Dominic Beger 07.11.2019
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using SharpMath.Expressions.Exceptions;
// ReSharper disable InconsistentNaming
namespace SharpMath.Expressions
{
/// <summary>
/// Represents a part of a mathematic term.
/// </summary>
public class Token
{
private static readonly Regex SWhitespace = new Regex(@"\s+");
protected static Dictionary<string, Action<Stack<double>>> _functionActions = new Dictionary
<string, Action<Stack<double>>>
{
{"sin", stack => stack.Push(Math.Sin(stack.Pop()))},
{"cos", stack => stack.Push(Math.Cos(stack.Pop()))},
{"tan", stack => stack.Push(Math.Tan(stack.Pop()))},
{"asin", stack => stack.Push(Math.Asin(stack.Pop()))},
{"acos", stack => stack.Push(Math.Acos(stack.Pop()))},
{"atan", stack => stack.Push(Math.Atan(stack.Pop()))},
{"sqrt", stack => stack.Push(Math.Sqrt(stack.Pop()))},
{"abs", stack => stack.Push(Math.Abs(stack.Pop()))},
{"ln", stack => stack.Push(Math.Log(stack.Pop()))},
{"lg", stack => stack.Push(Math.Log(stack.Pop(), 10))},
{
"log", stack =>
{
var exponent = stack.Pop();
stack.Push(Math.Log(exponent, stack.Pop()));
}
}
};
protected static Dictionary<string, Action<Stack<double>>> _constantActions = new Dictionary
<string, Action<Stack<double>>>
{
{"pi", stack => stack.Push(Math.PI)},
{"e", stack => stack.Push(Math.E)}
};
protected static Dictionary<string, Action<Stack<double>>> _operatorActions = new Dictionary
<string, Action<Stack<double>>>
{
{"+", stack => stack.Push(stack.Pop() + stack.Pop())},
{
"-", stack =>
{
var subtrahend = stack.Pop();
stack.Push(stack.Pop() - subtrahend);
}
},
{"*", stack => stack.Push(stack.Pop() * stack.Pop())},
{
"/", stack =>
{
var divisor = stack.Pop();
stack.Push(stack.Pop() / divisor);
}
},
{"!", stack => stack.Push(-stack.Pop())},
{
"^", stack =>
{
var exponent = stack.Pop();
stack.Push(Math.Pow(stack.Pop(), exponent));
}
}
};
/// <summary>
/// Initializes a new instance of the <see cref="Token" /> class.
/// </summary>
/// <param name="type">The type of the <see cref="Token" />.</param>
public Token(TokenType type)
{
Type = type;
}
/// <summary>
/// Gets or sets the type of this <see cref="Token" />.
/// </summary>
public TokenType Type { get; set; }
/// <summary>
/// Creates an <see cref="IEnumerable{Token}" /> containing infix tokens from partitioning the specified term.
/// </summary>
/// <param name="term">The term to partition into infix tokens.</param>
/// <returns><see cref="IEnumerable{Token}" /> containing the created infix tokens.</returns>
public static IEnumerable<Token> CalculateInfixTokens(string term)
{
var infixTokens = new List<Token>();
term = SWhitespace.Replace(term, string.Empty).ToLowerInvariant();
var i = 0;
while (i < term.Length)
{
var current = term[i];
if (char.IsLetter(current) || CharEx.IsMathematicOperator(current) || CharEx.IsBracket(current))
// Functions/Operators/Constants
{
if ((current == '+' || current == '-') &&
(i == 0 ||
infixTokens.Last().Type == TokenType.Bracket &&
((Token<string>) infixTokens.Last()).Value == "("))
// Must be a sign and handled differently.
{
if (current == '-')
{
var sb = new StringBuilder(term) {[term.IndexOf(current)] = '!'};
term = sb.ToString();
}
else
{
term.Remove(term.IndexOf(current), 1);
}
// Remove the '+' as it is redundant and disturbs our calculations
}
infixTokens.Add(ReadStringToken(term, ref i));
}
else if (char.IsDigit(current)) // Numbers
{
infixTokens.Add(ReadNumberToken(term, ref i));
}
else
{
throw new ParserException($"Char {current} cannot be interpreted as a valid token.");
}
}
return infixTokens;
}
/// <summary>
/// Evaluates this <see cref="Token" />.
/// </summary>
/// <param name="stack">The <see cref="Stack{double}" /> to take relating from and push the result to.</param>
public void Evaluate(Stack<double> stack)
{
switch (Type)
{
case TokenType.Number:
var token = this as Token<double>;
if (token != null)
stack.Push(token.Value);
break;
case TokenType.Function:
var token1 = this as Token<string>;
if (token1 != null)
_functionActions[token1.Value](stack);
break;
case TokenType.Operator:
var token2 = this as Token<string>;
if (token2 != null)
_operatorActions[token2.Value](stack);
break;
case TokenType.Constant:
var token3 = this as Token<string>;
if (token3 != null)
_constantActions[token3.Value](stack);
break;
}
}
/// <summary>
/// Reads a number token in the input string starting at the specified index.
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="index">The index to start at.</param>
/// <returns>The <see cref="Token" /> that has been read.</returns>
public static Token<double> ReadNumberToken(string input, ref int index)
{
var endIndex = index;
while (endIndex < input.Length && (char.IsDigit(input, endIndex) || input[endIndex] == '.'))
endIndex++;
var numberToken = input.Substring(index, endIndex - index);
double numberValue;
if (
!double.TryParse(numberToken, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture,
out numberValue))
throw new ParserException($"Invalid token: {numberToken} is not a valid number.");
index = endIndex;
return new Token<double>(numberValue, TokenType.Number);
}
/// <summary>
/// Reads a bracket, constant, operator or function token in the input string starting at the specified index.
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="index">The index to start at.</param>
/// <returns>The <see cref="Token" /> that has been read.</returns>
public static Token<string> ReadStringToken(string input, ref int index)
{
TokenType newType;
var endIndex = index;
while (endIndex < input.Length &&
(char.IsLetter(input, endIndex) || CharEx.IsMathematicOperator(input[endIndex]) ||
CharEx.IsBracket(input[endIndex])))
{
endIndex++;
var currentString = input.Substring(index, endIndex - index);
if (_functionActions.ContainsKey(currentString) || _operatorActions.ContainsKey(currentString) ||
_constantActions.ContainsKey(currentString) ||
currentString.IsBracket()
) // Last two conditions to parse e.g. "* sin(5)" correctly: As soon as the current token has finished, we should stop reading.
break; // This indicates that it has been found in the dictionary, so that is already it.
}
var stringToken = input.Substring(index, endIndex - index);
if (_functionActions.ContainsKey(stringToken))
newType = TokenType.Function;
else if (_operatorActions.ContainsKey(stringToken))
newType = TokenType.Operator;
else if (stringToken.IsBracket())
newType = TokenType.Bracket;
else if (_constantActions.ContainsKey(stringToken))
newType = TokenType.Constant;
else
throw new ParserException(
$"Invalid token: {stringToken} is not a valid function/operator, bracket or number equivalent.");
index = endIndex;
return new Token<string>(stringToken, newType);
}
}
/// <summary>
/// Represents a part of a mathematic term with a specific data type that should represent it.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="Token" /> that represents it.</typeparam>
public class Token<T> : Token
{
/// <summary>
/// Initializes a new instance of the <see cref="Token{T}" /> class.
/// </summary>
/// <param name="value">The value of the <see cref="Token{T}" />.</param>
/// <param name="type">The type of the <see cref="Token{T}" />.</param>
public Token(T value, TokenType type)
: base(type)
{
Value = value;
switch (type)
{
case TokenType.Number:
case TokenType.Constant:
Priority = 100;
break;
case TokenType.Operator:
switch (value as string)
{
case "+":
Priority = 1;
IsRightAssociative = false;
break;
case "-":
Priority = 1;
IsRightAssociative = false;
break;
case "*":
Priority = 2;
IsRightAssociative = false;
break;
case "/":
Priority = 2;
IsRightAssociative = false;
break;
case "%":
Priority = 3;
IsRightAssociative = false;
break;
case "!":
Priority = 4;
IsRightAssociative = false;
break;
case "^":
Priority = 5;
IsRightAssociative = true;
break;
}
break;
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Token" /> is right associative, or not.
/// </summary>
public bool IsRightAssociative { get; set; }
/// <summary>
/// Gets or sets the priority of this <see cref="Token{T}" />.
/// </summary>
public int Priority { get; set; }
/// <summary>
/// Gets or sets the value of this <see cref="Token{T}" />.
/// </summary>
public T Value { get; set; }
public override string ToString()
{
return Value.ToString();
}
}
}