-
-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathInterpreter.cs
More file actions
591 lines (495 loc) · 17.6 KB
/
Interpreter.cs
File metadata and controls
591 lines (495 loc) · 17.6 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using DynamicExpresso.Exceptions;
using DynamicExpresso.Parsing;
using DynamicExpresso.Reflection;
using DynamicExpresso.Resources;
using DynamicExpresso.Visitors;
namespace DynamicExpresso
{
/// <summary>
/// Class used to parse and compile a text expression into an Expression or a Delegate that can be invoked. Expression are written using a subset of C# syntax.
/// Only get properties, Parse and Eval methods are thread safe.
/// </summary>
public class Interpreter
{
private readonly ParserSettings _settings;
private readonly ISet<ExpressionVisitor> _visitors = new HashSet<ExpressionVisitor>();
#region Constructors
/// <summary>
/// Creates a new Interpreter using InterpreterOptions.Default.
/// </summary>
public Interpreter()
: this(InterpreterOptions.Default)
{
}
/// <summary>
/// Creates a new Interpreter using the specified options.
/// </summary>
/// <param name="options"></param>
public Interpreter(InterpreterOptions options)
{
var caseInsensitive = options.HasFlag(InterpreterOptions.CaseInsensitive);
var lateBindObject = options.HasFlag(InterpreterOptions.LateBindObject);
_settings = new ParserSettings(caseInsensitive, lateBindObject);
if ((options & InterpreterOptions.SystemKeywords) == InterpreterOptions.SystemKeywords)
{
SetIdentifiers(LanguageConstants.Literals);
}
if ((options & InterpreterOptions.PrimitiveTypes) == InterpreterOptions.PrimitiveTypes)
{
Reference(LanguageConstants.PrimitiveTypes);
Reference(LanguageConstants.CSharpPrimitiveTypes);
}
if ((options & InterpreterOptions.CommonTypes) == InterpreterOptions.CommonTypes)
{
Reference(LanguageConstants.CommonTypes);
}
if ((options & InterpreterOptions.LambdaExpressions) == InterpreterOptions.LambdaExpressions)
{
_settings.LambdaExpressions = true;
}
_visitors.Add(new DisableReflectionVisitor());
}
/// <summary>
/// Create a new interpreter with the settings copied from another interpreter
/// </summary>
internal Interpreter(ParserSettings settings)
{
_settings = settings;
}
#endregion
#region Properties
public bool CaseInsensitive
{
get
{
return _settings.CaseInsensitive;
}
}
/// <summary>
/// Gets a list of registeres types. Add types by using the Reference method.
/// </summary>
public IEnumerable<ReferenceType> ReferencedTypes
{
get
{
return _settings.KnownTypes
.Select(p => p.Value)
.ToList();
}
}
/// <summary>
/// Gets a list of known identifiers. Add identifiers using SetVariable, SetFunction or SetExpression methods.
/// </summary>
public IEnumerable<Identifier> Identifiers
{
get
{
return _settings.Identifiers
.Select(p => p.Value)
.ToList();
}
}
/// <summary>
/// Gets the available assignment operators.
/// </summary>
public AssignmentOperators AssignmentOperators
{
get { return _settings.AssignmentOperators; }
}
#endregion
#region Options
/// <summary>
/// Allow to set de default numeric type when no suffix is specified (Int by default, Double if real number)
/// </summary>
/// <param name="defaultNumberType"></param>
/// <returns></returns>
public Interpreter SetDefaultNumberType(DefaultNumberType defaultNumberType)
{
_settings.DefaultNumberType = defaultNumberType;
return this;
}
/// <summary>
/// Allows to enable/disable assignment operators.
/// For security when expression are generated by the users is more safe to disable assignment operators.
/// </summary>
/// <param name="assignmentOperators"></param>
/// <returns></returns>
public Interpreter EnableAssignment(AssignmentOperators assignmentOperators)
{
_settings.AssignmentOperators = assignmentOperators;
return this;
}
#endregion
#region Visitors
public ISet<ExpressionVisitor> Visitors
{
get { return _visitors; }
}
/// <summary>
/// Enable reflection expression (like x.GetType().GetMethod() or typeof(double).Assembly) by removing the DisableReflectionVisitor.
/// </summary>
/// <returns></returns>
public Interpreter EnableReflection()
{
var visitor = Visitors.FirstOrDefault(p => p is DisableReflectionVisitor);
if (visitor != null)
Visitors.Remove(visitor);
return this;
}
#endregion
#region Register identifiers
/// <summary>
/// Allow the specified function delegate to be called from a parsed expression.
/// Overloads can be added (ie. multiple delegates can be registered with the same name).
/// A delegate will replace any delegate with the exact same signature that is already registered.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
public Interpreter SetFunction(string name, Delegate value)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
if (_settings.Identifiers.TryGetValue(name, out var identifier) &&
identifier is FunctionIdentifier fIdentifier)
{
fIdentifier.AddOverload(value);
}
else
{
SetIdentifier(new FunctionIdentifier(name, value));
}
return this;
}
/// <summary>
/// Allow the specified variable to be used in a parsed expression.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
public Interpreter SetVariable(string name, object value)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
return SetExpression(name, Expression.Constant(value));
}
/// <summary>
/// Allow the specified variable to be used in a parsed expression.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
public Interpreter SetVariable<T>(string name, T value)
{
return SetVariable(name, value, typeof(T));
}
/// <summary>
/// Allow the specified variable to be used in a parsed expression.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <param name="type"></param>
/// <returns></returns>
public Interpreter SetVariable(string name, object value, Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
return SetExpression(name, Expression.Constant(value, type));
}
/// <summary>
/// Allow the specified Expression to be used in a parsed expression.
/// Basically add the specified expression as a known identifier.
/// </summary>
/// <param name="name"></param>
/// <param name="expression"></param>
/// <returns></returns>
public Interpreter SetExpression(string name, Expression expression)
{
return SetIdentifier(new Identifier(name, expression));
}
/// <summary>
/// Allow the specified list of identifiers to be used in a parsed expression.
/// Basically add the specified expressions as a known identifier.
/// </summary>
/// <param name="identifiers"></param>
/// <returns></returns>
public Interpreter SetIdentifiers(IEnumerable<Identifier> identifiers)
{
foreach (var i in identifiers)
SetIdentifier(i);
return this;
}
/// <summary>
/// Allow the specified identifier to be used in a parsed expression.
/// Basically add the specified expression as a known identifier.
/// </summary>
/// <param name="identifier"></param>
/// <returns></returns>
public Interpreter SetIdentifier(Identifier identifier)
{
if (identifier == null)
throw new ArgumentNullException(nameof(identifier));
if (LanguageConstants.ReservedKeywords.Contains(identifier.Name))
throw new InvalidOperationException(string.Format(ErrorMessages.ReservedWord, identifier.Name));
_settings.Identifiers[identifier.Name] = identifier;
return this;
}
/// <summary>
/// Remove <paramref name="name"/> from the list of known identifiers.
/// </summary>
/// <param name="name"></param>>
/// <returns></returns>
public Interpreter UnsetFunction(string name)
{
return UnsetIdentifier(name);
}
/// <summary>
/// Remove <paramref name="name"/> from the list of known identifiers.
/// </summary>
/// <param name="name"></param>>
/// <returns></returns>
public Interpreter UnsetVariable(string name)
{
return UnsetIdentifier(name);
}
/// <summary>
/// Remove <paramref name="name"/> from the list of known identifiers.
/// </summary>
/// <param name="name"></param>>
/// <returns></returns>
public Interpreter UnsetExpression(string name)
{
return UnsetIdentifier(name);
}
/// <summary>
/// Remove <paramref name="name"/> from the list of known identifiers.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public Interpreter UnsetIdentifier(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
_settings.Identifiers.Remove(name);
return this;
}
#endregion
#region Register referenced types
/// <summary>
/// Allow the specified type to be used inside an expression. The type will be available using its name.
/// If the type contains method extensions methods they will be available inside expressions.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public Interpreter Reference(Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
return Reference(type, type.Name);
}
/// <summary>
/// Allow the specified type to be used inside an expression.
/// See Reference(Type, string) method.
/// </summary>
/// <param name="types"></param>
/// <returns></returns>
public Interpreter Reference(IEnumerable<ReferenceType> types)
{
if (types == null)
throw new ArgumentNullException(nameof(types));
foreach (var t in types)
Reference(t);
return this;
}
/// <summary>
/// Allow the specified type to be used inside an expression by using a custom alias.
/// If the type contains extensions methods they will be available inside expressions.
/// </summary>
/// <param name="type"></param>
/// <param name="typeName">Public name that must be used in the expression.</param>
/// <returns></returns>
public Interpreter Reference(Type type, string typeName)
{
return Reference(new ReferenceType(typeName, type));
}
/// <summary>
/// Allow the specified type to be used inside an expression by using a custom alias.
/// If the type contains extensions methods they will be available inside expressions.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public Interpreter Reference(ReferenceType type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
_settings.KnownTypes[type.Name] = type;
_settings.ExtensionMethods.UnionWith(type.ExtensionMethods);
return this;
}
#endregion
#region Parse
/// <summary>
/// Parse a text expression and returns a Lambda class that can be used to invoke it.
/// </summary>
/// <param name="expressionText">Expression statement</param>
/// <param name="parameters"></param>
/// <returns></returns>
/// <exception cref="ParseException"></exception>
public Lambda Parse(string expressionText, params Parameter[] parameters)
{
return Parse(expressionText, typeof(void), parameters);
}
/// <summary>
/// Parse a text expression and returns a Lambda class that can be used to invoke it.
/// If the expression cannot be converted to the type specified in the expressionType parameter
/// an exception is throw.
/// </summary>
/// <param name="expressionText">Expression statement</param>
/// <param name="expressionType">The expected return type. Use void or object type if there isn't an expected return type.</param>
/// <param name="parameters"></param>
/// <returns></returns>
/// <exception cref="ParseException"></exception>
public Lambda Parse(string expressionText, Type expressionType, params Parameter[] parameters)
{
return ParseAsLambda(expressionText, expressionType, parameters);
}
[Obsolete("Use ParseAsDelegate<TDelegate>(string, params string[])")]
public TDelegate Parse<TDelegate>(string expressionText, params string[] parametersNames)
{
return ParseAsDelegate<TDelegate>(expressionText, parametersNames);
}
/// <summary>
/// Parse a text expression and convert it into a delegate.
/// </summary>
/// <typeparam name="TDelegate">Delegate to use</typeparam>
/// <param name="expressionText">Expression statement</param>
/// <param name="parametersNames">Names of the parameters. If not specified the parameters names defined inside the delegate are used.</param>
/// <returns></returns>
/// <exception cref="ParseException"></exception>
public TDelegate ParseAsDelegate<TDelegate>(string expressionText, params string[] parametersNames)
{
var lambda = ParseAs<TDelegate>(expressionText, parametersNames);
return lambda.Compile<TDelegate>();
}
/// <summary>
/// Parse a text expression and convert it into a lambda expression.
/// </summary>
/// <typeparam name="TDelegate">Delegate to use</typeparam>
/// <param name="expressionText">Expression statement</param>
/// <param name="parametersNames">Names of the parameters. If not specified the parameters names defined inside the delegate are used.</param>
/// <returns></returns>
/// <exception cref="ParseException"></exception>
public Expression<TDelegate> ParseAsExpression<TDelegate>(string expressionText,
params string[] parametersNames)
{
var lambda = ParseAs<TDelegate>(expressionText, parametersNames);
return lambda.LambdaExpression<TDelegate>();
}
internal LambdaExpression ParseAsExpression(Type delegateType, string expressionText,
params string[] parametersNames)
{
var delegateInfo = ReflectionExtensions.GetDelegateInfo(delegateType, parametersNames);
// return type is object means that we have no information beforehand
// => we force it to typeof(void) so that no conversion expression is emitted by the parser
// and the actual expression type is preserved
var returnType = delegateInfo.ReturnType;
if (returnType == typeof(object))
returnType = typeof(void);
var lambda = ParseAsLambda(expressionText, returnType, delegateInfo.Parameters);
return lambda.LambdaExpression(delegateType);
}
public Lambda ParseAs<TDelegate>(string expressionText, params string[] parametersNames)
{
return ParseAs(typeof(TDelegate), expressionText, parametersNames);
}
internal Lambda ParseAs(Type delegateType, string expressionText, params string[] parametersNames)
{
var delegateInfo = ReflectionExtensions.GetDelegateInfo(delegateType, parametersNames);
return ParseAsLambda(expressionText, delegateInfo.ReturnType, delegateInfo.Parameters);
}
#endregion
#region Eval
/// <summary>
/// Parse and invoke the specified expression.
/// </summary>
/// <param name="expressionText"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public object Eval(string expressionText, params Parameter[] parameters)
{
return Eval(expressionText, typeof(void), parameters);
}
/// <summary>
/// Parse and invoke the specified expression.
/// </summary>
/// <param name="expressionText"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public T Eval<T>(string expressionText, params Parameter[] parameters)
{
return (T)Eval(expressionText, typeof(T), parameters);
}
/// <summary>
/// Parse and invoke the specified expression.
/// </summary>
/// <param name="expressionText"></param>
/// <param name="expressionType">The return type of the expression. Use void or object if you don't know the expected return type.</param>
/// <param name="parameters"></param>
/// <returns></returns>
public object Eval(string expressionText, Type expressionType, params Parameter[] parameters)
{
// Eval is intended for one-off expressions: prefer interpretation to avoid IL generation cost.
var lambda = ParseAsLambda(expressionText, expressionType, parameters, preferInterpretation: true);
return lambda.Invoke(parameters);
}
#endregion
#region Detection
public IdentifiersInfo DetectIdentifiers(string expression)
{
var detector = new Detector(_settings);
return detector.DetectIdentifiers(expression, DetectorOptions.None);
}
public IdentifiersInfo DetectIdentifiers(string expression, DetectorOptions options)
{
var detector = new Detector(_settings);
return detector.DetectIdentifiers(expression, options);
}
#endregion
#region Private methods
private Lambda ParseAsLambda(string expressionText, Type expressionType, Parameter[] parameters, bool preferInterpretation = false)
{
var arguments = new ParserArguments(
expressionText,
_settings,
expressionType,
parameters);
var expression = Parser.Parse(arguments);
foreach (var visitor in Visitors)
expression = visitor.Visit(expression);
var lambda = new Lambda(expression, arguments, preferInterpretation);
#if TEST_DetectIdentifiers
AssertDetectIdentifiers(lambda);
#endif
return lambda;
}
#if TEST_DetectIdentifiers
private void AssertDetectIdentifiers(Lambda lambda)
{
var info = DetectIdentifiers(lambda.ExpressionText);
if (info.Identifiers.Count() != lambda.Identifiers.Count())
throw new Exception("Detected identifiers doesn't match actual identifiers");
if (info.Types.Count() != lambda.Types.Count())
throw new Exception("Detected types doesn't match actual types");
if (info.UnknownIdentifiers.Count() != lambda.UsedParameters.Count())
throw new Exception("Detected unknown identifiers doesn't match actual parameters");
}
#endif
#endregion
}
}