-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
CSharpToLinqTranslator.cs
1299 lines (1090 loc) · 64.3 KB
/
CSharpToLinqTranslator.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.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.EntityFrameworkCore.Internal;
using static System.Linq.Expressions.Expression;
namespace Microsoft.EntityFrameworkCore.Query.Internal;
/// <summary>
/// Translates a Roslyn syntax tree into a LINQ expression tree.
/// </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 CSharpToLinqTranslator : CSharpSyntaxVisitor<Expression>
{
private static readonly SymbolDisplayFormat QualifiedTypeNameSymbolDisplayFormat = new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces);
private Compilation? _compilation;
#pragma warning disable CS8618 // Uninitialized non-nullable fields. We check _compilation to make sure LoadCompilation was invoked.
private DbContext _userDbContext;
private Assembly? _additionalAssembly;
private INamedTypeSymbol _userDbContextSymbol;
private INamedTypeSymbol _formattableStringSymbol;
#pragma warning restore CS8618
private SemanticModel _semanticModel = null!;
private static MethodInfo? _stringConcatMethod;
private static MethodInfo? _stringFormatMethod;
private static MethodInfo? _formattableStringFactoryCreateMethod;
/// <summary>
/// Loads the given <see cref="Compilation" /> and prepares to translate queries using the given <see cref="DbContext" />.
/// </summary>
/// <param name="compilation">A <see cref="Compilation" /> containing the syntax nodes to be translated.</param>
/// <param name="userDbContext">An instance of the user's <see cref="DbContext" />.</param>
/// <param name="additionalAssembly">An optional additional assemblies to resolve CLR types from.</param>
/// <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 void Load(Compilation compilation, DbContext userDbContext, Assembly? additionalAssembly = null)
{
_compilation = compilation;
_userDbContext = userDbContext;
_additionalAssembly = additionalAssembly;
_userDbContextSymbol = GetTypeSymbolOrThrow(userDbContext.GetType().FullName!);
_formattableStringSymbol = GetTypeSymbolOrThrow("System.FormattableString");
INamedTypeSymbol GetTypeSymbolOrThrow(string fullyQualifiedMetadataName)
=> _compilation.GetTypeByMetadataName(fullyQualifiedMetadataName)
?? throw new InvalidOperationException("Could not find type symbol for: " + fullyQualifiedMetadataName);
}
private readonly Stack<ImmutableDictionary<string, ParameterExpression>> _parameterStack
= new(new[] { ImmutableDictionary<string, ParameterExpression>.Empty });
private readonly Dictionary<ISymbol, MemberExpression?> _capturedVariables = new(SymbolEqualityComparer.Default);
/// <summary>
/// Translates a Roslyn syntax tree into a LINQ expression tree.
/// </summary>
/// <param name="node">The Roslyn syntax node to be translated.</param>
/// <param name="semanticModel">
/// The <see cref="SemanticModel" /> for the Roslyn <see cref="SyntaxTree" /> of which <paramref name="node" /> is a part.
/// </param>
/// <returns>A LINQ expression tree translated from the provided <paramref name="node"/>.</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>
public virtual Expression Translate(SyntaxNode node, SemanticModel semanticModel)
{
if (_compilation is null)
{
throw new InvalidOperationException(DesignStrings.CompilationMustBeLoaded);
}
Check.DebugAssert(
ReferenceEquals(semanticModel.SyntaxTree, node.SyntaxTree),
"Provided semantic model doesn't match the provided syntax node");
_semanticModel = semanticModel;
// Perform data flow analysis to detect all captured data (closure parameters)
_capturedVariables.Clear();
foreach (var captured in _semanticModel.AnalyzeDataFlow(node).Captured)
{
_capturedVariables[captured] = null;
}
var result = Visit(node);
Debug.Assert(_parameterStack.Count == 1);
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("node")]
public override Expression? Visit(SyntaxNode? node)
=> base.Visit(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>
public override Expression VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax anonymousObjectCreation)
{
// Creating an actual anonymous object means creating a new type, which can only be done with Reflection.Emit.
// At least for EF's purposes, it doesn't matter, so we build a placeholder.
if (_semanticModel.GetSymbolInfo(anonymousObjectCreation).Symbol is not IMethodSymbol constructorSymbol)
{
throw new InvalidOperationException(
"Could not find symbol for anonymous object creation initializer: " + anonymousObjectCreation);
}
var anonymousType = ResolveType(constructorSymbol.ContainingType);
var parameters = constructorSymbol.Parameters.ToArray();
var parameterInfos = new ParameterInfo[parameters.Length];
var memberInfos = new MemberInfo[parameters.Length];
var arguments = new Expression[parameters.Length];
foreach (var initializer in anonymousObjectCreation.Initializers)
{
// If the initializer's name isn't explicitly specified, infer it from the initializer's expression like the compiler does
var name = initializer.NameEquals is not null
? initializer.NameEquals.Name.Identifier.Text
: initializer.Expression is MemberAccessExpressionSyntax memberAccess
? memberAccess.Name.Identifier.Text
: throw new InvalidOperationException(
$"AnonymousObjectCreation: unnamed initializer with non-MemberAccess expression: {initializer.Expression}");
var position = Array.FindIndex(parameters, p => p.Name == name);
var parameter = parameters[position];
var parameterType = ResolveType(parameter.Type) ?? throw new InvalidOperationException(
"Could not resolve type symbol for: " + parameter.Type);
parameterInfos[position] = new FakeParameterInfo(name, parameterType, position);
arguments[position] = Visit(initializer.Expression);
memberInfos[position] = anonymousType.GetProperty(parameter.Name)!;
}
return New(
new FakeConstructorInfo(anonymousType, parameterInfos),
arguments: arguments,
memberInfos);
}
/// <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 override Expression VisitArgument(ArgumentSyntax argument)
{
if (!argument.RefKindKeyword.IsKind(SyntaxKind.None))
{
throw new InvalidOperationException($"Argument with ref/out: {argument}");
}
return Visit(argument.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>
public override Expression VisitArrayCreationExpression(ArrayCreationExpressionSyntax arrayCreation)
{
if (_semanticModel.GetTypeInfo(arrayCreation).Type is not IArrayTypeSymbol arrayTypeSymbol)
{
throw new InvalidOperationException($"ArrayCreation: non-array type symbol: {arrayCreation}");
}
if (arrayTypeSymbol.Rank > 1)
{
throw new NotImplementedException($"ArrayCreation: multi-dimensional array: {arrayCreation}");
}
var elementType = ResolveType(arrayTypeSymbol.ElementType);
Check.DebugAssert(elementType is not null, "elementType is not null");
return arrayCreation.Initializer is null
? NewArrayBounds(elementType, Visit(arrayCreation.Type.RankSpecifiers[0].Sizes[0]))
: NewArrayInit(elementType, arrayCreation.Initializer.Expressions.Select(e => Visit(e)));
}
/// <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 override Expression VisitBinaryExpression(BinaryExpressionSyntax binary)
{
var left = Visit(binary.Left);
var right = Visit(binary.Right);
// https://learn.microsoft.com/dotnet/api/Microsoft.CodeAnalysis.CSharp.Syntax.BinaryExpressionSyntax
return binary.Kind() switch
{
// String concatenation
SyntaxKind.AddExpression
when left.Type == typeof(string) && right.Type == typeof(string)
=> Add(left, right,
_stringConcatMethod ??=
typeof(string).GetMethod(nameof(string.Concat), new[] { typeof(string), typeof(string) })),
SyntaxKind.AddExpression => Add(left, right),
SyntaxKind.SubtractExpression => Subtract(left, right),
SyntaxKind.MultiplyExpression => Multiply(left, right),
SyntaxKind.DivideExpression => Divide(left, right),
SyntaxKind.ModuloExpression => Modulo(left, right),
SyntaxKind.LeftShiftExpression => LeftShift(left, right),
SyntaxKind.RightShiftExpression => RightShift(left, right),
// TODO UnsignedRightShiftExpression
SyntaxKind.LogicalOrExpression => OrElse(left, right),
SyntaxKind.LogicalAndExpression => AndAlso(left, right),
// For bitwise operations over enums, we cast the enum to its underlying type before the bitwise operation, and then back to the
// enum afterwards (this is corresponds to the LINQ expression tree that the compiler generates)
SyntaxKind.BitwiseOrExpression when left.Type.IsEnum || right.Type.IsEnum
=> Convert(Or(Convert(left, left.Type.GetEnumUnderlyingType()), Convert(right, right.Type.GetEnumUnderlyingType())), left.Type),
SyntaxKind.BitwiseAndExpression when left.Type.IsEnum || right.Type.IsEnum
=> Convert(And(Convert(left, left.Type.GetEnumUnderlyingType()), Convert(right, right.Type.GetEnumUnderlyingType())), left.Type),
SyntaxKind.ExclusiveOrExpression when left.Type.IsEnum || right.Type.IsEnum
=> Convert(ExclusiveOr(Convert(left, left.Type.GetEnumUnderlyingType()), Convert(right, right.Type.GetEnumUnderlyingType())), left.Type),
SyntaxKind.BitwiseOrExpression => Or(left, right),
SyntaxKind.BitwiseAndExpression => And(left, right),
SyntaxKind.ExclusiveOrExpression => ExclusiveOr(left, right),
SyntaxKind.EqualsExpression => Equal(left, right),
SyntaxKind.NotEqualsExpression => NotEqual(left, right),
SyntaxKind.LessThanExpression => LessThan(left, right),
SyntaxKind.LessThanOrEqualExpression => LessThanOrEqual(left, right),
SyntaxKind.GreaterThanExpression => GreaterThan(left, right),
SyntaxKind.GreaterThanOrEqualExpression => GreaterThanOrEqual(left, right),
SyntaxKind.IsExpression => TypeIs(left, right is ConstantExpression { Value : Type type }
? type
: throw new InvalidOperationException(
$"Encountered {SyntaxKind.IsExpression} with non-constant type right argument: {right}")),
SyntaxKind.AsExpression => TypeAs(left, right is ConstantExpression { Value : Type type }
? type
: throw new InvalidOperationException(
$"Encountered {SyntaxKind.AsExpression} with non-constant type right argument: {right}")),
SyntaxKind.CoalesceExpression => Coalesce(left, right),
_ => throw new ArgumentOutOfRangeException($"BinaryExpressionSyntax with {binary.Kind()}")
};
}
/// <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 override Expression VisitCastExpression(CastExpressionSyntax cast)
=> Convert(Visit(cast.Expression), ResolveType(cast.Type));
/// <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 override Expression VisitConditionalExpression(ConditionalExpressionSyntax conditional)
=> Condition(
Visit(conditional.Condition),
Visit(conditional.WhenTrue),
Visit(conditional.WhenFalse));
/// <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 override Expression VisitElementAccessExpression(ElementAccessExpressionSyntax elementAccessExpression)
{
var arguments = elementAccessExpression.ArgumentList.Arguments;
var visitedExpression = Visit(elementAccessExpression.Expression);
switch (_semanticModel.GetTypeInfo(elementAccessExpression.Expression).ConvertedType)
{
case IArrayTypeSymbol:
Check.DebugAssert(elementAccessExpression.ArgumentList.Arguments.Count == 1,
$"ElementAccessExpressionSyntax over array with {arguments.Count} arguments");
return ArrayIndex(visitedExpression, Visit(arguments[0].Expression));
case INamedTypeSymbol:
var property = visitedExpression.Type
.GetProperties()
.Select(p => new { Property = p, IndexParameters = p.GetIndexParameters() })
.Where(
t => t.IndexParameters.Length == arguments.Count
&& t.IndexParameters
.Select(p => p.ParameterType)
.SequenceEqual(arguments.Select(a => ResolveType(a.Expression))))
.Select(t => t.Property)
.FirstOrDefault();
Check.DebugAssert(property?.GetMethod is not null, "No matching property found for ElementAccessExpressionSyntax");
return Call(visitedExpression, property.GetMethod, arguments.Select(a => Visit(a.Expression)));
case null:
throw new InvalidOperationException(
$"No type for expression {elementAccessExpression.Expression} in {nameof(ElementAccessExpressionSyntax)}");
default:
throw new NotImplementedException($"{nameof(ElementAccessExpressionSyntax)} over non-array");
}
}
/// <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 override Expression VisitIdentifierName(IdentifierNameSyntax identifierName)
{
if (_parameterStack.Peek().TryGetValue(identifierName.Identifier.Text, out var parameter))
{
return parameter;
}
var symbol = _semanticModel.GetSymbolInfo(identifierName).Symbol;
ITypeSymbol typeSymbol;
switch (symbol)
{
case INamedTypeSymbol s:
return Constant(ResolveType(s));
case ILocalSymbol s:
typeSymbol = s.Type;
break;
case IFieldSymbol s:
typeSymbol = s.Type;
break;
case IPropertySymbol s:
typeSymbol = s.Type;
break;
case null:
throw new InvalidOperationException($"Identifier without symbol: {identifierName}");
default:
throw new UnreachableException($"IdentifierName of type {symbol.GetType().Name}: {identifierName}");
}
// TODO: Separate out EF Core-specific logic (EF Core would extend this visitor)
if (typeSymbol.Name.Contains("DbSet"))
{
throw new NotImplementedException("DbSet local symbol");
}
// We have an identifier which isn't in our parameters stack.
// First, if the identifier type is the user's DbContext type (e.g. DbContext local variable, or field/property),
// return a constant over that.
if (typeSymbol.Equals(_userDbContextSymbol, SymbolEqualityComparer.Default))
{
return Constant(_userDbContext);
}
// The Translate entry point into the translator uses Roslyn's data flow analysis to locate all captured variables, and populates
// the _capturedVariable dictionary with them (with null values).
if (symbol is ILocalSymbol localSymbol && _capturedVariables.TryGetValue(localSymbol, out var memberExpression))
{
// The first time we see a captured variable, we create MemberExpression for it and cache it in _capturedVariables.
return memberExpression
?? (_capturedVariables[localSymbol] =
Field(
Constant(new FakeClosureFrameClass()),
new FakeFieldInfo(
typeof(FakeClosureFrameClass),
ResolveType(localSymbol.Type),
localSymbol.Name)));
}
throw new InvalidOperationException(
$"Encountered unknown identifier name '{identifierName}', which doesn't correspond to a lambda parameter or captured variable");
}
/// <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 override Expression VisitImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax implicitArrayCreation)
{
if (_semanticModel.GetTypeInfo(implicitArrayCreation).Type is not IArrayTypeSymbol arrayTypeSymbol)
{
throw new InvalidOperationException($"ArrayCreation: non-array type symbol: {implicitArrayCreation}");
}
if (arrayTypeSymbol.Rank > 1)
{
throw new NotImplementedException($"ArrayCreation: multi-dimensional array: {implicitArrayCreation}");
}
var elementType = ResolveType(arrayTypeSymbol.ElementType);
Check.DebugAssert(elementType is not null, "elementType is not null");
var initializers = implicitArrayCreation.Initializer.Expressions.Select(e => Visit(e));
return NewArrayInit(elementType, initializers);
}
/// <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 override Expression VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax interpolatedString)
{
var formatBuilder = new StringBuilder();
var arguments = new List<Expression>();
foreach (var fragment in interpolatedString.Contents)
{
switch (fragment)
{
case InterpolatedStringTextSyntax text:
formatBuilder.Append(text);
break;
case InterpolationSyntax interpolation:
var interpolationExpression = Visit(interpolation.Expression);
if (interpolationExpression.Type != typeof(object))
{
interpolationExpression = Convert(interpolationExpression, typeof(object));
}
arguments.Add(interpolationExpression);
formatBuilder.Append('{').Append(arguments.Count - 1).Append('}');
break;
default:
throw new UnreachableException();
}
}
// Return a call to string.Format(), unless we have an implicit conversion to FormattableString, in which case return a call to
// FormattableStringFactory.Create().
return Call(
_semanticModel.GetTypeInfo(interpolatedString).ConvertedType switch
{
{ } t when t.Equals(_formattableStringSymbol, SymbolEqualityComparer.Default)
=> _formattableStringFactoryCreateMethod ??= typeof(FormattableStringFactory).GetMethod(
nameof(FormattableStringFactory.Create), [typeof(string), typeof(object[])])!,
_ => _stringFormatMethod ??= typeof(string).GetMethod(nameof(string.Format), [typeof(string), typeof(object[])])!
},
Constant(formatBuilder.ToString()),
NewArrayInit(typeof(object), 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>
public override Expression VisitInvocationExpression(InvocationExpressionSyntax invocation)
{
if (_semanticModel.GetSymbolInfo(invocation).Symbol is not IMethodSymbol methodSymbol)
{
throw new InvalidOperationException("Could not find symbol for method invocation: " + invocation);
}
// First, if the method return type is the user's DbContext type (e.g. DbContext local variable, or field/property), return a
// constant over that DbContext type; the invocation can serve as the root for a LINQ query we can precompile.
if (methodSymbol.ReturnType.Equals(_userDbContextSymbol, SymbolEqualityComparer.Default))
{
return Constant(_userDbContext);
}
var declaringType = ResolveType(methodSymbol.ContainingType);
Expression? instance = null;
if (!methodSymbol.IsStatic || methodSymbol.IsExtensionMethod)
{
// In normal method calls (the ones we support), the invocation node is composed on top of a member access
if (invocation.Expression is not MemberAccessExpressionSyntax { Expression: var receiver })
{
throw new NotSupportedException($"Invocation over non-member access: {invocation}");
}
instance = Visit(receiver);
}
MethodInfo? methodInfo;
if (methodSymbol.IsGenericMethod)
{
var originalDefinition = methodSymbol.OriginalDefinition;
if (originalDefinition.ReducedFrom is not null)
{
originalDefinition = originalDefinition.ReducedFrom;
}
// To accurately find the right open generic method definition based on the Roslyn symbol, we need to create a mapping between
// generic type parameter names (based on the Roslyn side) and .NET reflection Types representing those type parameters.
// This includes both type parameters immediately on the generic method, as well as type parameters from the method's
// containing type (and recursively, its containing types)
var typeTypeParameterMap = new Dictionary<string, Type>(GetTypeTypeParameters(methodSymbol.ContainingType));
var definitionMethodInfos = declaringType.GetMethods()
.Where(m =>
{
if (m.Name == methodSymbol.Name
&& m.IsGenericMethodDefinition
&& m.GetGenericArguments() is var candidateGenericArguments
&& candidateGenericArguments.Length == originalDefinition.TypeParameters.Length
&& m.GetParameters() is var candidateParams
&& candidateParams.Length == originalDefinition.Parameters.Length)
{
var methodTypeParameterMap = new Dictionary<string, Type>(typeTypeParameterMap);
// Prepare a dictionary that will be used to resolve generic type parameters (ITypeParameterSymbol) to the
// corresponding reflection Type. This is needed to correctly (and recursively) resolve the type of parameters
// below.
foreach (var (symbol, type) in methodSymbol.TypeParameters.Zip(candidateGenericArguments))
{
if (symbol.Name != type.Name)
{
return false;
}
methodTypeParameterMap[symbol.Name] = type;
}
for (var i = 0; i < candidateParams.Length; i++)
{
var translatedParamType = ResolveType(originalDefinition.Parameters[i].Type, methodTypeParameterMap);
if (translatedParamType != candidateParams[i].ParameterType)
{
return false;
}
}
return true;
}
return false;
}).ToArray();
if (definitionMethodInfos.Length != 1)
{
throw new InvalidOperationException($"Invocation: Found {definitionMethodInfos.Length} matches for generic method: {invocation}");
}
var definitionMethodInfo = definitionMethodInfos[0];
var typeParams = methodSymbol.TypeArguments.Select(a => ResolveType(a)).ToArray();
methodInfo = definitionMethodInfo.MakeGenericMethod(typeParams);
}
else
{
// Non-generic method
var reducedMethodSymbol = methodSymbol.ReducedFrom ?? methodSymbol;
methodInfo = declaringType.GetMethod(
methodSymbol.Name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
reducedMethodSymbol.Parameters.Select(p => ResolveType(p.Type)).ToArray());
if (methodInfo is null)
{
throw new InvalidOperationException(
$"Invocation: couldn't find method '{methodSymbol.Name}' on type '{declaringType.Name}': {invocation}");
}
}
// We have the reflection MethodInfo for the method, prepare the arguments.
// We can have less arguments than parameters when the method has optional parameters; fill in the missing ones with the default
// value.
// If the method also has a "params" parameter, we also need to take care of that - the syntactic arguments will need to be packed
// into the "params" array etc.
var parameters = methodInfo.GetParameters();
var sourceArguments = invocation.ArgumentList.Arguments;
var destArguments = new Expression?[parameters.Length];
var paramIndex = 0;
// At the syntactic level, an extension method invocation looks like a normal instance's.
// Prepend the instance to the argument list.
// TODO: Test invoking extension without extension syntax (as static)
if (methodSymbol is { IsExtensionMethod: true /*, ReceiverType: { } */ })
{
destArguments[0] = instance;
paramIndex = 1;
instance = null;
}
for (var sourceArgIndex = 0; paramIndex < parameters.Length; paramIndex++)
{
var parameter = parameters[paramIndex];
if (parameter.IsDefined(typeof(ParamArrayAttribute)))
{
// We've reached a "params" parameter; pack all the remaining args (possibly zero) into a NewArrayExpression
var elementType = parameter.ParameterType.GetElementType()!;
var paramsArguments = new Expression[sourceArguments.Count - sourceArgIndex];
for (var paramsArgIndex = 0; sourceArgIndex < sourceArguments.Count; sourceArgIndex++, paramsArgIndex++)
{
var arg = invocation.ArgumentList.Arguments[sourceArgIndex];
Check.DebugAssert(arg.NameColon is null, "Named argument in params");
paramsArguments[paramsArgIndex] = Visit(arg);
}
destArguments[paramIndex] = NewArrayInit(elementType, paramsArguments);
Check.DebugAssert(paramIndex == parameters.Length - 1, "Parameters after params");
break;
}
if (sourceArgIndex >= sourceArguments.Count)
{
// Fewer arguments than there are parameters - we have optional parameters.
Check.DebugAssert(parameter.IsOptional, "Missing non-optional argument");
destArguments[paramIndex] = Constant(
parameter.DefaultValue is null && parameter.ParameterType.IsValueType
? Activator.CreateInstance(parameter.ParameterType)
: parameter.DefaultValue,
parameter.ParameterType);
continue;
}
var argument = invocation.ArgumentList.Arguments[sourceArgIndex++];
// Positional argument
if (argument.NameColon is null)
{
destArguments[paramIndex] = Visit(argument);
continue;
}
// Named argument
throw new NotImplementedException("Named argument");
}
Check.DebugAssert(destArguments.All(a => a is not null), "arguments.All(a => a is not null)");
return Call(instance, methodInfo, destArguments!);
IEnumerable<KeyValuePair<string, Type>> GetTypeTypeParameters(INamedTypeSymbol typeSymbol)
{
// TODO: We match Roslyn type parameters by name, not sure that's right; also for the method's generic type parameters
if (typeSymbol.ContainingType is INamedTypeSymbol containingTypeSymbol)
{
foreach (var kvp in GetTypeTypeParameters(containingTypeSymbol))
{
yield return kvp;
}
}
var type = ResolveType(typeSymbol);
var genericArguments = type.GetGenericArguments();
Check.DebugAssert(
genericArguments.Length == typeSymbol.TypeParameters.Length,
"genericArguments.Length == typeSymbol.TypeParameters.Length");
foreach (var (typeParamSymbol, typeParamType) in typeSymbol.TypeParameters.Zip(genericArguments))
{
yield return new KeyValuePair<string, Type>(typeParamSymbol.Name, typeParamType);
}
}
}
/// <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 override Expression VisitLiteralExpression(LiteralExpressionSyntax literal)
=> _semanticModel.GetTypeInfo(literal) is { ConvertedType: ITypeSymbol type }
? Constant(literal.Token.Value, ResolveType(type))
: Constant(literal.Token.Value);
/// <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 override Expression VisitMemberAccessExpression(MemberAccessExpressionSyntax memberAccess)
{
var expression = Visit(memberAccess.Expression);
if (_semanticModel.GetSymbolInfo(memberAccess).Symbol is not ISymbol memberSymbol)
{
throw new InvalidOperationException($"MemberAccess: Couldn't find symbol for member: {memberAccess}");
}
var containingType = ResolveType(memberSymbol.ContainingType);
var memberInfo = memberSymbol switch
{
IPropertySymbol p => (MemberInfo?)containingType.GetProperty(p.Name),
IFieldSymbol f => containingType.GetField(f.Name),
INamedTypeSymbol t => containingType.GetNestedType(t.Name),
null => throw new InvalidOperationException($"MemberAccess: Couldn't find symbol for member: {memberAccess}"),
_ => throw new NotSupportedException($"MemberAccess: unsupported member symbol '{memberSymbol.GetType().Name}': {memberAccess}")
};
switch (memberInfo)
{
case Type nestedType:
return Constant(nestedType);
case null:
throw new InvalidOperationException($"MemberAccess: couldn't find member '{memberSymbol.Name}': {memberAccess}");
}
// Enum field constant
if (containingType.IsEnum)
{
return Constant(Enum.Parse(containingType, memberInfo.Name), containingType);
}
// array.Length
if (expression.Type.IsArray && memberInfo.Name == "Length")
{
if (expression.Type.GetArrayRank() != 1)
{
throw new NotImplementedException("MemberAccess on multi-dimensional array");
}
return ArrayLength(expression);
}
return MakeMemberAccess(
expression is ConstantExpression { Value: Type } ? null : expression,
memberInfo);
}
/// <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 override Expression VisitObjectCreationExpression(ObjectCreationExpressionSyntax objectCreation)
{
if (_semanticModel.GetSymbolInfo(objectCreation).Symbol is not IMethodSymbol constructorSymbol)
{
throw new InvalidOperationException($"ObjectCreation: couldn't find IMethodSymbol for constructor: {objectCreation}");
}
Check.DebugAssert(constructorSymbol.MethodKind == MethodKind.Constructor, "constructorSymbol.MethodKind == MethodKind.Constructor");
var type = ResolveType(constructorSymbol.ContainingType);
// Find the reflection constructor that matches the constructor symbol's signature
var parameterTypes = constructorSymbol.Parameters.Select(ps => ResolveType(ps.Type)).ToArray();
var constructor = type.GetConstructor(parameterTypes);
var newExpression = constructor is not null
? New(
constructor,
objectCreation.ArgumentList?.Arguments.Select(a => Visit(a)) ?? Array.Empty<Expression>())
: parameterTypes.Length == 0 // For structs, there's no actual parameterless constructor
? New(type)
: throw new InvalidOperationException($"ObjectCreation: Missing constructor: {objectCreation}");
switch (objectCreation.Initializer)
{
// No initializers, just return the NewExpression
case null or { Expressions: [] }:
return newExpression;
// Assignment initializer (new Blog { Name = "foo" })
case { Expressions: [AssignmentExpressionSyntax, ..] }:
return MemberInit(
newExpression,
objectCreation.Initializer.Expressions.Select(
e =>
{
if (e is not AssignmentExpressionSyntax { Left: var lValue, Right: var value })
{
throw new NotSupportedException(
$"ObjectCreation: non-assignment initializer expression of type '{e.GetType().Name}': {objectCreation}");
}
var lValueSymbol = _semanticModel.GetSymbolInfo(lValue).Symbol;
var memberInfo = lValueSymbol switch
{
IPropertySymbol p => (MemberInfo?)type.GetProperty(p.Name),
IFieldSymbol f => type.GetField(f.Name),
_ => throw new InvalidOperationException(
$"ObjectCreation: unsupported initializer for member of type '{lValueSymbol?.GetType().Name}': {e}")
};
if (memberInfo is null)
{
throw new InvalidOperationException(
$"ObjectCreation: couldn't find initialized member '{lValueSymbol.Name}': {e}");
}
return Bind(memberInfo, Visit(value));
}));
// Non-assignment initializer => list initializer (new List<int> { 1, 2, 3 })
default:
// Find the correct Add() method on the collection type
// TODO: This doesn't work if there are multiple Add() methods (contrived). Complete solution would be to find the base
// TODO: type for all initializer expressions and find an Add overload of that type (or a superclass thereof)
var addMethod = type.GetMethods().SingleOrDefault(m => m.Name == "Add" && m.GetParameters().Length == 1);
if (addMethod is null)
{
throw new InvalidOperationException(
$"Couldn't find single Add method on type '{type.Name}', required for list initializer");
}
// TODO: Dictionary initializer, where each ElementInit has more than one expression
return ListInit(
newExpression,
objectCreation.Initializer.Expressions.Select(e => ElementInit(addMethod, Visit(e))));
}
}
/// <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 override Expression VisitParenthesizedExpression(ParenthesizedExpressionSyntax parenthesized)
=> Visit(parenthesized.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>
public override Expression VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax lambda)
=> VisitLambdaExpression(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>
public override Expression VisitPredefinedType(PredefinedTypeSyntax predefinedType)
=> Constant(ResolveType(predefinedType), typeof(Type));
/// <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 override Expression VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax unary)
{
var operand = Visit(unary.Operand);
// https://learn.microsoft.com/dotnet/api/Microsoft.CodeAnalysis.CSharp.Syntax.PrefixUnaryExpressionSyntax
return unary.Kind() switch
{
SyntaxKind.UnaryPlusExpression => UnaryPlus(operand),
SyntaxKind.UnaryMinusExpression => Negate(operand),
SyntaxKind.BitwiseNotExpression => Not(operand),
SyntaxKind.LogicalNotExpression => Not(operand),
SyntaxKind.AddressOfExpression => throw NotSupportedInExpressionTrees(),
SyntaxKind.IndexExpression => throw NotSupportedInExpressionTrees(),
SyntaxKind.PointerIndirectionExpression => throw NotSupportedInExpressionTrees(),
SyntaxKind.PreDecrementExpression => throw NotSupportedInExpressionTrees(),
SyntaxKind.PreIncrementExpression => throw NotSupportedInExpressionTrees(),
_ => throw new UnreachableException(
$"Unexpected syntax kind '{unary.Kind()}' when visiting a {nameof(PrefixUnaryExpressionSyntax)}")
};
NotSupportedException NotSupportedInExpressionTrees()
=> throw new UnreachableException(
$"Unary expression of type {unary.Kind()} is not supported in expression trees");
}
/// <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 override Expression VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax unary)
{
var operand = Visit(unary.Operand);
// https://learn.microsoft.com/dotnet/api/Microsoft.CodeAnalysis.CSharp.Syntax.PostfixUnaryExpressionSyntax
return unary.Kind() switch
{
SyntaxKind.SuppressNullableWarningExpression => operand,
SyntaxKind.PostIncrementExpression => throw NotSupportedInExpressionTrees(),
SyntaxKind.PostDecrementExpression => throw NotSupportedInExpressionTrees(),
_ => throw new UnreachableException(
$"Unexpected syntax kind '{unary.Kind()}' when visiting a {nameof(PostfixUnaryExpressionSyntax)}")
};
NotSupportedException NotSupportedInExpressionTrees()
=> throw new UnreachableException(
$"Unary expression of type {unary.Kind()} is not supported in expression trees");
}
/// <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 override Expression VisitQueryExpression(QueryExpressionSyntax node)
=> throw new NotSupportedException(DesignStrings.QueryComprehensionSyntaxNotSupportedInPrecompiledQueries);
/// <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 override Expression VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax lambda)
=> VisitLambdaExpression(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>
public override Expression VisitTypeOfExpression(TypeOfExpressionSyntax typeOf)
{
if (_semanticModel.GetSymbolInfo(typeOf.Type).Symbol is not ITypeSymbol typeSymbol)
{
throw new InvalidOperationException(
"Could not find symbol for typeof() expression: " + typeOf);
}
var type = ResolveType(typeSymbol);
return Constant(type, typeof(Type));
}
/// <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 override Expression DefaultVisit(SyntaxNode node)
=> throw new NotSupportedException($"Unsupported syntax node of type '{node.GetType()}': {node}");
private Expression VisitLambdaExpression(AnonymousFunctionExpressionSyntax lambda)
{
if (lambda.ExpressionBody is null)
{
throw new NotSupportedException("Lambda with null expression body");
}
if (lambda.Modifiers.Any())
{
throw new NotSupportedException("Lambda with modifiers not supported: " + lambda.Modifiers);