forked from codingseb/ExpressionEvaluator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ExpressionEvaluator.cs
4287 lines (3653 loc) · 197 KB
/
ExpressionEvaluator.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************************************
Title : ExpressionEvaluator (https://github.com/codingseb/ExpressionEvaluator)
Version : 1.4.18.1
(if last digit (the forth) is not a zero, the version is an intermediate version and can be unstable)
Author : Coding Seb
Licence : MIT (https://github.com/codingseb/ExpressionEvaluator/blob/master/LICENSE.md)
*******************************************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;
namespace CodingSeb.ExpressionEvaluator
{
/// <summary>
/// This class allow to evaluate a string math or pseudo C# expression
/// </summary>
public partial class ExpressionEvaluator
{
#region Regex declarations
protected const string primaryTypesRegexPattern = @"(?<=^|[^\p{L}_])(?<primaryType>object|string|bool[?]?|byte[?]?|char[?]?|decimal[?]?|double[?]?|short[?]?|int[?]?|long[?]?|sbyte[?]?|float[?]?|ushort[?]?|uint[?]?|ulong[?]?|void)(?=[^a-zA-Z_]|$)";
protected static readonly Regex varOrFunctionRegEx = new Regex(@"^((?<sign>[+-])|(?<prefixOperator>[+][+]|--)|(?<varKeyword>var)\s+|(?<dynamicKeyword>dynamic)\s+|(?<inObject>(?<nullConditional>[?])?\.)?)(?<name>[\p{L}_](?>[\p{L}_0-9]*))(?>\s*)((?<assignationOperator>(?<assignmentPrefix>[+\-*/%&|^]|<<|>>|\?\?)?=(?![=>]))|(?<postfixOperator>([+][+]|--)(?![\p{L}_0-9]))|((?<isgeneric>[<](?>([\p{L}_](?>[\p{L}_0-9]*)|(?>\s+)|[,\.])+|(?<gentag>[<])|(?<-gentag>[>]))*(?(gentag)(?!))[>])?(?<isfunction>[(])?))", RegexOptions.IgnoreCase | RegexOptions.Compiled);
protected const string numberRegexOrigPattern = @"^(?<sign>[+-])?([0-9][0-9_{1}]*[0-9]|\d)(?<hasdecimal>{0}?([0-9][0-9_]*[0-9]|\d)(e[+-]?([0-9][0-9_]*[0-9]|\d))?)?(?<type>ul|[fdulm])?";
protected string numberRegexPattern;
protected static readonly Regex otherBasesNumberRegex = new Regex("^(?<sign>[+-])?(?<value>0(?<type>x)([0-9a-f][0-9a-f_]*[0-9a-f]|[0-9a-f])|0(?<type>b)([01][01_]*[01]|[01]))", RegexOptions.IgnoreCase | RegexOptions.Compiled);
protected static readonly Regex stringBeginningRegex = new Regex("^(?<interpolated>[$])?(?<escaped>[@])?[\"]", RegexOptions.Compiled);
protected static readonly Regex internalCharRegex = new Regex(@"^['](\\[\\'0abfnrtv]|[^'])[']", RegexOptions.Compiled);
protected static readonly Regex indexingBeginningRegex = new Regex(@"^[?]?\[", RegexOptions.Compiled);
protected static readonly Regex assignationOrPostFixOperatorRegex = new Regex(@"^(?>\s*)((?<assignmentPrefix>[+\-*/%&|^]|<<|>>|\?\?)?=(?![=>])|(?<postfixOperator>([+][+]|--)(?![\p{L}_0-9])))");
protected static readonly Regex genericsDecodeRegex = new Regex("(?<name>[^,<>]+)(?<isgeneric>[<](?>[^<>]+|(?<gentag>[<])|(?<-gentag>[>]))*(?(gentag)(?!))[>])?", RegexOptions.Compiled);
protected static readonly Regex genericsEndOnlyOneTrim = new Regex(@"(?>\s*)[>](?>\s*)$", RegexOptions.Compiled);
protected static readonly Regex endOfStringWithDollar = new Regex("^([^\"{\\\\]|\\\\[\\\\\"0abfnrtv])*[\"{]", RegexOptions.Compiled);
protected static readonly Regex endOfStringWithoutDollar = new Regex("^([^\"\\\\]|\\\\[\\\\\"0abfnrtv])*[\"]", RegexOptions.Compiled);
protected static readonly Regex endOfStringWithDollarWithAt = new Regex("^[^\"{]*[\"{]", RegexOptions.Compiled);
protected static readonly Regex endOfStringWithoutDollarWithAt = new Regex("^[^\"]*[\"]", RegexOptions.Compiled);
protected static readonly Regex endOfStringInterpolationRegex = new Regex("^('\"'|[^}\"])*[}\"]", RegexOptions.Compiled);
protected static readonly Regex stringBeginningForEndBlockRegex = new Regex("[$]?[@]?[\"]$", RegexOptions.Compiled);
protected static readonly Regex lambdaExpressionRegex = new Regex(@"^(?>\s*)(?<args>((?>\s*)[(](?>\s*)([\p{L}_](?>[\p{L}_0-9]*)(?>\s*)([,](?>\s*)[\p{L}_][\p{L}_0-9]*(?>\s*))*)?[)])|[\p{L}_](?>[\p{L}_0-9]*))(?>\s*)=>(?<expression>.*)$", RegexOptions.Singleline | RegexOptions.Compiled);
protected static readonly Regex lambdaArgRegex = new Regex(@"[\p{L}_](?>[\p{L}_0-9]*)", RegexOptions.Compiled);
protected static readonly Regex initInNewBeginningRegex = new Regex(@"^(?>\s*){", RegexOptions.Compiled);
// Depending on OptionInlineNamespacesEvaluationActive. Initialized in constructor
protected string InstanceCreationWithNewKeywordRegexPattern { get { return @"^new(?>\s*)((?<isAnonymous>[{{])|((?<name>[\p{L}_][\p{L}_0-9"+ (OptionInlineNamespacesEvaluationActive ? @"\." : string.Empty) + @"]*)(?>\s*)(?<isgeneric>[<](?>[^<>]+|(?<gentag>[<])|(?<-gentag>[>]))*(?(gentag)(?!))[>])?(?>\s*)((?<isfunction>[(])|(?<isArray>\[)|(?<isInit>[{{]))?))"; } }
protected string CastRegexPattern { get { return @"^\((?>\s*)(?<typeName>[\p{L}_][\p{L}_0-9"+ (OptionInlineNamespacesEvaluationActive ? @"\." : string.Empty) + @"\[\]<>]*[?]?)(?>\s*)\)"; } }
// To remove comments in scripts based on https://stackoverflow.com/questions/3524317/regex-to-strip-line-comments-from-c-sharp/3524689#3524689
protected const string blockComments = @"/\*(.*?)\*/";
protected const string lineComments = @"//[^\r\n]*";
protected const string stringsIgnore = @"""((\\[^\n]|[^""\n])*)""";
protected const string verbatimStringsIgnore = @"@(""[^""]*"")+";
protected static readonly Regex removeCommentsRegex = new Regex($"{blockComments}|{lineComments}|{stringsIgnore}|{verbatimStringsIgnore}", RegexOptions.Singleline | RegexOptions.Compiled);
protected static readonly Regex newLineCharsRegex = new Regex(@"\r\n|\r|\n", RegexOptions.Compiled);
// For script only
protected static readonly Regex blockKeywordsBeginningRegex = new Regex(@"^(?>\s*)(?<keyword>while|for|foreach|if|else(?>\s*)if|catch)(?>\s*)[(]", RegexOptions.IgnoreCase | RegexOptions.Compiled);
protected static readonly Regex foreachParenthisEvaluationRegex = new Regex(@"^(?>\s*)(?<variableName>[\p{L}_](?>[\p{L}_0-9]*))(?>\s*)(?<in>in)(?>\s*)(?<collection>.*)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
protected static readonly Regex blockKeywordsWithoutParenthesesBeginningRegex = new Regex(@"^(?>\s*)(?<keyword>else|do|try|finally)(?![\p{L}_0-9])", RegexOptions.IgnoreCase | RegexOptions.Compiled);
protected static readonly Regex blockBeginningRegex = new Regex(@"^(?>\s*)[{]", RegexOptions.Compiled);
protected static readonly Regex returnKeywordRegex = new Regex(@"^return((?>\s*)|\()", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled);
protected static readonly Regex nextIsEndOfExpressionRegex = new Regex(@"^(?>\s*)[;]", RegexOptions.Compiled);
#endregion
#region enums (if else blocks states)
protected enum IfBlockEvaluatedState
{
NoBlockEvaluated,
If,
ElseIf
}
protected enum TryBlockEvaluatedState
{
NoBlockEvaluated,
Try,
Catch
}
#endregion
#region Dictionaries declarations (Primary types, number suffix, escaped chars, operators management, default vars and functions)
protected static readonly IDictionary<string, Type> primaryTypesDict = new Dictionary<string, Type>()
{
{ "object", typeof(object) },
{ "string", typeof(string) },
{ "bool", typeof(bool) },
{ "bool?", typeof(bool?) },
{ "byte", typeof(byte) },
{ "byte?", typeof(byte?) },
{ "char", typeof(char) },
{ "char?", typeof(char?) },
{ "decimal", typeof(decimal) },
{ "decimal?", typeof(decimal?) },
{ "double", typeof(double) },
{ "double?", typeof(double?) },
{ "short", typeof(short) },
{ "short?", typeof(short?) },
{ "int", typeof(int) },
{ "int?", typeof(int?) },
{ "long", typeof(long) },
{ "long?", typeof(long?) },
{ "sbyte", typeof(sbyte) },
{ "sbyte?", typeof(sbyte?) },
{ "float", typeof(float) },
{ "float?", typeof(float?) },
{ "ushort", typeof(ushort) },
{ "ushort?", typeof(ushort?) },
{ "uint", typeof(uint) },
{ "uint?", typeof(uint?) },
{ "ulong", typeof(ulong) },
{ "ulong?", typeof(ulong?) },
{ "void", typeof(void) }
};
protected static readonly IDictionary<string, Func<string, CultureInfo, object>> numberSuffixToParse = new Dictionary<string, Func<string, CultureInfo, object>>(StringComparer.OrdinalIgnoreCase) // Always Case insensitive, like in C#
{
{ "f", (number, culture) => float.Parse(number, NumberStyles.Any, culture) },
{ "d", (number, culture) => double.Parse(number, NumberStyles.Any, culture) },
{ "u", (number, culture) => uint.Parse(number, NumberStyles.Any, culture) },
{ "l", (number, culture) => long.Parse(number, NumberStyles.Any, culture) },
{ "ul", (number, culture) => ulong.Parse(number, NumberStyles.Any, culture) },
{ "m", (number, culture) => decimal.Parse(number, NumberStyles.Any, culture) }
};
protected static readonly IDictionary<char, string> stringEscapedCharDict = new Dictionary<char, string>()
{
{ '\\', @"\" },
{ '"', "\"" },
{ '0', "\0" },
{ 'a', "\a" },
{ 'b', "\b" },
{ 'f', "\f" },
{ 'n', "\n" },
{ 'r', "\r" },
{ 't', "\t" },
{ 'v', "\v" }
};
protected static readonly IDictionary<char, char> charEscapedCharDict = new Dictionary<char, char>()
{
{ '\\', '\\' },
{ '\'', '\'' },
{ '0', '\0' },
{ 'a', '\a' },
{ 'b', '\b' },
{ 'f', '\f' },
{ 'n', '\n' },
{ 'r', '\r' },
{ 't', '\t' },
{ 'v', '\v' }
};
/// <summary>
/// OperatorsDictionaryInit() for values
/// </summary>
protected IDictionary<string, ExpressionOperator> operatorsDictionary = new Dictionary<string, ExpressionOperator>(StringComparer.Ordinal)
{
{ "+", ExpressionOperator.Plus },
{ "-", ExpressionOperator.Minus },
{ "*", ExpressionOperator.Multiply },
{ "/", ExpressionOperator.Divide },
{ "%", ExpressionOperator.Modulo },
{ "<", ExpressionOperator.Lower },
{ ">", ExpressionOperator.Greater },
{ "<=", ExpressionOperator.LowerOrEqual },
{ ">=", ExpressionOperator.GreaterOrEqual },
{ "is", ExpressionOperator.Is },
{ "==", ExpressionOperator.Equal },
{ "!=", ExpressionOperator.NotEqual },
{ "&&", ExpressionOperator.ConditionalAnd },
{ "||", ExpressionOperator.ConditionalOr },
{ "!", ExpressionOperator.LogicalNegation },
{ "~", ExpressionOperator.BitwiseComplement },
{ "&", ExpressionOperator.LogicalAnd },
{ "|", ExpressionOperator.LogicalOr },
{ "^", ExpressionOperator.LogicalXor },
{ "<<", ExpressionOperator.ShiftBitsLeft },
{ ">>", ExpressionOperator.ShiftBitsRight },
{ "??", ExpressionOperator.NullCoalescing },
};
protected static readonly IList<ExpressionOperator> leftOperandOnlyOperatorsEvaluationDictionary = new List<ExpressionOperator>();
protected static readonly IList<ExpressionOperator> rightOperandOnlyOperatorsEvaluationDictionary = new List<ExpressionOperator>()
{
ExpressionOperator.LogicalNegation,
ExpressionOperator.BitwiseComplement,
ExpressionOperator.UnaryPlus,
ExpressionOperator.UnaryMinus
};
protected virtual IList<ExpressionOperator> LeftOperandOnlyOperatorsEvaluationDictionary => leftOperandOnlyOperatorsEvaluationDictionary;
protected virtual IList<ExpressionOperator> RightOperandOnlyOperatorsEvaluationDictionary => rightOperandOnlyOperatorsEvaluationDictionary;
protected virtual IList<IDictionary<ExpressionOperator, Func<dynamic, dynamic, object>>> OperatorsEvaluations => operatorsEvaluations;
protected static object IndexingOperatorFunc(dynamic left, dynamic right)
{
if (left is NullConditionalNullValue)
{
return left;
}
else if (left is BubbleExceptionContainer)
{
return left;
}
Type type = ((object)left).GetType();
if (left is IDictionary<string, object> dictionaryLeft)
{
return dictionaryLeft[right];
}
else if (type.GetMethod("Item", new Type[] { ((object)right).GetType() }) is MethodInfo methodInfo)
{
return methodInfo.Invoke(left, new object[] { right });
}
return left[right];
}
protected static readonly IList<IDictionary<ExpressionOperator, Func<dynamic, dynamic, object>>> operatorsEvaluations =
new List<IDictionary<ExpressionOperator, Func<dynamic, dynamic, object>>>()
{
new Dictionary<ExpressionOperator, Func<dynamic, dynamic, object>>()
{
{ExpressionOperator.Indexing, IndexingOperatorFunc},
{ExpressionOperator.IndexingWithNullConditional, (dynamic left, dynamic right) =>
{
if(left == null)
return new NullConditionalNullValue();
return IndexingOperatorFunc(left, right);
}
},
},
new Dictionary<ExpressionOperator, Func<dynamic, dynamic, object>>()
{
{ExpressionOperator.UnaryPlus, (dynamic _, dynamic right) => +right },
{ExpressionOperator.UnaryMinus, (dynamic _, dynamic right) => -right },
{ExpressionOperator.LogicalNegation, (dynamic _, dynamic right) => !right },
{ExpressionOperator.BitwiseComplement, (dynamic _, dynamic right) => ~right },
{ExpressionOperator.Cast, (dynamic left, dynamic right) => ChangeType(right, left) },
},
new Dictionary<ExpressionOperator, Func<dynamic, dynamic, object>>()
{
{ExpressionOperator.Multiply, (dynamic left, dynamic right) => left * right },
{ExpressionOperator.Divide, (dynamic left, dynamic right) => left / right },
{ExpressionOperator.Modulo, (dynamic left, dynamic right) => left % right },
},
new Dictionary<ExpressionOperator, Func<dynamic, dynamic, object>>()
{
{ExpressionOperator.Plus, (dynamic left, dynamic right) => left + right },
{ExpressionOperator.Minus, (dynamic left, dynamic right) => left - right },
},
new Dictionary<ExpressionOperator, Func<dynamic, dynamic, object>>()
{
{ExpressionOperator.ShiftBitsLeft, (dynamic left, dynamic right) => left << right },
{ExpressionOperator.ShiftBitsRight, (dynamic left, dynamic right) => left >> right },
},
new Dictionary<ExpressionOperator, Func<dynamic, dynamic, object>>()
{
{ExpressionOperator.Lower, (dynamic left, dynamic right) => left < right },
{ExpressionOperator.Greater, (dynamic left, dynamic right) => left > right },
{ExpressionOperator.LowerOrEqual, (dynamic left, dynamic right) => left <= right },
{ExpressionOperator.GreaterOrEqual, (dynamic left, dynamic right) => left >= right },
{ExpressionOperator.Is, (dynamic left, dynamic right) => left != null && (((ClassOrEnumType)right).Type).IsAssignableFrom(left.GetType()) },
},
new Dictionary<ExpressionOperator, Func<dynamic, dynamic, object>>()
{
{ExpressionOperator.Equal, (dynamic left, dynamic right) => left == right },
{ExpressionOperator.NotEqual, (dynamic left, dynamic right) => left != right },
},
new Dictionary<ExpressionOperator, Func<dynamic, dynamic, object>>()
{
{ExpressionOperator.LogicalAnd, (dynamic left, dynamic right) => left & right },
},
new Dictionary<ExpressionOperator, Func<dynamic, dynamic, object>>()
{
{ExpressionOperator.LogicalXor, (dynamic left, dynamic right) => left ^ right },
},
new Dictionary<ExpressionOperator, Func<dynamic, dynamic, object>>()
{
{ExpressionOperator.LogicalOr, (dynamic left, dynamic right) => left | right },
},
new Dictionary<ExpressionOperator, Func<dynamic, dynamic, object>>()
{
{ExpressionOperator.ConditionalAnd, (dynamic left, dynamic right) => {
if ( left is BubbleExceptionContainer leftExceptionContainer)
{
throw leftExceptionContainer.Exception;
}
else if (!left)
{
return false;
}
else if (right is BubbleExceptionContainer rightExceptionContainer)
{
throw rightExceptionContainer.Exception;
}
else
{
return left && right;
}
} },
},
new Dictionary<ExpressionOperator, Func<dynamic, dynamic, object>>()
{
{ExpressionOperator.ConditionalOr, (dynamic left, dynamic right) => {
if ( left is BubbleExceptionContainer leftExceptionContainer)
{
throw leftExceptionContainer.Exception;
}
else if (left)
{
return true;
}
else if (right is BubbleExceptionContainer rightExceptionContainer)
{
throw rightExceptionContainer.Exception;
}
else
{
return left || right;
}
} },
},
new Dictionary<ExpressionOperator, Func<dynamic, dynamic, object>>()
{
{ExpressionOperator.NullCoalescing, (dynamic left, dynamic right) => left ?? right },
},
};
protected IDictionary<string, object> defaultVariables = new Dictionary<string, object>(StringComparer.Ordinal)
{
{ "Pi", Math.PI },
{ "E", Math.E },
{ "null", null},
{ "true", true },
{ "false", false },
};
protected IDictionary<string, Func<double, double>> simpleDoubleMathFuncsDictionary = new Dictionary<string, Func<double, double>>(StringComparer.Ordinal)
{
{ "Abs", Math.Abs },
{ "Acos", Math.Acos },
{ "Asin", Math.Asin },
{ "Atan", Math.Atan },
{ "Ceiling", Math.Ceiling },
{ "Cos", Math.Cos },
{ "Cosh", Math.Cosh },
{ "Exp", Math.Exp },
{ "Floor", Math.Floor },
{ "Log10", Math.Log10 },
{ "Sin", Math.Sin },
{ "Sinh", Math.Sinh },
{ "Sqrt", Math.Sqrt },
{ "Tan", Math.Tan },
{ "Tanh", Math.Tanh },
{ "Truncate", Math.Truncate },
};
protected IDictionary<string, Func<double, double, double>> doubleDoubleMathFuncsDictionary = new Dictionary<string, Func<double, double, double>>(StringComparer.Ordinal)
{
{ "Atan2", Math.Atan2 },
{ "IEEERemainder", Math.IEEERemainder },
{ "Log", Math.Log },
{ "Pow", Math.Pow },
};
protected IDictionary<string, Func<ExpressionEvaluator, List<string>, object>> complexStandardFuncsDictionary = new Dictionary<string, Func<ExpressionEvaluator, List<string>, object>>(StringComparer.Ordinal)
{
{ "Array", (self, args) => args.ConvertAll(self.Evaluate).ToArray() },
{ "ArrayOfType", (self, args) =>
{
Array sourceArray = args.Skip(1).Select(self.Evaluate).ToArray();
Array typedArray = Array.CreateInstance((Type)self.Evaluate(args[0]), sourceArray.Length);
Array.Copy(sourceArray, typedArray, sourceArray.Length);
return typedArray;
}
},
{ "Avg", (self, args) => args.ConvertAll(arg => Convert.ToDouble(self.Evaluate(arg))).Sum() / args.Count },
{ "default", (self, args) =>
{
object argValue = self.Evaluate(args[0]);
if (argValue is ClassOrEnumType classOrTypeName)
return Activator.CreateInstance(classOrTypeName.Type);
else
return null;
}
},
{ "in", (self, args) => args.Skip(1).ToList().ConvertAll(self.Evaluate).Contains(self.Evaluate(args[0])) },
{ "List", (self, args) => args.ConvertAll(self.Evaluate) },
{ "ListOfType", (self, args) =>
{
Type type = (Type)self.Evaluate(args[0]);
Array sourceArray = args.Skip(1).Select(self.Evaluate).ToArray();
Array typedArray = Array.CreateInstance(type, sourceArray.Length);
Array.Copy(sourceArray, typedArray, sourceArray.Length);
Type typeOfList = typeof(List<>).MakeGenericType(type);
object list = Activator.CreateInstance(typeOfList);
typeOfList.GetMethod("AddRange").Invoke(list, new object[]{ typedArray });
return list;
}
},
{ "Max", (self, args) => args.ConvertAll(arg => Convert.ToDouble(self.Evaluate(arg))).Max() },
{ "Min", (self, args) => args.ConvertAll(arg => Convert.ToDouble(self.Evaluate(arg))).Min() },
{ "new", (self, args) =>
{
List<object> cArgs = args.ConvertAll(self.Evaluate);
return cArgs[0] is ClassOrEnumType classOrEnumType ? Activator.CreateInstance(classOrEnumType.Type, cArgs.Skip(1).ToArray()) : null;
}
},
{ "Round", (self, args) =>
{
if(args.Count == 3)
{
return Math.Round(Convert.ToDouble(self.Evaluate(args[0])), Convert.ToInt32(self.Evaluate(args[1])), (MidpointRounding)self.Evaluate(args[2]));
}
else if(args.Count == 2)
{
object arg2 = self.Evaluate(args[1]);
if(arg2 is MidpointRounding midpointRounding)
return Math.Round(Convert.ToDouble(self.Evaluate(args[0])), midpointRounding);
else
return Math.Round(Convert.ToDouble(self.Evaluate(args[0])), Convert.ToInt32(arg2));
}
else if(args.Count == 1) { return Math.Round(Convert.ToDouble(self.Evaluate(args[0]))); }
else
{
throw new ArgumentException();
}
}
},
{ "Sign", (self, args) => Math.Sign(Convert.ToDouble(self.Evaluate(args[0]))) },
{ "sizeof", (self, args) =>
{
Type type = ((ClassOrEnumType)self.Evaluate(args[0])).Type;
if(type == typeof(bool))
return 1;
else if(type == typeof(char))
return 2;
else
return Marshal.SizeOf(type);
}
},
{ "typeof", (self, args) => ((ClassOrEnumType)self.Evaluate(args[0])).Type },
};
#endregion
#region Caching
/// <summary>
/// if set to <c>true</c> use a cache for types that were resolved to resolve faster next time.
/// if set to <c>false</c> the cache of types resolution is not use for this instance of ExpressionEvaluator.
/// Default : false
/// the cache is the static Dictionary TypesResolutionCaching (so it is shared by all instances of ExpressionEvaluator that have CacheTypesResolutions enabled)
/// </summary>
public bool CacheTypesResolutions { get; set; }
/// <summary>
/// A shared cache for types resolution.
/// </summary>
public static IDictionary<string, Type> TypesResolutionCaching { get; set; } = new Dictionary<string, Type>();
/// <summary>
/// Clear all ExpressionEvaluator caches
/// </summary>
public static void ClearAllCaches()
{
TypesResolutionCaching.Clear();
}
#endregion
#region Assemblies, Namespaces and types lists
private static IList<Assembly> staticAssemblies;
private IList<Assembly> assemblies;
/// <summary>
/// All assemblies needed to resolves Types
/// by default all Assemblies loaded in the current AppDomain
/// </summary>
public virtual IList<Assembly> Assemblies
{
get { return assemblies ?? (assemblies = staticAssemblies) ?? (assemblies = staticAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList()); }
set { assemblies = value; }
}
/// <summary>
/// All Namespaces Where to find types
/// </summary>
public virtual IList<string> Namespaces { get; set; } = new List<string>()
{
"System",
"System.Linq",
"System.IO",
"System.Text",
"System.Text.RegularExpressions",
"System.ComponentModel",
"System.Dynamic",
"System.Collections",
"System.Collections.Generic",
"System.Collections.Specialized",
"System.Globalization"
};
/// <summary>
/// To add or remove specific types to manage in expression.
/// </summary>
public virtual IList<Type> Types { get; set; } = new List<Type>();
/// <summary>
/// A list of type to block an keep un usable in Expression Evaluation for security purpose
/// </summary>
public virtual IList<Type> TypesToBlock { get; set; } = new List<Type>();
/// <summary>
/// A list of statics types where to find extensions methods
/// </summary>
public virtual IList<Type> StaticTypesForExtensionsMethods { get; set; } = new List<Type>()
{
typeof(Enumerable) // For Linq extension methods
};
#endregion
#region Options
private bool optionCaseSensitiveEvaluationActive = true;
/// <summary>
/// If <c>true</c> all evaluation are case sensitives.
/// If <c>false</c> evaluations are case insensitive.
/// By default = true
/// </summary>
public bool OptionCaseSensitiveEvaluationActive
{
get { return optionCaseSensitiveEvaluationActive; }
set
{
optionCaseSensitiveEvaluationActive = value;
StringComparisonForCasing = optionCaseSensitiveEvaluationActive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
Variables = Variables;
operatorsDictionary = new Dictionary<string, ExpressionOperator>(operatorsDictionary, StringComparerForCasing);
defaultVariables = new Dictionary<string, object>(defaultVariables, StringComparerForCasing);
simpleDoubleMathFuncsDictionary = new Dictionary<string, Func<double, double>>(simpleDoubleMathFuncsDictionary, StringComparerForCasing);
doubleDoubleMathFuncsDictionary = new Dictionary<string, Func<double, double, double>>(doubleDoubleMathFuncsDictionary, StringComparerForCasing);
complexStandardFuncsDictionary = new Dictionary<string, Func<ExpressionEvaluator, List<string>, object>>(complexStandardFuncsDictionary, StringComparerForCasing);
}
}
private StringComparison StringComparisonForCasing { get; set; } = StringComparison.Ordinal;
protected StringComparer StringComparerForCasing
{
get
{
return OptionCaseSensitiveEvaluationActive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
}
}
/// <summary>
/// If <c>true</c> all numbers without decimal and suffixes evaluations will be done as double
/// If <c>false</c> Integers values without decimal and suffixes will be evaluate as int as in C# (Warning some operation can round values)
/// By default = false
/// </summary>
public bool OptionForceIntegerNumbersEvaluationsAsDoubleByDefault { get; set; }
private CultureInfo cultureInfoForNumberParsing = CultureInfo.InvariantCulture.Clone() as CultureInfo;
/// <summary>
/// The culture used to evaluate numbers
/// Synchronized with OptionNumberParsingDecimalSeparator and OptionNumberParsingThousandSeparator.
/// So always set a full CultureInfo object and do not change CultureInfoForNumberParsing.NumberFormat.NumberDecimalSeparator and CultureInfoForNumberParsing.NumberFormat.NumberGroupSeparator properties directly.
/// Warning if using comma in separators change also OptionFunctionArgumentsSeparator and OptionInitializersSeparator otherwise it will create conflicts
/// </summary>
public CultureInfo CultureInfoForNumberParsing
{
get
{
return cultureInfoForNumberParsing;
}
set
{
cultureInfoForNumberParsing = value;
OptionNumberParsingDecimalSeparator = cultureInfoForNumberParsing.NumberFormat.NumberDecimalSeparator;
OptionNumberParsingThousandSeparator = cultureInfoForNumberParsing.NumberFormat.NumberGroupSeparator;
}
}
private string optionNumberParsingDecimalSeparator = ".";
/// <summary>
/// Allow to change the decimal separator of numbers when parsing expressions.
/// By default "."
/// Warning if using comma change also OptionFunctionArgumentsSeparator and OptionInitializersSeparator otherwise it will create conflicts.
/// Modify CultureInfoForNumberParsing.
/// </summary>
public string OptionNumberParsingDecimalSeparator
{
get
{
return optionNumberParsingDecimalSeparator;
}
set
{
optionNumberParsingDecimalSeparator = value ?? ".";
CultureInfoForNumberParsing.NumberFormat.NumberDecimalSeparator = optionNumberParsingDecimalSeparator;
numberRegexPattern = string.Format(numberRegexOrigPattern,
optionNumberParsingDecimalSeparator != null ? Regex.Escape(optionNumberParsingDecimalSeparator) : ".",
optionNumberParsingThousandSeparator != null ? Regex.Escape(optionNumberParsingThousandSeparator) : "");
}
}
private string optionNumberParsingThousandSeparator = string.Empty;
/// <summary>
/// Allow to change the thousand separator of numbers when parsing expressions.
/// By default string.Empty
/// Warning if using comma change also OptionFunctionArgumentsSeparator and OptionInitializersSeparator otherwise it will create conflicts.
/// Modify CultureInfoForNumberParsing.
/// </summary>
public string OptionNumberParsingThousandSeparator
{
get
{
return optionNumberParsingThousandSeparator;
}
set
{
optionNumberParsingThousandSeparator = value ?? string.Empty;
CultureInfoForNumberParsing.NumberFormat.NumberGroupSeparator = value;
numberRegexPattern = string.Format(numberRegexOrigPattern,
optionNumberParsingDecimalSeparator != null ? Regex.Escape(optionNumberParsingDecimalSeparator) : ".",
optionNumberParsingThousandSeparator != null ? Regex.Escape(optionNumberParsingThousandSeparator) : "");
}
}
/// <summary>
/// Allow to change the separator of functions arguments.
/// By default ","
/// Warning must to be changed if OptionNumberParsingDecimalSeparator = "," otherwise it will create conflicts
/// </summary>
public string OptionFunctionArgumentsSeparator { get; set; } = ",";
/// <summary>
/// Allow to change the separator of Object and collections Initialization between { and } after the keyword new.
/// By default ","
/// Warning must to be changed if OptionNumberParsingDecimalSeparator = "," otherwise it will create conflicts
/// </summary>
public string OptionInitializersSeparator { get; set; } = ",";
/// <summary>
/// if <c>true</c> allow to add the prefix Fluid or Fluent before void methods names to return back the instance on which the method is call.
/// if <c>false</c> unactive this functionality.
/// By default : true
/// </summary>
public bool OptionFluidPrefixingActive { get; set; } = true;
/// <summary>
/// if <c>true</c> allow the use of inline namespace (Can be slow, and is less secure).
/// if <c>false</c> unactive inline namespace (only namespaces in Namespaces list are available).
/// By default : true
/// </summary>
public bool OptionInlineNamespacesEvaluationActive { get; set; } = true;
private Func<ExpressionEvaluator, List<string>, object> newMethodMem;
/// <summary>
/// if <c>true</c> allow to create instance of object with the Default function new(ClassNam,...).
/// if <c>false</c> unactive this functionality.
/// By default : true
/// </summary>
public bool OptionNewFunctionEvaluationActive
{
get
{
return complexStandardFuncsDictionary.ContainsKey("new");
}
set
{
if (value && !complexStandardFuncsDictionary.ContainsKey("new"))
{
complexStandardFuncsDictionary["new"] = newMethodMem;
}
else if (!value && complexStandardFuncsDictionary.ContainsKey("new"))
{
newMethodMem = complexStandardFuncsDictionary["new"];
complexStandardFuncsDictionary.Remove("new");
}
}
}
/// <summary>
/// if <c>true</c> allow to create instance of object with the C# syntax new ClassName(...).
/// if <c>false</c> unactive this functionality.
/// By default : true
/// </summary>
public bool OptionNewKeywordEvaluationActive { get; set; } = true;
/// <summary>
/// if <c>true</c> allow to call static methods on classes.
/// if <c>false</c> unactive this functionality.
/// By default : true
/// </summary>
public bool OptionStaticMethodsCallActive { get; set; } = true;
/// <summary>
/// if <c>true</c> allow to get static properties on classes
/// if <c>false</c> unactive this functionality.
/// By default : true
/// </summary>
public bool OptionStaticPropertiesGetActive { get; set; } = true;
/// <summary>
/// if <c>true</c> allow to call instance methods on objects.
/// if <c>false</c> unactive this functionality.
/// By default : true
/// </summary>
public bool OptionInstanceMethodsCallActive { get; set; } = true;
/// <summary>
/// if <c>true</c> allow to get instance properties on objects
/// if <c>false</c> unactive this functionality.
/// By default : true
/// </summary>
public bool OptionInstancePropertiesGetActive { get; set; } = true;
/// <summary>
/// if <c>true</c> allow to get object at index or key like IndexedObject[indexOrKey]
/// if <c>false</c> unactive this functionality.
/// By default : true
/// </summary>
public bool OptionIndexingActive { get; set; } = true;
/// <summary>
/// if <c>true</c> allow string interpretation with ""
/// if <c>false</c> unactive this functionality.
/// By default : true
/// </summary>
public bool OptionStringEvaluationActive { get; set; } = true;
/// <summary>
/// if <c>true</c> allow char interpretation with ''
/// if <c>false</c> unactive this functionality.
/// By default : true
/// </summary>
public bool OptionCharEvaluationActive { get; set; } = true;
/// <summary>
/// If <c>true</c> Evaluate function is callables in an expression. If <c>false</c> Evaluate is not callable.
/// By default : true
/// if set to false for security (also ensure that ExpressionEvaluator type is in TypesToBlock list)
/// </summary>
public bool OptionEvaluateFunctionActive { get; set; } = true;
/// <summary>
/// If <c>true</c> allow to assign a value to a variable in the Variable disctionary with (=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, ++ or --)
/// If <c>false</c> unactive this functionality
/// By default : true
/// </summary>
public bool OptionVariableAssignationActive { get; set; } = true;
/// <summary>
/// If <c>true</c> allow to set/modify a property or a field value with (=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, ++ or --)
/// If <c>false</c> unactive this functionality
/// By default : true
/// </summary>
public bool OptionPropertyOrFieldSetActive { get; set; } = true;
/// <summary>
/// If <c>true</c> allow to assign a indexed element like Collections, List, Arrays and Dictionaries with (=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, ++ or --)
/// If <c>false</c> unactive this functionality
/// By default : true
/// </summary>
public bool OptionIndexingAssignationActive { get; set; } = true;
/// <summary>
/// If <c>true</c> ScriptEvaluate function is callables in an expression. If <c>false</c> Evaluate is not callable.
/// By default : true
/// if set to false for security (also ensure that ExpressionEvaluator type is in TypesToBlock list)
/// </summary>
public bool OptionScriptEvaluateFunctionActive { get; set; } = true;
/// <summary>
/// If <c>ReturnAutomaticallyLastEvaluatedExpression</c> ScriptEvaluate return automatically the last evaluated expression if no return keyword is met.
/// If <c>ReturnNull</c> return null if no return keyword is met.
/// If <c>ThrowSyntaxException</c> a exception is throw if no return keyword is met.
/// By default : ReturnAutomaticallyLastEvaluatedExpression;
/// </summary>
public OptionOnNoReturnKeywordFoundInScriptAction OptionOnNoReturnKeywordFoundInScriptAction { get; set; }
/// <summary>
/// If <c>true</c> ScriptEvaluate need to have a semicolon [;] after each expression.
/// If <c>false</c> Allow to omit the semicolon for the last expression of the script.
/// Default : true
/// </summary>
public bool OptionScriptNeedSemicolonAtTheEndOfLastExpression { get; set; } = true;
/// <summary>
/// If <c>true</c> Allow to access fields, properties and methods that are not declared public. (private, protected and internal)
/// If <c>false</c> Allow to access only to public members.
/// Default : false
/// Warning : This clearly break the encapsulation principle use this only if you know what you do.
/// </summary>
public bool OptionAllowNonPublicMembersAccess { get; set; }
/// <summary>
/// If <c>true</c> On unsuccessful call to an extension method, all defined overloads of that method are detected to resolve whether method is defined and called with wrong arguments or method is not defined.
/// If <c>false</c> Unsucessful call to an extension method will always result in "Method {name} is not defined on type {type}"
/// Default : true
/// </summary>
public bool OptionDetectExtensionMethodsOverloadsOnExtensionMethodNotFound { get; set; } = true;
#endregion
#region Reflection flags
protected virtual BindingFlags InstanceBindingFlag
{
get
{
BindingFlags flag = BindingFlags.Default | BindingFlags.Public | BindingFlags.Instance;
if (!OptionCaseSensitiveEvaluationActive)
flag |= BindingFlags.IgnoreCase;
if (OptionAllowNonPublicMembersAccess)
flag |= BindingFlags.NonPublic;
return flag;
}
}
protected virtual BindingFlags StaticBindingFlag
{
get
{
BindingFlags flag = BindingFlags.Default | BindingFlags.Public | BindingFlags.Static;
if (!OptionCaseSensitiveEvaluationActive)
flag |= BindingFlags.IgnoreCase;
if (OptionAllowNonPublicMembersAccess)
flag |= BindingFlags.NonPublic;
return flag;
}
}
#endregion
#region Custom and on the fly variables and methods
/// <summary>
/// If set, this object is used to use it's fields, properties and methods as global variables and functions
/// </summary>
public object Context { get; set; }
private IDictionary<string, object> variables = new Dictionary<string, object>(StringComparer.Ordinal);
/// <summary>
/// Counts stack initialisations to determine if the expression enty point was reached. In that case the transported exception should be thrown.
/// </summary>
private int evaluationStackCount;
/// <summary>
/// The Values of the variable use in the expressions
/// </summary>
public IDictionary<string, object> Variables
{
get { return variables; }
set { variables = value == null ? new Dictionary<string, object>(StringComparerForCasing) : new Dictionary<string, object>(value, StringComparerForCasing); }
}
/// <summary>
/// Is Fired before a variable, field or property resolution.
/// Allow to define a variable and the corresponding value on the fly.
/// Allow also to cancel the evaluation of this variable (consider it does'nt exists)
/// </summary>
public event EventHandler<VariablePreEvaluationEventArg> PreEvaluateVariable;
/// <summary>
/// Is Fired before a function or method resolution.
/// Allow to define a function or method and the corresponding value on the fly.
/// Allow also to cancel the evaluation of this function (consider it does'nt exists)
/// </summary>
public event EventHandler<FunctionPreEvaluationEventArg> PreEvaluateFunction;
/// <summary>
/// Is Fired if no variable, field or property were found
/// Allow to define a variable and the corresponding value on the fly.
/// </summary>
public event EventHandler<VariableEvaluationEventArg> EvaluateVariable;
/// <summary>
/// Is Fired if no function or method when were found.
/// Allow to define a function or method and the corresponding value on the fly.
/// </summary>
public event EventHandler<FunctionEvaluationEventArg> EvaluateFunction;
#endregion
#region Constructors and overridable Inits methods
/// <summary>
/// Default Constructor
/// </summary>
public ExpressionEvaluator()
{
DefaultDecimalSeparatorInit();
Init();
}
/// <summary>
/// Constructor with variables initialize
/// </summary>
/// <param name="variables">The Values of variables use in the expressions</param>
public ExpressionEvaluator(IDictionary<string, object> variables) : this()
{
Variables = variables;
}
/// <summary>
/// Constructor with context initialize
/// </summary>
/// <param name="context">the context that propose it's fields, properties and methods to the evaluation</param>
public ExpressionEvaluator(object context) : this()
{
Context = context;
}
/// <summary>
/// Constructor with variables and context initialize
/// </summary>
/// <param name="context">the context that propose it's fields, properties and methods to the evaluation</param>
/// <param name="variables">The Values of variables use in the expressions</param>
public ExpressionEvaluator(object context, IDictionary<string, object> variables) : this()
{
Context = context;
Variables = variables;
}
protected virtual void DefaultDecimalSeparatorInit()
{
numberRegexPattern = string.Format(numberRegexOrigPattern, @"\.", string.Empty);
CultureInfoForNumberParsing.NumberFormat.NumberDecimalSeparator = ".";
}
protected virtual void Init()
{ }
#endregion
#region Main evaluate methods (Expressions and scripts ==> public)
#region Scripts
protected bool inScript;
/// <summary>
/// Evaluate a script (multiple expressions separated by semicolon)
/// Support Assignation with [=] (for simple variable write in the Variables dictionary)
/// support also if, else if, else while and for keywords
/// </summary>
/// <typeparam name="T">The type in which to cast the result of the expression</typeparam>
/// <param name="script">the script to evaluate</param>
/// <returns>The result of the last evaluated expression</returns>