-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathParameterExtractingExpressionVisitor.cs
More file actions
804 lines (680 loc) · 34.1 KB
/
ParameterExtractingExpressionVisitor.cs
File metadata and controls
804 lines (680 loc) · 34.1 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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace Microsoft.EntityFrameworkCore.Query.Internal;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class ParameterExtractingExpressionVisitor : ExpressionVisitor
{
private const string QueryFilterPrefix = "ef_filter";
private readonly IParameterValues _parameterValues;
private readonly IDiagnosticsLogger<DbLoggerCategory.Query> _logger;
private readonly bool _parameterize;
private readonly bool _generateContextAccessors;
private readonly EvaluatableExpressionFindingExpressionVisitor _evaluatableExpressionFindingExpressionVisitor;
private readonly ContextParameterReplacingExpressionVisitor _contextParameterReplacingExpressionVisitor;
private readonly Dictionary<Expression, EvaluatedValues> _evaluatedValues = new(ExpressionEqualityComparer.Instance);
private IDictionary<Expression, bool> _evaluatableExpressions;
private IQueryProvider? _currentQueryProvider;
private static readonly bool UseOldBehavior31552 =
AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue31552", out var enabled31552) && enabled31552;
private static readonly bool UseOldBehavior35100 =
AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue35100", out var enabled35100) && enabled35100;
private static readonly bool UseOldBehavior37176 =
AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue37176", out var enabled37176) && enabled37176;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public ParameterExtractingExpressionVisitor(
IEvaluatableExpressionFilter evaluatableExpressionFilter,
IParameterValues parameterValues,
Type contextType,
IModel model,
IDiagnosticsLogger<DbLoggerCategory.Query> logger,
bool parameterize,
bool generateContextAccessors)
{
_evaluatableExpressionFindingExpressionVisitor
= new EvaluatableExpressionFindingExpressionVisitor(evaluatableExpressionFilter, model, parameterize);
_parameterValues = parameterValues;
_logger = logger;
_parameterize = parameterize;
_generateContextAccessors = generateContextAccessors;
// The entry method will take care of populating this field always. So accesses should be safe.
_evaluatableExpressions = null!;
_contextParameterReplacingExpressionVisitor = _generateContextAccessors
? new ContextParameterReplacingExpressionVisitor(contextType)
: null!;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual Expression ExtractParameters(Expression expression)
=> ExtractParameters(expression, clearEvaluatedValues: true);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual Expression ExtractParameters(Expression expression, bool clearEvaluatedValues)
{
var oldEvaluatableExpressions = _evaluatableExpressions;
_evaluatableExpressions = _evaluatableExpressionFindingExpressionVisitor.Find(expression);
try
{
return Visit(expression);
}
finally
{
_evaluatableExpressions = oldEvaluatableExpressions;
if (clearEvaluatedValues)
{
_evaluatedValues.Clear();
}
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[return: NotNullIfNotNull("expression")]
public override Expression? Visit(Expression? expression)
{
if (expression == null)
{
return null;
}
if (_evaluatableExpressions.TryGetValue(expression, out var generateParameter)
&& !PreserveInitializationConstant(expression, generateParameter)
&& !PreserveConvertNode(expression))
{
return Evaluate(expression, _parameterize && generateParameter);
}
return base.Visit(expression);
}
private static bool PreserveInitializationConstant(Expression expression, bool generateParameter)
=> !generateParameter && expression is NewExpression or MemberInitExpression;
private bool PreserveConvertNode(Expression expression)
{
if (expression is UnaryExpression unaryExpression
&& (unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked))
{
if (unaryExpression.Type == typeof(object)
|| unaryExpression.Type == typeof(Enum)
|| unaryExpression.Operand.Type.UnwrapNullableType().IsEnum)
{
return true;
}
var innerType = unaryExpression.Operand.Type.UnwrapNullableType();
if (unaryExpression.Type.UnwrapNullableType() == typeof(int)
&& (innerType == typeof(byte)
|| innerType == typeof(sbyte)
|| innerType == typeof(char)
|| innerType == typeof(short)
|| innerType == typeof(ushort)))
{
return true;
}
return PreserveConvertNode(unaryExpression.Operand);
}
return false;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitConditional(ConditionalExpression conditionalExpression)
{
var newTestExpression = TryGetConstantValue(conditionalExpression.Test) ?? Visit(conditionalExpression.Test);
if (newTestExpression is ConstantExpression { Value: bool constantTestValue })
{
return constantTestValue
? Visit(conditionalExpression.IfTrue)
: Visit(conditionalExpression.IfFalse);
}
return conditionalExpression.Update(
newTestExpression,
Visit(conditionalExpression.IfTrue),
Visit(conditionalExpression.IfFalse));
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
var method = methodCallExpression.Method;
if (!UseOldBehavior31552
&& method.DeclaringType == typeof(EF)
&& method.Name == nameof(EF.Constant))
{
// If this is a call to EF.Constant(), then examine its operand. If the operand isn't evaluatable (i.e. contains a reference
// to a database table), throw immediately.
// Otherwise, evaluate the operand as a constant and return that.
var operand = methodCallExpression.Arguments[0];
if (!_evaluatableExpressions.TryGetValue(operand, out _))
{
throw new InvalidOperationException(CoreStrings.EFConstantWithNonEvaluableArgument);
}
return Evaluate(operand, generateParameter: false);
}
// .NET 10 made changes to overload resolution to prefer Span-based overloads when those exist ("first-class spans").
// Unfortunately, the LINQ interpreter does not support ref structs, so we rewrite e.g. MemoryExtensions.Contains to
// Enumerable.Contains here. See https://github.com/dotnet/runtime/issues/109757.
if (method.DeclaringType == typeof(MemoryExtensions) && !UseOldBehavior35100)
{
switch (method.Name)
{
case nameof(MemoryExtensions.Contains)
when UseOldBehavior37176
&& methodCallExpression.Arguments is [var arg0, var arg1]
&& TryUnwrapSpanImplicitCast(arg0, out var unwrappedArg0):
{
return Visit(
Expression.Call(
EnumerableMethods.Contains.MakeGenericMethod(method.GetGenericArguments()[0]),
unwrappedArg0, arg1));
}
// In .NET 10, MemoryExtensions.Contains has an overload that accepts a third, optional comparer, in addition to the older
// overload that accepts two parameters only.
case nameof(MemoryExtensions.Contains)
when !UseOldBehavior37176
&& methodCallExpression.Arguments is [var spanArg, var valueArg, ..]
&& (methodCallExpression.Arguments.Count is 2
|| methodCallExpression.Arguments.Count is 3
&& methodCallExpression.Arguments[2] is ConstantExpression { Value: null })
&& TryUnwrapSpanImplicitCast(spanArg, out var unwrappedSpanArg):
{
return Visit(
Expression.Call(
EnumerableMethods.Contains.MakeGenericMethod(method.GetGenericArguments()[0]),
unwrappedSpanArg, valueArg));
}
case nameof(MemoryExtensions.SequenceEqual)
when methodCallExpression.Arguments is [var arg0, var arg1]
&& TryUnwrapSpanImplicitCast(arg0, out var unwrappedArg0)
&& TryUnwrapSpanImplicitCast(arg1, out var unwrappedArg1):
return Visit(
Expression.Call(
EnumerableMethods.SequenceEqual.MakeGenericMethod(method.GetGenericArguments()[0]),
unwrappedArg0, unwrappedArg1));
}
static bool TryUnwrapSpanImplicitCast(Expression expression, [NotNullWhen(true)] out Expression? result)
{
switch (expression)
{
// With newer versions of the SDK, the implicit cast is represented as a MethodCallExpression;
// with older versions, it's a Convert node.
case MethodCallExpression
{
Method: { Name: "op_Implicit", DeclaringType: { IsGenericType: true } implicitCastDeclaringType },
Arguments: [var unwrapped]
} when implicitCastDeclaringType.GetGenericTypeDefinition() is var genericTypeDefinition
&& (genericTypeDefinition == typeof(Span<>) || genericTypeDefinition == typeof(ReadOnlySpan<>)):
{
result = unwrapped;
return true;
}
case UnaryExpression
{
NodeType: ExpressionType.Convert,
Operand: var unwrapped,
Type: { IsGenericType: true } convertType
} when !UseOldBehavior37176 && convertType.GetGenericTypeDefinition() is var genericTypeDefinition
&& (genericTypeDefinition == typeof(Span<>) || genericTypeDefinition == typeof(ReadOnlySpan<>)):
{
result = unwrapped;
return true;
}
default:
result = null;
return false;
}
}
}
return base.VisitMethodCall(methodCallExpression);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitBinary(BinaryExpression binaryExpression)
{
switch (binaryExpression.NodeType)
{
case ExpressionType.Coalesce:
{
var newLeftExpression = TryGetConstantValue(binaryExpression.Left) ?? Visit(binaryExpression.Left);
if (newLeftExpression is ConstantExpression constantLeftExpression)
{
return constantLeftExpression.Value == null
? Visit(binaryExpression.Right)
: newLeftExpression;
}
return binaryExpression.Update(
newLeftExpression,
binaryExpression.Conversion,
Visit(binaryExpression.Right));
}
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
{
var newLeftExpression = TryGetConstantValue(binaryExpression.Left) ?? Visit(binaryExpression.Left);
if (ShortCircuitLogicalExpression(newLeftExpression, binaryExpression.NodeType))
{
return newLeftExpression;
}
var newRightExpression = TryGetConstantValue(binaryExpression.Right) ?? Visit(binaryExpression.Right);
return ShortCircuitLogicalExpression(newRightExpression, binaryExpression.NodeType)
? newRightExpression
: binaryExpression.Update(newLeftExpression, binaryExpression.Conversion, newRightExpression);
}
default:
return base.VisitBinary(binaryExpression);
}
}
private Expression? TryGetConstantValue(Expression expression)
{
if (_evaluatableExpressions.ContainsKey(expression))
{
var value = GetValue(expression, out _);
if (value is bool)
{
return Expression.Constant(value, typeof(bool));
}
}
return null;
}
private static bool ShortCircuitLogicalExpression(Expression expression, ExpressionType nodeType)
=> expression is ConstantExpression { Value: bool constantValue }
&& ((constantValue && nodeType == ExpressionType.OrElse)
|| (!constantValue && nodeType == ExpressionType.AndAlso));
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitExtension(Expression extensionExpression)
{
if (extensionExpression is QueryRootExpression queryRootExpression)
{
var queryProvider = queryRootExpression.QueryProvider;
if (_currentQueryProvider == null)
{
_currentQueryProvider = queryProvider;
}
else if (!ReferenceEquals(queryProvider, _currentQueryProvider))
{
throw new InvalidOperationException(CoreStrings.ErrorInvalidQueryable);
}
// Visit after detaching query provider since custom query roots can have additional components
extensionExpression = queryRootExpression.DetachQueryProvider();
}
return base.VisitExtension(extensionExpression);
}
private static Expression GenerateConstantExpression(object? value, Type returnType)
{
var constantExpression = Expression.Constant(value, value?.GetType() ?? returnType);
return constantExpression.Type != returnType
? Expression.Convert(constantExpression, returnType)
: constantExpression;
}
private Expression Evaluate(Expression expression, bool generateParameter)
{
object? parameterValue;
string? parameterName;
if (_evaluatedValues.TryGetValue(expression, out var cachedValue))
{
// The _generateContextAccessors condition allows us to reuse parameter expressions evaluated in query filters.
// In principle, _generateContextAccessors is orthogonal to query filters, but in practice it is only used in the
// nav expansion query filters (and defining query). If this changes in future, they would need to be decoupled.
var existingExpression = generateParameter || _generateContextAccessors
? cachedValue.Parameter
: cachedValue.Constant;
if (existingExpression != null)
{
return existingExpression;
}
parameterValue = cachedValue.Value;
parameterName = cachedValue.CandidateParameterName;
}
else
{
parameterValue = GetValue(expression, out parameterName);
cachedValue = new EvaluatedValues { CandidateParameterName = parameterName, Value = parameterValue };
_evaluatedValues[expression] = cachedValue;
}
if (parameterValue is IQueryable innerQueryable)
{
return ExtractParameters(innerQueryable.Expression, clearEvaluatedValues: false);
}
if (parameterName?.StartsWith(QueryFilterPrefix, StringComparison.Ordinal) != true)
{
if (parameterValue is Expression innerExpression)
{
return ExtractParameters(innerExpression, clearEvaluatedValues: false);
}
if (!generateParameter)
{
var constantValue = GenerateConstantExpression(parameterValue, expression.Type);
cachedValue.Constant = constantValue;
return constantValue;
}
}
parameterName ??= "p";
if (string.Equals(QueryFilterPrefix, parameterName, StringComparison.Ordinal))
{
parameterName = QueryFilterPrefix + "__p";
}
var compilerPrefixIndex
= parameterName.LastIndexOf(">", StringComparison.Ordinal);
if (compilerPrefixIndex != -1)
{
parameterName = parameterName[(compilerPrefixIndex + 1)..];
}
parameterName
= QueryCompilationContext.QueryParameterPrefix
+ parameterName
+ "_"
+ _parameterValues.ParameterValues.Count;
_parameterValues.AddParameter(parameterName, parameterValue);
var parameter = Expression.Parameter(expression.Type, parameterName);
cachedValue.Parameter = parameter;
return parameter;
}
private sealed class ContextParameterReplacingExpressionVisitor : ExpressionVisitor
{
private readonly Type _contextType;
public ContextParameterReplacingExpressionVisitor(Type contextType)
{
ContextParameterExpression = Expression.Parameter(contextType, "context");
_contextType = contextType;
}
public ParameterExpression ContextParameterExpression { get; }
[return: NotNullIfNotNull("expression")]
public override Expression? Visit(Expression? expression)
=> expression?.Type != typeof(object)
&& expression?.Type.IsAssignableFrom(_contextType) == true
? ContextParameterExpression
: base.Visit(expression);
}
private static Expression RemoveConvert(Expression expression)
{
if (expression is UnaryExpression unaryExpression
&& expression.NodeType is ExpressionType.Convert or ExpressionType.ConvertChecked)
{
return RemoveConvert(unaryExpression.Operand);
}
return expression;
}
private object? GetValue(Expression? expression, out string? parameterName)
{
parameterName = null;
if (expression == null)
{
return null;
}
if (_generateContextAccessors)
{
var newExpression = _contextParameterReplacingExpressionVisitor.Visit(expression);
if (newExpression != expression)
{
if (newExpression.Type is IQueryable)
{
return newExpression;
}
parameterName = QueryFilterPrefix
+ (RemoveConvert(expression) is MemberExpression memberExpression
? ("__" + memberExpression.Member.Name)
: "");
return Expression.Lambda(
newExpression,
_contextParameterReplacingExpressionVisitor.ContextParameterExpression);
}
}
switch (expression)
{
case MemberExpression memberExpression:
var instanceValue = GetValue(memberExpression.Expression, out parameterName);
try
{
switch (memberExpression.Member)
{
case FieldInfo fieldInfo:
parameterName = (parameterName != null ? parameterName + "_" : "") + fieldInfo.Name;
return fieldInfo.GetValue(instanceValue);
case PropertyInfo propertyInfo:
parameterName = (parameterName != null ? parameterName + "_" : "") + propertyInfo.Name;
return propertyInfo.GetValue(instanceValue);
}
}
catch
{
// Try again when we compile the delegate
}
break;
case ConstantExpression constantExpression:
return constantExpression.Value;
case MethodCallExpression methodCallExpression:
parameterName = methodCallExpression.Method.Name;
break;
case UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression
when (unaryExpression.Type.UnwrapNullableType() == unaryExpression.Operand.Type):
return GetValue(unaryExpression.Operand, out parameterName);
}
try
{
return Expression.Lambda<Func<object>>(
Expression.Convert(expression, typeof(object)))
.Compile(preferInterpretation: true)
.Invoke();
}
catch (Exception exception)
{
throw new InvalidOperationException(
_logger.ShouldLogSensitiveData()
? CoreStrings.ExpressionParameterizationExceptionSensitive(expression)
: CoreStrings.ExpressionParameterizationException,
exception);
}
}
private sealed class EvaluatableExpressionFindingExpressionVisitor : ExpressionVisitor
{
private readonly IEvaluatableExpressionFilter _evaluatableExpressionFilter;
private readonly ISet<ParameterExpression> _allowedParameters = new HashSet<ParameterExpression>();
private readonly IModel _model;
private readonly bool _parameterize;
private bool _evaluatable;
private bool _containsClosure;
private bool _inLambda;
private IDictionary<Expression, bool> _evaluatableExpressions;
public EvaluatableExpressionFindingExpressionVisitor(
IEvaluatableExpressionFilter evaluatableExpressionFilter,
IModel model,
bool parameterize)
{
_evaluatableExpressionFilter = evaluatableExpressionFilter;
_model = model;
_parameterize = parameterize;
// The entry method will take care of populating this field always. So accesses should be safe.
_evaluatableExpressions = null!;
}
public IDictionary<Expression, bool> Find(Expression expression)
{
_evaluatable = true;
_containsClosure = false;
_inLambda = false;
_evaluatableExpressions = new Dictionary<Expression, bool>();
_allowedParameters.Clear();
Visit(expression);
return _evaluatableExpressions;
}
[return: NotNullIfNotNull("expression")]
public override Expression? Visit(Expression? expression)
{
if (expression == null)
{
return base.Visit(expression);
}
var parentEvaluatable = _evaluatable;
var parentContainsClosure = _containsClosure;
_evaluatable = IsEvaluatableNodeType(expression, out var preferNoEvaluation)
// Extension point to disable funcletization
&& _evaluatableExpressionFilter.IsEvaluatableExpression(expression, _model)
// Don't evaluate QueryableMethods if in compiled query
&& (_parameterize || !IsQueryableMethod(expression));
_containsClosure = false;
base.Visit(expression);
if (_evaluatable && !preferNoEvaluation)
{
// Force parameterization when not in lambda
_evaluatableExpressions[expression] = _containsClosure || !_inLambda;
}
_evaluatable = parentEvaluatable && _evaluatable;
_containsClosure = parentContainsClosure || _containsClosure;
return expression;
}
protected override Expression VisitLambda<T>(Expression<T> lambdaExpression)
{
var oldInLambda = _inLambda;
_inLambda = true;
// Note: Don't skip visiting parameter here.
// SelectMany does not use parameter in lambda but we should still block it from evaluating
base.VisitLambda(lambdaExpression);
_inLambda = oldInLambda;
return lambdaExpression;
}
protected override Expression VisitMemberInit(MemberInitExpression memberInitExpression)
{
Visit(memberInitExpression.Bindings, VisitMemberBinding);
// Cannot make parameter for NewExpression if Bindings cannot be evaluated
// but we still need to visit inside of it.
var bindingsEvaluatable = _evaluatable;
Visit(memberInitExpression.NewExpression);
if (!bindingsEvaluatable)
{
_evaluatableExpressions.Remove(memberInitExpression.NewExpression);
}
return memberInitExpression;
}
protected override Expression VisitListInit(ListInitExpression listInitExpression)
{
Visit(listInitExpression.Initializers, VisitElementInit);
// Cannot make parameter for NewExpression if Initializers cannot be evaluated
// but we still need to visit inside of it.
var initializersEvaluatable = _evaluatable;
Visit(listInitExpression.NewExpression);
if (!initializersEvaluatable)
{
_evaluatableExpressions.Remove(listInitExpression.NewExpression);
}
return listInitExpression;
}
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
Visit(methodCallExpression.Object);
var parameterInfos = methodCallExpression.Method.GetParameters();
for (var i = 0; i < methodCallExpression.Arguments.Count; i++)
{
if (i == 1
&& _evaluatableExpressions.ContainsKey(methodCallExpression.Arguments[0])
&& methodCallExpression.Method.DeclaringType == typeof(Enumerable)
&& methodCallExpression.Method.Name == nameof(Enumerable.Select)
&& methodCallExpression.Arguments[1] is LambdaExpression lambdaExpression)
{
// Allow evaluation Enumerable.Select operation
foreach (var parameter in lambdaExpression.Parameters)
{
_allowedParameters.Add(parameter);
}
}
Visit(methodCallExpression.Arguments[i]);
if (_evaluatableExpressions.ContainsKey(methodCallExpression.Arguments[i])
&& (parameterInfos[i].GetCustomAttribute<NotParameterizedAttribute>() != null
|| _model.IsIndexerMethod(methodCallExpression.Method)))
{
_evaluatableExpressions[methodCallExpression.Arguments[i]] = false;
}
}
return methodCallExpression;
}
protected override Expression VisitMember(MemberExpression memberExpression)
{
_containsClosure = memberExpression.Expression != null
|| !(memberExpression.Member is FieldInfo { IsInitOnly: true });
return base.VisitMember(memberExpression);
}
protected override Expression VisitParameter(ParameterExpression parameterExpression)
{
_evaluatable = _allowedParameters.Contains(parameterExpression);
return base.VisitParameter(parameterExpression);
}
protected override Expression VisitConstant(ConstantExpression constantExpression)
{
_evaluatable = !(constantExpression.Value is IQueryable);
#pragma warning disable RCS1096 // Use bitwise operation instead of calling 'HasFlag'.
_containsClosure
= (constantExpression.Type.Attributes.HasFlag(TypeAttributes.NestedPrivate)
&& Attribute.IsDefined(constantExpression.Type, typeof(CompilerGeneratedAttribute), inherit: true)) // Closure
|| constantExpression.Type == typeof(ValueBuffer); // Find method
#pragma warning restore RCS1096 // Use bitwise operation instead of calling 'HasFlag'.
return base.VisitConstant(constantExpression);
}
private static bool IsEvaluatableNodeType(Expression expression, out bool preferNoEvaluation)
{
switch (expression.NodeType)
{
case ExpressionType.NewArrayInit:
preferNoEvaluation = true;
return true;
case ExpressionType.Extension:
preferNoEvaluation = false;
return expression.CanReduce && IsEvaluatableNodeType(expression.ReduceAndCheck(), out preferNoEvaluation);
// Identify a call to EF.Constant(), and flag that as non-evaluable.
// This is important to prevent a larger subtree containing EF.Constant from being evaluated, i.e. to make sure that
// the EF.Function argument is present in the tree as its own, constant node.
case ExpressionType.Call
when !UseOldBehavior31552 && expression is MethodCallExpression { Method: var method }
&& method.DeclaringType == typeof(EF)
&& method.Name == nameof(EF.Constant):
preferNoEvaluation = true;
return false;
default:
preferNoEvaluation = false;
return true;
}
}
private static bool IsQueryableMethod(Expression expression)
=> expression is MethodCallExpression methodCallExpression
&& methodCallExpression.Method.DeclaringType == typeof(Queryable);
}
private sealed class EvaluatedValues
{
public string? CandidateParameterName { get; init; }
public object? Value { get; init; }
public Expression? Constant { get; set; }
public Expression? Parameter { get; set; }
}
}