-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathExpressionTreeFuncletizer.cs
2340 lines (1990 loc) · 110 KB
/
ExpressionTreeFuncletizer.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using static System.Linq.Expressions.Expression;
using ElementInit = System.Linq.Expressions.ElementInit;
namespace Microsoft.EntityFrameworkCore.Query.Internal;
/// <summary>
/// This visitor identifies subtrees in the query which can be evaluated client-side (i.e. no reference to server-side resources),
/// and evaluates those subtrees, integrating the result either as a constant (if the subtree contained no captured closure variables),
/// or as parameters.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public class ExpressionTreeFuncletizer : ExpressionVisitor
{
// The general algorithm here is the following.
// 1. First, for each node type, visit that node's children and get their states (evaluatable, contains evaluatable, no evaluatable).
// 2. Calculate the parent node's aggregate state from its children; a container node whose children are all evaluatable is itself
// evaluatable, etc.
// 3. If the parent node is evaluatable (because all its children are), simply bubble that up - nothing more to do
// 4. If the parent node isn't evaluatable but contains an evaluatable child, that child is an evaluatable root for its fragment.
// Evaluate it, making it either into a parameter (if it contains any captured variables), or into a constant (if not).
// 5. If we're in path extraction mode (precompiled queries), build a path back up from the evaluatable roots to the query root; this
// is what later gets used to generate code to evaluate and extract those fragments as parameters. If we're in regular parameter
// parameter extraction (not precompilation), don't do this (not needed) and just return "not evaluatable".
/// <summary>
/// Indicates whether we're calculating the paths to all parameterized evaluatable roots (precompilation mode), or doing regular,
/// non-precompiled parameter extraction.
/// </summary>
private bool _calculatingPath;
/// <summary>
/// Indicates whether performing parameter extraction on a precompiled query.
/// </summary>
private bool _precompiledQuery;
/// <summary>
/// Indicates whether we should parameterize. Is false in compiled query mode, as well as when we're handling query filters from
/// NavigationExpandingExpressionVisitor.
/// </summary>
private bool _parameterize;
/// <summary>
/// Indicates whether we're currently within a lambda. When not in a lambda, we evaluate evaluatables as constants even if they
/// don't contains a captured variable (Skip/Take case).
/// </summary>
private bool _inLambda;
/// <summary>
/// A provider-facing extensibility hook to allow preventing certain expression nodes from being evaluated (typically specific
/// methods).
/// </summary>
private readonly IEvaluatableExpressionFilter _evaluatableExpressionFilter;
/// <summary>
/// <see cref="ParameterExpression" /> is generally considered as non-evaluatable, since it represents a lambda parameter and we
/// don't evaluate lambdas. The one exception is a Select operator over something evaluatable (e.g. a parameterized list) - this
/// does need to get evaluated. This list contains <see cref="ParameterExpression" /> instances for that case, to allow
/// evaluatability.
/// </summary>
private readonly HashSet<ParameterExpression> _evaluatableParameters = new();
/// <summary>
/// A cache of tree fragments that have already been parameterized, along with their parameter. This allows us to reuse the same
/// query parameter twice when the same captured variable is referenced in the query.
/// </summary>
private readonly Dictionary<Expression, QueryParameterExpression> _parameterizedValues = new(ExpressionEqualityComparer.Instance);
/// <summary>
/// A set of the names of parameters that have already been created. Used to ensure different parameters have unique names.
/// </summary>
private readonly HashSet<string> _parameterNames = new();
/// <summary>
/// Used only when evaluating arbitrary QueryRootExpressions (specifically SqlQueryRootExpression), to force any evaluatable nested
/// expressions to get evaluated as roots, since the query root itself is never evaluatable.
/// </summary>
private bool _evaluateRoot;
/// <summary>
/// Enabled only when funcletization is invoked on query filters from within NavigationExpandingExpressionVisitor. Causes special
/// handling for DbContext when it's referenced from within the query filter (e.g. for the tenant ID).
/// </summary>
private readonly bool _generateContextAccessors;
private IQueryProvider? _currentQueryProvider;
private State _state;
private IParameterValues _parameterValues = null!;
private readonly IModel _model;
private readonly ContextParameterReplacer _contextParameterReplacer;
private readonly IDiagnosticsLogger<DbLoggerCategory.Query> _logger;
private static readonly MethodInfo ReadOnlyCollectionIndexerGetter = typeof(ReadOnlyCollection<Expression>).GetProperties()
.Single(p => p.GetIndexParameters() is { Length: 1 } indexParameters && indexParameters[0].ParameterType == typeof(int)).GetMethod!;
private static readonly MethodInfo ReadOnlyElementInitCollectionIndexerGetter = typeof(ReadOnlyCollection<ElementInit>)
.GetProperties()
.Single(p => p.GetIndexParameters() is { Length: 1 } indexParameters && indexParameters[0].ParameterType == typeof(int)).GetMethod!;
private static readonly MethodInfo ReadOnlyMemberBindingCollectionIndexerGetter = typeof(ReadOnlyCollection<MemberBinding>)
.GetProperties()
.Single(p => p.GetIndexParameters() is { Length: 1 } indexParameters && indexParameters[0].ParameterType == typeof(int)).GetMethod!;
private static readonly PropertyInfo MemberAssignmentExpressionProperty =
typeof(MemberAssignment).GetProperty(nameof(MemberAssignment.Expression))!;
private static readonly ArrayPool<State> StateArrayPool = ArrayPool<State>.Shared;
private const string QueryFilterPrefix = "ef_filter";
/// <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 ExpressionTreeFuncletizer(
IModel model,
IEvaluatableExpressionFilter evaluatableExpressionFilter,
Type contextType,
bool generateContextAccessors,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
_model = model;
_evaluatableExpressionFilter = evaluatableExpressionFilter;
_generateContextAccessors = generateContextAccessors;
_contextParameterReplacer = _generateContextAccessors
? new ContextParameterReplacer(contextType)
: null!;
_logger = logger;
}
/// <summary>
/// Processes an expression tree, extracting parameters and evaluating evaluatable fragments as part of the pass.
/// Used for regular query execution (neither compiled nor pre-compiled).
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public virtual Expression ExtractParameters(
Expression expression,
IParameterValues parameterValues,
bool parameterize,
bool clearParameterizedValues)
=> ExtractParameters(expression, parameterValues, parameterize, clearParameterizedValues, precompiledQuery: false);
/// <summary>
/// Processes an expression tree, extracting parameters and evaluating evaluatable fragments as part of the pass.
/// Used for regular query execution (neither compiled nor pre-compiled).
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
[Experimental(EFDiagnostics.PrecompiledQueryExperimental)]
public virtual Expression ExtractParameters(
Expression expression,
IParameterValues parameterValues,
bool parameterize,
bool clearParameterizedValues,
bool precompiledQuery)
{
Reset(clearParameterizedValues);
_parameterValues = parameterValues;
_parameterize = parameterize;
_calculatingPath = false;
_precompiledQuery = precompiledQuery;
var root = Visit(expression, out var state);
Check.DebugAssert(!state.ContainsEvaluatable, "In parameter extraction mode, end state should not contain evaluatable");
// If the top-most node in the tree is evaluatable, evaluate it.
if (state.IsEvaluatable)
{
root = ProcessEvaluatableRoot(root, ref state);
}
return root;
}
/// <summary>
/// Resets the funcletizer in preparation for multiple path calculations (i.e. for the same query). After this is called,
/// <see cref="CalculatePathsToEvaluatableRoots(MethodCallExpression, int)" /> can be called multiple times, preserving state
/// between calls.
/// </summary>
[Experimental(EFDiagnostics.PrecompiledQueryExperimental)]
public virtual void ResetPathCalculation()
{
Reset();
_calculatingPath = true;
_parameterize = true;
// In precompilation mode we don't actually extract parameter values; but we do need to generate the parameter names, using the
// same logic (and via the same code) used in parameter extraction, and that logic requires _parameterValues.
_parameterValues = new DummyParameterValues();
}
/// <summary>
/// Processes an expression tree, locates references to captured variables and returns information on how to extract them from
/// expression trees with the same shape. Used to generate C# code for query precompilation.
/// </summary>
/// <returns>A tree representing the path to each evaluatable root node in the tree.</returns>
/// <remarks>
/// 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.
/// </remarks>
[Experimental(EFDiagnostics.PrecompiledQueryExperimental)]
public virtual PathNode? CalculatePathsToEvaluatableRoots(MethodCallExpression linqOperatorMethodCall, int argumentIndex)
{
var argument = linqOperatorMethodCall.Arguments[argumentIndex];
if (argument is UnaryExpression { NodeType: ExpressionType.Quote } quote)
{
argument = quote.Operand;
}
var root = Visit(argument, out var state);
// If the top-most node in the tree is evaluatable, that means we have a non-lambda parameter to the LINQ operator (e.g. Skip/Take).
// We make sure to return a path containing the argument; note that since we're not in a lambda, the argument will always be
// parameterized since we're not inside a lambda (e.g. Skip/Take), except for [NotParameterized].
if (state.IsEvaluatable
&& IsParameterParameterizable(linqOperatorMethodCall.Method, linqOperatorMethodCall.Method.GetParameters()[argumentIndex]))
{
_ = Evaluate(root, out var parameterName);
state = new State
{
StateType = StateType.ContainsEvaluatable,
Path = new PathNode
{
ExpressionType = state.ExpressionType!,
ParameterName = parameterName,
Children = Array.Empty<PathNode>()
}
};
}
return state.Path;
}
/// <summary>
/// Processes an expression tree, locates references to captured variables and returns information on how to extract them from
/// expression trees with the same shape. Used to generate C# code for query precompilation.
/// </summary>
/// <returns>A tree representing the path to each evaluatable root node in the tree.</returns>
/// <remarks>
/// 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.
/// </remarks>
[Experimental(EFDiagnostics.PrecompiledQueryExperimental)]
public virtual PathNode? CalculatePathsToEvaluatableRoots(Expression expression)
{
var root = Visit(expression, out var state);
// If the top-most node in the tree is evaluatable, that means we have a non-lambda parameter to the LINQ operator (e.g. Skip/Take).
// We make sure to return a path containing the argument; note that since we're not in a lambda, the argument will always be
// parameterized since we're not inside a lambda (e.g. Skip/Take), except for [NotParameterized].
if (state.IsEvaluatable)
{
_ = Evaluate(root, out var parameterName);
state = new State
{
StateType = StateType.ContainsEvaluatable,
Path = new PathNode
{
ExpressionType = state.ExpressionType!,
ParameterName = parameterName,
Children = Array.Empty<PathNode>()
}
};
}
return state.Path;
}
private void Reset(bool clearParameterizedValues = true)
{
_inLambda = false;
_currentQueryProvider = null;
_evaluateRoot = false;
_evaluatableParameters.Clear();
if (clearParameterizedValues)
{
_parameterizedValues.Clear();
_parameterNames.Clear();
}
}
[return: NotNullIfNotNull(nameof(expression))]
private Expression? Visit(Expression? expression, out State state)
{
_state = default;
var result = base.Visit(expression);
state = _state;
return result;
}
/// <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(nameof(expression))]
public override Expression? Visit(Expression? expression)
{
_state = default;
if (_evaluateRoot)
{
// This path is only called from VisitExtension for query roots, as a way of evaluating expressions inside query roots
// (i.e. SqlQueryRootExpression.Arguments).
_evaluateRoot = false;
var result = base.Visit(expression);
_evaluateRoot = true;
if (_state.IsEvaluatable)
{
result = ProcessEvaluatableRoot(result, ref _state);
// TODO: Test this scenario in path calculation mode (probably need to handle children path?)
}
return result;
}
return base.Visit(expression);
}
#region Visitation implementations
/// <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 binary)
{
var left = Visit(binary.Left, out var leftState);
// Perform short-circuiting checks to avoid evaluating the right side if not necessary
object? leftValue = null;
if (leftState.IsEvaluatable)
{
switch (binary.NodeType)
{
case ExpressionType.Coalesce:
leftValue = Evaluate(left);
Expression returnValue;
switch (leftValue)
{
case null:
returnValue = Visit(binary.Right, out _state);
break;
case bool b:
_state = leftState with { StateType = StateType.EvaluatableWithoutCapturedVariable };
returnValue = Constant(b);
break;
default:
returnValue = left;
break;
}
return ConvertIfNeeded(returnValue, binary.Type);
case ExpressionType.OrElse or ExpressionType.AndAlso when Evaluate(left) is bool leftBoolValue:
{
left = Constant(leftBoolValue);
leftState = leftState with { StateType = StateType.EvaluatableWithoutCapturedVariable };
if (leftBoolValue && binary.NodeType is ExpressionType.OrElse
|| !leftBoolValue && binary.NodeType is ExpressionType.AndAlso)
{
_state = leftState;
return left;
}
binary = binary.Update(left, binary.Conversion, binary.Right);
break;
}
}
}
var right = Visit(binary.Right, out var rightState);
if (binary.NodeType is ExpressionType.AndAlso or ExpressionType.OrElse)
{
if (leftState.IsEvaluatable && leftValue is bool leftBoolValue)
{
switch ((leftConstant: leftBoolValue, binary.NodeType))
{
case (true, ExpressionType.AndAlso) or (false, ExpressionType.OrElse):
_state = rightState;
return right;
case (true, ExpressionType.OrElse) or (false, ExpressionType.AndAlso):
throw new UnreachableException(); // Already handled above before visiting the right side
}
}
if (rightState.IsEvaluatable && Evaluate(right) is bool rightBoolValue)
{
switch ((binary.NodeType, rightConstant: rightBoolValue))
{
case (ExpressionType.AndAlso, true) or (ExpressionType.OrElse, false):
_state = leftState;
return left;
case (ExpressionType.OrElse, true) or (ExpressionType.AndAlso, false):
_state = rightState with { StateType = StateType.EvaluatableWithoutCapturedVariable };
return Constant(rightBoolValue);
}
}
}
// We're done with simplification/short-circuiting checks specific to BinaryExpression.
var state = CombineStateTypes(leftState.StateType, rightState.StateType);
switch (state)
{
case StateType.NoEvaluatability:
_state = State.NoEvaluatability;
break;
case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown:
if (IsGenerallyEvaluatable(binary))
{
_state = State.CreateEvaluatable(typeof(BinaryExpression), state is StateType.EvaluatableWithCapturedVariable);
break;
}
goto case StateType.ContainsEvaluatable;
case StateType.ContainsEvaluatable:
if (leftState.IsEvaluatable)
{
left = ProcessEvaluatableRoot(left, ref leftState);
}
if (rightState.IsEvaluatable)
{
right = ProcessEvaluatableRoot(right, ref rightState);
}
List<PathNode>? children = null;
if (_calculatingPath)
{
if (leftState.ContainsEvaluatable)
{
children =
[
leftState.Path! with { PathFromParent = static e => Property(e, nameof(BinaryExpression.Left)) }
];
}
if (rightState.ContainsEvaluatable)
{
children ??= new List<PathNode>();
children.Add(rightState.Path! with { PathFromParent = static e => Property(e, nameof(BinaryExpression.Right)) });
}
}
_state = children is null
? State.NoEvaluatability
: State.CreateContainsEvaluatable(typeof(BinaryExpression), children);
break;
default:
throw new UnreachableException();
}
return binary.Update(left, binary.Conversion, right);
}
/// <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 conditional)
{
var test = Visit(conditional.Test, out var testState);
// If the test evaluates, simplify the conditional away by bubbling up the leg that remains
if (testState.IsEvaluatable && Evaluate(test) is bool testBoolValue)
{
return ConvertIfNeeded(
testBoolValue
? Visit(conditional.IfTrue, out _state)
: Visit(conditional.IfFalse, out _state),
conditional.Type);
}
var ifTrue = Visit(conditional.IfTrue, out var ifTrueState);
var ifFalse = Visit(conditional.IfFalse, out var ifFalseState);
var state = CombineStateTypes(testState.StateType, CombineStateTypes(ifTrueState.StateType, ifFalseState.StateType));
switch (state)
{
case StateType.NoEvaluatability:
_state = State.NoEvaluatability;
break;
// If all three children are evaluatable, so is this conditional expression; simply bubble up, we're part of an evaluatable
// fragment that will get evaluated somewhere above.
case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown:
if (IsGenerallyEvaluatable(conditional))
{
_state = State.CreateEvaluatable(typeof(ConditionalExpression), state is StateType.EvaluatableWithCapturedVariable);
break;
}
goto case StateType.ContainsEvaluatable;
case StateType.ContainsEvaluatable:
if (testState.IsEvaluatable)
{
test = ProcessEvaluatableRoot(test, ref testState);
}
if (ifTrueState.IsEvaluatable)
{
ifTrue = ProcessEvaluatableRoot(ifTrue, ref ifTrueState);
}
if (ifFalseState.IsEvaluatable)
{
ifFalse = ProcessEvaluatableRoot(ifFalse, ref ifFalseState);
}
List<PathNode>? children = null;
if (_calculatingPath)
{
if (testState.ContainsEvaluatable)
{
children ??= new List<PathNode>();
children.Add(
testState.Path! with { PathFromParent = static e => Property(e, nameof(ConditionalExpression.Test)) });
}
if (ifTrueState.ContainsEvaluatable)
{
children ??= new List<PathNode>();
children.Add(
ifTrueState.Path! with { PathFromParent = static e => Property(e, nameof(ConditionalExpression.IfTrue)) });
}
if (ifFalseState.ContainsEvaluatable)
{
children ??= new List<PathNode>();
children.Add(
ifFalseState.Path! with { PathFromParent = static e => Property(e, nameof(ConditionalExpression.IfFalse)) });
}
}
_state = children is null
? State.NoEvaluatability
: State.CreateContainsEvaluatable(typeof(ConditionalExpression), children);
break;
default:
throw new UnreachableException();
}
return conditional.Update(test, ifTrue, 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 VisitConstant(ConstantExpression constant)
{
// Whether this constant represents a captured variable determines whether we'll evaluate it as a parameter (if yes) or as a
// constant (if no).
var isCapturedVariable =
// This identifies compiler-generated closure types which contain captured variables.
(constant.Type.Attributes.HasFlag(TypeAttributes.NestedPrivate)
&& Attribute.IsDefined(constant.Type, typeof(CompilerGeneratedAttribute), inherit: true))
// The following is for supporting the Find method (we should look into this and possibly clean it up).
|| constant.Type == typeof(ValueBuffer);
_state = constant.Value is IQueryable
? State.NoEvaluatability
: State.CreateEvaluatable(typeof(ConstantExpression), isCapturedVariable);
return constant;
}
/// <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 VisitDefault(DefaultExpression node)
{
_state = State.CreateEvaluatable(typeof(DefaultExpression), containsCapturedVariable: false);
return node;
}
/// <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 extension)
{
switch (extension)
{
case QueryRootExpression queryRoot:
{
var queryProvider = queryRoot.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
extension = queryRoot.DetachQueryProvider();
// The following is somewhat hacky. We're going to visit the query root's children via VisitChildren - this is primarily for
// FromSqlQueryRootExpression. Since the query root itself is never evaluatable, its children should all be handled as
// evaluatable roots - we set _evaluateRoot and do that in Visit.
// In addition, FromSqlQueryRootExpression's Arguments need to be a parameter rather than constant, so we set _inLambda to
// make that happen (quite hacky, but was done this way in the old ParameterExtractingEV as well). Think about a better way.
_evaluateRoot = true;
var parentInLambda = _inLambda;
_inLambda = false;
var visitedExtension = base.VisitExtension(extension);
_evaluateRoot = false;
_inLambda = parentInLambda;
_state = State.NoEvaluatability;
return visitedExtension;
}
// In regular queries, query parameters are represented as captured variables, i.e. member accesses over a ConstantExpression
// referencing the closure type (see VisitConstant).
// However, compiled queries work differently, and their query parameters are actual ParameterExpressions that correspond to the
// compiled query lambda parameters. These are replaced with QueryParameterExpression in CompiledQueryBase, so we need to handle
// those here.
case QueryParameterExpression queryParameter:
_state = State.NoEvaluatability;
return queryParameter;
}
return base.VisitExtension(extension);
}
/// <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 VisitInvocation(InvocationExpression invocation)
{
var expression = Visit(invocation.Expression, out var expressionState);
var state = expressionState.StateType;
var arguments = Visit(invocation.Arguments, ref state, out var argumentStates);
switch (state)
{
case StateType.NoEvaluatability:
_state = State.NoEvaluatability;
break;
case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown:
if (IsGenerallyEvaluatable(invocation))
{
_state = State.CreateEvaluatable(typeof(InvocationExpression), state is StateType.EvaluatableWithCapturedVariable);
break;
}
goto case StateType.ContainsEvaluatable;
case StateType.ContainsEvaluatable:
List<PathNode>? children = null;
if (expressionState.IsEvaluatable)
{
expression = ProcessEvaluatableRoot(expression, ref expressionState);
}
if (expressionState.ContainsEvaluatable && _calculatingPath)
{
children =
[
expressionState.Path! with { PathFromParent = static e => Property(e, nameof(InvocationExpression.Expression)) }
];
}
arguments = EvaluateList(
((IReadOnlyList<Expression>?)arguments) ?? invocation.Arguments,
argumentStates,
ref children,
static i => e =>
Call(
Property(e, nameof(InvocationExpression.Arguments)),
ReadOnlyCollectionIndexerGetter,
arguments: [Constant(i)]));
_state = children is null
? State.NoEvaluatability
: State.CreateContainsEvaluatable(typeof(InvocationExpression), children);
break;
default:
throw new UnreachableException();
}
StateArrayPool.Return(argumentStates);
return invocation.Update(expression, ((IReadOnlyList<Expression>?)arguments) ?? invocation.Arguments);
}
/// <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 VisitIndex(IndexExpression index)
{
var @object = Visit(index.Object, out var objectState);
var state = objectState.StateType;
var arguments = Visit(index.Arguments, ref state, out var argumentStates);
switch (state)
{
case StateType.NoEvaluatability:
_state = State.NoEvaluatability;
break;
case StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable or StateType.Unknown:
if (IsGenerallyEvaluatable(index))
{
_state = State.CreateEvaluatable(typeof(IndexExpression), state is StateType.EvaluatableWithCapturedVariable);
break;
}
goto case StateType.ContainsEvaluatable;
case StateType.ContainsEvaluatable:
List<PathNode>? children = null;
if (objectState.IsEvaluatable)
{
@object = ProcessEvaluatableRoot(@object, ref objectState);
}
if (objectState.ContainsEvaluatable && _calculatingPath)
{
children = [objectState.Path! with { PathFromParent = static e => Property(e, nameof(IndexExpression.Object)) }];
}
arguments = EvaluateList(
((IReadOnlyList<Expression>?)arguments) ?? index.Arguments,
argumentStates,
ref children,
static i => e =>
Call(
Property(e, nameof(IndexExpression.Arguments)),
ReadOnlyCollectionIndexerGetter,
arguments: [Constant(i)]));
_state = children is null
? State.NoEvaluatability
: State.CreateContainsEvaluatable(typeof(IndexExpression), children);
break;
default:
throw new UnreachableException();
}
StateArrayPool.Return(argumentStates);
// TODO: https://github.com/dotnet/runtime/issues/96626
return index.Update(@object!, ((IReadOnlyList<Expression>?)arguments) ?? index.Arguments);
}
/// <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 VisitLambda<T>(Expression<T> lambda)
{
var oldInLambda = _inLambda;
_inLambda = true;
var body = Visit(lambda.Body, out _state);
lambda = lambda.Update(body, lambda.Parameters);
if (_state.StateType is StateType.EvaluatableWithCapturedVariable or StateType.EvaluatableWithoutCapturedVariable)
{
// The lambda body is evaluatable. If all lambda parameters are also in the _allowedParameters set (this happens for
// Select() over an evaluatable source, see VisitMethodCall()), then the whole lambda is evaluatable. Otherwise, evaluate
// the body.
if (lambda.Parameters.All(parameter => _evaluatableParameters.Contains(parameter)))
{
_state = State.CreateEvaluatable(typeof(LambdaExpression), _state.ContainsCapturedVariable);
return lambda;
}
lambda = lambda.Update(ProcessEvaluatableRoot(lambda.Body, ref _state), lambda.Parameters);
}
if (_state.ContainsEvaluatable)
{
_state = State.CreateContainsEvaluatable(
typeof(LambdaExpression),
[_state.Path! with { PathFromParent = static e => Property(e, nameof(Expression<T>.Body)) }]);
}
_inLambda = oldInLambda;
return lambda;
}
/// <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 VisitMember(MemberExpression member)
{
// Static member access - notably required for EF.Functions, but also for various translations (DateTime.Now).
// Note that this is treated as a captured variable (so will be parameterized), unless the captured variable is init-only.
if (member.Expression is null)
{
_state = IsGenerallyEvaluatable(member)
? State.CreateEvaluatable(
typeof(MemberExpression),
containsCapturedVariable: member.Member is not FieldInfo { IsInitOnly: true })
: State.NoEvaluatability;
return member;
}
var expression = Visit(member.Expression, out _state);
if (_state.IsEvaluatable)
{
// If the query contains a captured variable that's a nested IQueryable, inline it into the main query.
// Otherwise, evaluation of a terminating operator up the call chain will cause us to execute the query and do another
// roundtrip.
// Note that we only do this when the MemberExpression is typed as IQueryable/IOrderedQueryable; this notably excludes
// DbSet captured variables integrated directly into the query, as that also evaluates e.g. context.Order in
// context.Order.FromSqlInterpolated(), which fails.
if (member.Type.IsConstructedGenericType
&& member.Type.GetGenericTypeDefinition() is var genericTypeDefinition
&& (genericTypeDefinition == typeof(IQueryable<>) || genericTypeDefinition == typeof(IOrderedQueryable<>))
&& Evaluate(member) is IQueryable queryable)
{
return Visit(queryable.Expression);
}
if (IsGenerallyEvaluatable(member))
{
// Note that any evaluatable MemberExpression is treated as a captured variable.
_state = State.CreateEvaluatable(typeof(MemberExpression), containsCapturedVariable: true);
return member.Update(expression);
}
expression = ProcessEvaluatableRoot(expression, ref _state);
}
if (_state.ContainsEvaluatable && _calculatingPath)
{
_state = State.CreateContainsEvaluatable(
typeof(MemberExpression),
[_state.Path! with { PathFromParent = static e => Property(e, nameof(MemberExpression.Expression)) }]);
}
return member.Update(expression);
}
/// <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 methodCall)
{
var method = methodCall.Method;
// Handle some special, well-known functions
// If this is a call to EF.Constant(), or EF.Parameter(), then examine the operand; if it isn't evaluatable (i.e. contains a
// reference to a database table), throw immediately. Otherwise, evaluate the operand (either as a constant or as a parameter) and
// return that.
if (method.DeclaringType == typeof(EF))
{
switch (method.Name)
{
case nameof(EF.Constant):
{
if (_calculatingPath)
{
throw new InvalidOperationException(CoreStrings.EFConstantNotSupportedInPrecompiledQueries);
}
var argument = Visit(methodCall.Arguments[0], out var argumentState);
if (!argumentState.IsEvaluatable)
{
throw new InvalidOperationException(CoreStrings.EFConstantWithNonEvaluatableArgument);
}
// Even EF.Constant will be parameter here.
// To have a query cache hit, the constantization will happen later in pipeline.
argumentState = argumentState with { StateType = StateType.EvaluatableWithCapturedVariable };
var evaluatedArgument = ProcessEvaluatableRoot(argument, ref argumentState);
_state = argumentState;
return Call(method, evaluatedArgument);
}
case nameof(EF.Parameter):
{
var argument = Visit(methodCall.Arguments[0], out var argumentState);
if (!argumentState.IsEvaluatable)
{
throw new InvalidOperationException(CoreStrings.EFParameterWithNonEvaluatableArgument);
}
argumentState = argumentState with { StateType = StateType.EvaluatableWithCapturedVariable };
var evaluatedArgument = ProcessEvaluatableRoot(argument, ref argumentState, forceEvaluation: true);
_state = argumentState;
return Call(method, evaluatedArgument);
}
}
}
// .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))
{
switch (method.Name)
{
case nameof(MemoryExtensions.Contains)
when methodCall.Arguments is [var arg0, var arg1] && TryUnwrapSpanImplicitCast(arg0, out var unwrappedArg0):
{
return Visit(
Call(
EnumerableMethods.Contains.MakeGenericMethod(methodCall.Method.GetGenericArguments()[0]),
unwrappedArg0, arg1));
}
case nameof(MemoryExtensions.SequenceEqual)
when methodCall.Arguments is [var arg0, var arg1]
&& TryUnwrapSpanImplicitCast(arg0, out var unwrappedArg0)
&& TryUnwrapSpanImplicitCast(arg1, out var unwrappedArg1):
return Visit(
Call(
EnumerableMethods.SequenceEqual.MakeGenericMethod(methodCall.Method.GetGenericArguments()[0]),
unwrappedArg0, unwrappedArg1));
}
static bool TryUnwrapSpanImplicitCast(Expression expression, [NotNullWhen(true)] out Expression? result)
{
if (expression is MethodCallExpression
{
Method: { Name: "op_Implicit", DeclaringType: { IsGenericType: true } implicitCastDeclaringType },