-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Inspection.cs
1298 lines (1190 loc) · 48.6 KB
/
Inspection.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
using Dapper.CodeAnalysis;
using Dapper.Internal.Roslyn;
using Dapper.SqlAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Operations;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
namespace Dapper.Internal;
internal static class Inspection
{
public static bool InvolvesTupleType(this ITypeSymbol? type, out bool hasNames)
=> InvolvesTupleTypeDepthChecked(type, out hasNames, 0);
private static bool InvolvesTupleTypeDepthChecked(ITypeSymbol? type, out bool hasNames, int depth)
{
if (depth >= 20) ThrowPossibleRecursion();
// avoid SOE
static void ThrowPossibleRecursion() => throw new InvalidOperationException("Recursion depth exceeded checking for tuple-type");
while (type is not null) // dive for inheritance
{
if (type is IErrorTypeSymbol) break; // nope!
var named = type as INamedTypeSymbol;
if (type.IsTupleType)
{
hasNames = false;
if (named is not null)
{
int i = 1;
foreach (var field in named.TupleElements)
{
if (!IsDefaultFieldName(field.Name, i))
{
hasNames = true;
break;
}
i++;
}
return true;
}
static bool IsDefaultFieldName(string name, int index)
{
if (string.IsNullOrWhiteSpace(name)) return true;
return name.StartsWith("Item") && name == $"Item{index}";
}
}
if (type is IArrayTypeSymbol array)
{
return InvolvesTupleTypeDepthChecked(array.ElementType, out hasNames, depth + 1);
}
if (named is { IsGenericType: true, IsUnboundGenericType: false })
{
foreach (var arg in named.TypeArguments)
{
if (InvolvesTupleTypeDepthChecked(arg, out hasNames, depth + 1)) return true;
}
}
type = type.BaseType;
}
return hasNames = false;
}
public static AttributeData? GetClosestDapperAttribute(in ParseState ctx, IOperation op, string attributeName)
=> GetClosestDapperAttribute(ctx, op, attributeName, out _);
public static AttributeData? GetClosestDapperAttribute(in ParseState ctx, IOperation op, string attributeName, out Location? location)
{
var symbol = GetSymbol(ctx, op);
while (symbol is not null)
{
var attrib = GetDapperAttribute(symbol, attributeName);
if (attrib is not null)
{
location = symbol.Locations.FirstOrDefault();
return attrib;
}
symbol = symbol is IAssemblySymbol ? null : symbol.ContainingSymbol;
}
location = null;
return null;
}
public static bool IsBasicDapperType(ITypeSymbol? type, string name, TypeKind kind = TypeKind.Class)
=> type is INamedTypeSymbol
{
Arity: 0, ContainingType: null,
ContainingNamespace: { Name: "Dapper", ContainingNamespace.IsGlobalNamespace: true }
} named && named.TypeKind == kind && named.Name == name;
public static bool IsNestedSqlMapperType(ITypeSymbol? type, string name, TypeKind kind = TypeKind.Class)
=> type is INamedTypeSymbol
{
Arity: 0, ContainingType:
{
Name: Types.SqlMapper, TypeKind: TypeKind.Class, IsStatic: true, Arity: 0,
ContainingNamespace: { Name: "Dapper", ContainingNamespace.IsGlobalNamespace: true },
},
} named && named.TypeKind == kind && named.Name == name;
public static ISymbol? GetSymbol(in ParseState ctx, IOperation operation)
{
var method = GetContainingMethodSyntax(operation);
return method is null ? null : ctx.SemanticModel.GetDeclaredSymbol(method, ctx.CancellationToken);
static SyntaxNode? GetContainingMethodSyntax(IOperation op)
{
var syntax = op.Syntax;
while (syntax is not null)
{
if (syntax.IsMethodDeclaration())
{
return syntax;
}
if (syntax.IsGlobalStatement(out var entryPoint))
{
return entryPoint;
}
syntax = syntax.Parent;
}
return null;
}
}
// support the fact that [DapperAot(bool)] can enable/disable generation at any level
// including method, type, module and assembly; first attribute found (walking up the tree): wins
public static bool IsEnabled(in ParseState ctx, IOperation op, string attributeName, out bool exists)
{
var attrib = GetClosestDapperAttribute(ctx, op, attributeName);
if (attrib is not null && attrib.ConstructorArguments.Length == 1
&& attrib.ConstructorArguments[0].Value is bool b)
{
exists = true;
return b;
}
exists = false;
return false;
}
public static bool IsDapperAttribute(AttributeData attrib)
=> attrib.AttributeClass is
{
ContainingNamespace:
{
Name: "Dapper",
ContainingNamespace.IsGlobalNamespace: true
}
};
public static AttributeData? GetDapperAttribute(ISymbol? symbol, string attributeName)
{
if (symbol is not null)
{
foreach (var attrib in symbol.GetAttributes())
{
if (IsDapperAttribute(attrib) && attrib.AttributeClass!.Name == attributeName)
{
return attrib;
}
}
}
return null;
}
public static bool IsMissingOrObjectOrDynamic(ITypeSymbol? type) => type is null || type.SpecialType == SpecialType.System_Object || type.TypeKind == TypeKind.Dynamic;
internal static bool IsDynamicParameters(ITypeSymbol? type, out bool needsConstruction)
{
needsConstruction = false;
if (type is null || type.SpecialType != SpecialType.None) return false;
if (IsBasicDapperType(type, Types.DynamicParameters)
|| IsNestedSqlMapperType(type, Types.IDynamicParameters, TypeKind.Interface)) return true;
foreach (var i in type.AllInterfaces)
{
if (IsNestedSqlMapperType(i, Types.IDynamicParameters, TypeKind.Interface)) return true;
}
// Dapper also treats anything IEnumerable<string,object[?]> as dynamic parameters
if (type.ImplementsIEnumerable(out var found) && found is INamedTypeSymbol { Arity: 1 } iet
&& iet.TypeArguments[0] is INamedTypeSymbol
{
Name: "KeyValuePair", Arity: 2, ContainingType: null,
ContainingNamespace:
{
Name: "Generic",
ContainingNamespace:
{
Name: "Collections",
ContainingNamespace:
{
Name: "System",
ContainingNamespace.IsGlobalNamespace: true
}
}
}
} kvp
&& kvp.TypeArguments[0].SpecialType == SpecialType.System_String
&& kvp.TypeArguments[1].SpecialType == SpecialType.System_Object)
{
needsConstruction = true;
return true;
}
return false;
}
public static bool IsPublicOrAssemblyLocal(ISymbol? symbol, in ParseState ctx, out ISymbol? failingSymbol)
=> IsPublicOrAssemblyLocal(symbol, ctx.SemanticModel.Compilation.Assembly, out failingSymbol);
public static bool IsPublicOrAssemblyLocal(ISymbol? symbol, IAssemblySymbol? assembly, out ISymbol? failingSymbol)
{
if (symbol is null || symbol.Kind == SymbolKind.DynamicType)
{ // interpret null as "dynamic"
failingSymbol = null;
return true;
}
while (symbol is not null)
{
if (symbol is IArrayTypeSymbol array)
{
return IsPublicOrAssemblyLocal(array.ElementType, assembly, out failingSymbol);
}
switch (symbol.DeclaredAccessibility)
{
case Accessibility.Public:
break; // fine, keep looking upwards
case Accessibility.Internal:
case Accessibility.ProtectedOrInternal when assembly is not null:
if (!SymbolEqualityComparer.Default.Equals(symbol.ContainingAssembly, assembly))
{
// different assembly
failingSymbol = symbol;
return false;
}
break; // otherwise fine, keep looking upwards
default:
failingSymbol = symbol;
return false;
}
symbol = symbol.ContainingType;
}
failingSymbol = null;
return true;
}
public static bool InvolvesGenericTypeParameter(ISymbol? symbol)
{
while (symbol is not null)
{
if (symbol is ITypeParameterSymbol)
{
return true;
}
if (symbol is INamedTypeSymbol named && named.Arity != 0)
{
foreach (var arg in named.TypeArguments)
{
if (InvolvesGenericTypeParameter(arg))
{
return true;
}
}
}
// could be Something.Foo<T>.SomethingElse
symbol = symbol.ContainingType;
}
return false;
}
public static string NameAccessibility(ISymbol symbol)
{
var accessibility = symbol is IArrayTypeSymbol array
? array.ElementType.DeclaredAccessibility : symbol.DeclaredAccessibility;
return accessibility switch
{
Accessibility.Public => "public",
Accessibility.Internal => "internal",
Accessibility.Private => "private",
Accessibility.Protected => "protected",
Accessibility.ProtectedAndInternal => "private protected",
Accessibility.ProtectedOrInternal => "protected internal",
_ => "non-public",
};
}
public static bool IsPrimitiveType(ITypeSymbol? parameterType) => parameterType.IsPrimitiveType();
public static bool IsCollectionType(ITypeSymbol? parameterType, out ITypeSymbol? elementType)
=> IsCollectionType(parameterType, out elementType, out _, false);
public static bool IsCollectionType(ITypeSymbol? parameterType, out ITypeSymbol? elementType,
out string castType)
=> IsCollectionType(parameterType, out elementType, out castType, true);
private static bool IsCollectionType(ITypeSymbol? parameterType, out ITypeSymbol? elementType,
out string castType, bool getCastType)
{
castType = "";
if (parameterType is null || parameterType.SpecialType == SpecialType.System_String)
{
elementType = null;
return false;
}
if (parameterType.IsArray())
{
elementType = parameterType.GetContainingTypeSymbol();
if (getCastType) castType = elementType.GetTypeDisplayName() + "[]";
return true;
}
if (parameterType.IsList())
{
elementType = parameterType.GetContainingTypeSymbol();
if (getCastType) castType = "global::System.Collections.Generic.List<" + elementType.GetTypeDisplayName() + ">";
return true;
}
if (parameterType.IsImmutableArray())
{
elementType = parameterType.GetContainingTypeSymbol();
if (getCastType) castType = "global::System.Collections.Immutable.ImmutableArray<" + elementType.GetTypeDisplayName() + ">";
return true;
}
if (parameterType.ImplementsIList(out var listTypeSymbol))
{
elementType = listTypeSymbol.GetContainingTypeSymbol();
if (getCastType) castType = "global::System.Collections.Generic.IList<" + elementType.GetTypeDisplayName() + ">";
return true;
}
if (parameterType.ImplementsICollection(out var collectionTypeSymbol))
{
elementType = collectionTypeSymbol.GetContainingTypeSymbol();
if (getCastType) castType = "global::System.Collections.Generic.ICollection<" + elementType.GetTypeDisplayName() + ">";
return true;
}
if (parameterType.ImplementsIReadOnlyList(out var readonlyListTypeSymbol))
{
elementType = readonlyListTypeSymbol.GetContainingTypeSymbol();
if (getCastType) castType = "global::System.Collections.Generic.IReadOnlyList<" + elementType.GetTypeDisplayName() + ">";
return true;
}
if (parameterType.ImplementsIReadOnlyCollection(out var readonlyCollectionTypeSymbol))
{
elementType = readonlyCollectionTypeSymbol.GetContainingTypeSymbol();
if (getCastType) castType = "global::System.Collections.Generic.IReadOnlyCollection<" + elementType.GetTypeDisplayName() + ">";
return true;
}
if (parameterType.ImplementsIEnumerable(out var enumerableTypeSymbol))
{
elementType = enumerableTypeSymbol.GetContainingTypeSymbol();
if (getCastType) castType = "global::System.Collections.Generic.IEnumerable<" + elementType.GetTypeDisplayName() + ">";
return true;
}
elementType = null;
return false;
}
[DebuggerDisplay("Order: {Order}; Name: {Name}")]
readonly struct MethodParameter
{
/// <summary>
/// Order of parameter in method.
/// Will be 1 for member1 in method(member0, member1, ...)
/// </summary>
public int Order { get; }
/// <summary>
/// Type of method parameter
/// </summary>
public ITypeSymbol Type { get; }
/// <summary>
/// Name of method parameter
/// </summary>
public string Name { get; }
public MethodParameter(int order, ITypeSymbol type, string name)
{
Order = order;
Type = type;
Name = name;
}
}
[Flags]
public enum ElementMemberKind
{
None = 0,
RowCount = 1 << 0,
RowCountHint = 1 << 1,
}
public readonly struct ElementMember
{
public Location[]? AsAdditionalLocations(string? attributeName = null)
{
var loc = GetLocation(attributeName);
return loc is null ? null : [loc];
}
private readonly AttributeData? _dbValue;
public string DbName => TryGetAttributeValue(_dbValue, "Name", out string? name)
&& !string.IsNullOrWhiteSpace(name) ? name!.Trim() : CodeName;
public string CodeName => Member.Name;
public ISymbol Member { get; }
public ITypeSymbol CodeType => Member switch
{
IPropertySymbol prop => prop.Type,
_ => ((IFieldSymbol)Member).Type,
};
public ParameterDirection Direction => TryGetAttributeValue(_dbValue, nameof(Direction), out int direction)
? (ParameterDirection)direction : ParameterDirection.Input;
public ElementMemberKind Kind { get; }
public bool IsRowCount => (Kind & ElementMemberKind.RowCount) != 0;
public bool IsRowCountHint => (Kind & ElementMemberKind.RowCountHint) != 0;
public bool HasDbValueAttribute => _dbValue is not null;
public T? TryGetValue<T>(string memberName) where T : struct
=> TryGetAttributeValue(_dbValue, memberName, out T value) ? value : null;
public DbType? GetDbType(out string? readerMethod)
{
var dbType = IdentifyDbType(CodeType, out readerMethod);
if (TryGetAttributeValue(_dbValue, "DbType", out int explicitType, out bool isNull))
{
var preferredType = isNull ? (DbType?)null : (DbType)explicitType;
if (preferredType != dbType)
{ // only preserve the reader method if this matches
readerMethod = null;
}
}
return dbType;
}
private readonly ElementMemberFlags _flags;
public ElementMemberFlags Flags => _flags;
public bool IsGettable => (_flags & ElementMemberFlags.IsGettable) != 0;
public bool IsSettable => (_flags & ElementMemberFlags.IsSettable) != 0;
public bool IsInitOnly => (_flags & ElementMemberFlags.IsInitOnly) != 0;
public bool IsRequired => (_flags & ElementMemberFlags.IsRequired) != 0;
public bool IsExpandable => (_flags & ElementMemberFlags.IsExpandable) != 0;
/// <summary>
/// Order of member in constructor parameter list (starts from 0).
/// </summary>
public int? ConstructorParameterOrder { get; }
/// <summary>
/// Order of member in factory method parameter list (starts from 0).
/// </summary>
public int? FactoryMethodParameterOrder { get; }
public ElementMember(ISymbol member, AttributeData? dbValue, ElementMemberKind kind)
{
Member = member;
_dbValue = dbValue;
Kind = kind;
}
[Flags]
public enum ElementMemberFlags
{
None = 0,
IsGettable = 1 << 0,
IsSettable = 1 << 1,
IsInitOnly = 1 << 2,
IsExpandable = 1 << 3,
IsRequired = 1 << 4,
}
public ElementMember(
ISymbol member,
AttributeData? dbValue,
ElementMemberKind kind,
ElementMemberFlags flags,
int? constructorParameterOrder,
int? factoryMethodParameterOrder)
{
_dbValue = dbValue;
_flags = flags;
Member = member;
Kind = kind;
ConstructorParameterOrder = constructorParameterOrder;
FactoryMethodParameterOrder = factoryMethodParameterOrder;
}
public override int GetHashCode() => SymbolEqualityComparer.Default.GetHashCode(Member);
public override string ToString() => Member?.Name ?? "";
public override bool Equals(object obj) => obj is ElementMember other
&& SymbolEqualityComparer.Default.Equals(Member, other.Member);
public Location? GetLocation()
{
foreach (var node in Member.DeclaringSyntaxReferences)
{
if (node.GetSyntax().GetLocation() is { } loc)
{
return loc;
}
}
return null;
}
public Location? GetLocation(string? attributeName = null)
{
var loc = attributeName is null ? null :
GetDapperAttribute(Member, attributeName)?.ApplicationSyntaxReference?.GetSyntax()?.GetLocation();
return loc ?? GetLocation();
}
}
public enum ConstructorResult
{
NoneFound,
SuccessSingleExplicit,
SuccessSingleImplicit,
FailMultipleExplicit,
FailMultipleImplicit
}
public enum FactoryMethodResult
{
// note that implicit isn't a thing here
NoneFound,
SuccessSingleExplicit,
FailMultipleExplicit
}
/// <summary>
/// Tries to choose a single factory method for the type.
/// _Note:_ factory method is a 1) publicly visibly; 2) static method 3) with response type equal to containing type
/// </summary>
internal static FactoryMethodResult ChooseFactoryMethod(ITypeSymbol? typeSymbol, out IMethodSymbol? factoryMethod)
{
factoryMethod = null;
if (typeSymbol is null)
{
return FactoryMethodResult.NoneFound;
}
var staticMethods = typeSymbol
.GetMethods(method =>
method.IsStatic &&
SymbolEqualityComparer.Default.Equals(method.ReturnType, typeSymbol) &&
method.DeclaredAccessibility == Accessibility.Public
)
?.ToArray();
if (staticMethods?.Length == 0)
{
return FactoryMethodResult.NoneFound;
}
foreach (var method in staticMethods!)
{
if (GetDapperAttribute(method, Types.ExplicitConstructorAttribute) is not null)
{
if (factoryMethod is not null)
{
// note pointing to first found method for diagnostic
return FactoryMethodResult.FailMultipleExplicit;
}
factoryMethod = method;
}
}
return factoryMethod is null ? FactoryMethodResult.NoneFound : FactoryMethodResult.SuccessSingleExplicit;
}
/// <summary>
/// Builds a collection of type constructors, which are NOT:
/// a) parameterless
/// b) marked with [DapperAot(false)]
/// </summary>
internal static ConstructorResult ChooseConstructor(ITypeSymbol? typeSymbol, out IMethodSymbol? constructor)
{
constructor = null;
if (typeSymbol is not INamedTypeSymbol named)
{
return ConstructorResult.NoneFound;
}
var ctors = named.Constructors;
if (ctors.IsDefaultOrEmpty)
{
return ConstructorResult.NoneFound;
}
// look for [ExplicitConstructor]
foreach (var ctor in ctors)
{
if (GetDapperAttribute(ctor, Types.ExplicitConstructorAttribute) is not null)
{
if (constructor is not null)
{
return ConstructorResult.FailMultipleExplicit;
}
constructor = ctor;
}
}
if (constructor is not null)
{
// we found one [ExplicitConstructor]
return ConstructorResult.SuccessSingleExplicit;
}
// look for remaining constructors
foreach (var ctor in ctors)
{
switch (ctor.DeclaredAccessibility)
{
case Accessibility.Private:
case Accessibility.Protected:
case Accessibility.Friend:
case Accessibility.ProtectedAndInternal:
continue; // we can't use it, so...
}
var args = ctor.Parameters;
if (args.Length == 0) continue; // default constructor
// exclude copy constructors (anything that takes the own type) and serialization constructors
bool exclude = false;
foreach (var arg in args)
{
if (SymbolEqualityComparer.Default.Equals(arg.Type, named))
{
exclude = true;
break;
}
if (arg.Type is INamedTypeSymbol
{
Name: "SerializationInfo" or "StreamingContext",
ContainingType: null,
Arity: 0,
ContainingNamespace:
{
Name: "Serialization",
ContainingNamespace:
{
Name: "Runtime",
ContainingNamespace:
{
Name: "System",
ContainingNamespace.IsGlobalNamespace: true
}
}
}
})
{
exclude = true;
break;
}
}
if (exclude)
{
// ruled out by signature
continue;
}
if (constructor is not null)
{
return ConstructorResult.FailMultipleImplicit;
}
constructor = ctor;
}
return constructor is null ? ConstructorResult.NoneFound : ConstructorResult.SuccessSingleImplicit;
}
/// <summary>
/// Yields the type's members.
/// If <param name="constructor"/> is passed, will be used to associate element member with the constructor parameter by name (case-insensitive).
/// </summary>
/// <param name="elementType">type, which elements to parse</param>
/// <param name="constructor">pointer to single constructor available for AOT scenario</param>
/// <param name="factoryMethod">pointer to single factoryMethod available for AOT scenario</param>
internal static ImmutableArray<ElementMember> GetMembers(bool forParameters, ITypeSymbol? elementType, IMethodSymbol? constructor, IMethodSymbol? factoryMethod)
{
if (elementType is null)
{
return ImmutableArray<ElementMember>.Empty;
}
if (elementType is INamedTypeSymbol named && named.IsTupleType)
{
return ImmutableArray.CreateRange(named.TupleElements, field => new ElementMember(field, null, ElementMemberKind.None));
}
else
{
var elMembers = elementType.GetMembers();
var builder = ImmutableArray.CreateBuilder<ElementMember>(elMembers.Length);
var constructorParameters = (constructor is not null) ? ParseMethodParameters(constructor) : null;
var factoryMethodParameters = (factoryMethod is not null) ? ParseMethodParameters(factoryMethod) : null;
foreach (var member in elMembers)
{
// instance only, must be able to access by name
if (member.IsStatic || !member.CanBeReferencedByName) continue;
// public or annotated only; not explicitly ignored
var dbValue = GetDapperAttribute(member, Types.DbValueAttribute);
var kind = ElementMemberKind.None;
if (GetDapperAttribute(member, Types.RowCountAttribute) is not null)
{
kind |= ElementMemberKind.RowCount;
}
if (GetDapperAttribute(member, Types.RowCountHintAttribute) is not null)
{
kind |= ElementMemberKind.RowCountHint;
}
if (dbValue is null && member.DeclaredAccessibility != Accessibility.Public && kind == ElementMemberKind.None) continue;
if (TryGetAttributeValue(dbValue, "Ignore", out bool ignore) && ignore)
{
continue;
}
// field or property (not indexer)
ITypeSymbol memberType;
switch (member)
{
case IPropertySymbol { IsIndexer: false } prop:
memberType = prop.Type;
break;
case IFieldSymbol field:
memberType = field.Type;
break;
default:
continue;
}
if (memberType is null) continue;
int? constructorParameterOrder = constructorParameters?.TryGetValue(member.Name, out var constructorParameter) == true
? constructorParameter.Order
: null;
int? factoryMethodParamOrder = factoryMethodParameters?.TryGetValue(member.Name, out var factoryMethodParam) == true
? factoryMethodParam.Order
: null;
ElementMember.ElementMemberFlags flags = ElementMember.ElementMemberFlags.None;
if (CodeWriter.IsGettableInstanceMember(member, out _)) flags |= ElementMember.ElementMemberFlags.IsGettable;
if (CodeWriter.IsSettableInstanceMember(member, out _)) flags |= ElementMember.ElementMemberFlags.IsSettable;
if (CodeWriter.IsInitOnlyInstanceMember(member, out _)) flags |= ElementMember.ElementMemberFlags.IsInitOnly;
if (CodeWriter.IsRequired(member)) flags |= ElementMember.ElementMemberFlags.IsRequired;
if (forParameters)
{
// needs to be readable
if ((flags & ElementMember.ElementMemberFlags.IsGettable) == 0) continue;
}
else
{
// needs to be writable
if (constructorParameterOrder is null && factoryMethodParamOrder is null &&
(flags & (ElementMember.ElementMemberFlags.IsSettable | ElementMember.ElementMemberFlags.IsInitOnly)) == 0) continue;
}
// see Dapper's TryStringSplit logic
if (IsCollectionType(memberType, out var innerType) && innerType is not null)
{
flags |= ElementMember.ElementMemberFlags.IsExpandable;
}
// all good, then!
builder.Add(new(member, dbValue, kind, flags, constructorParameterOrder, factoryMethodParamOrder));
}
return builder.ToImmutable();
}
static IReadOnlyDictionary<string, MethodParameter> ParseMethodParameters(IMethodSymbol constructorSymbol)
{
var parameters = new Dictionary<string, MethodParameter>(StringComparer.InvariantCultureIgnoreCase);
int order = 0;
foreach (var parameter in constructorSymbol.Parameters)
{
parameters.Add(parameter.Name, new MethodParameter(order: order++, type: parameter.Type, name: parameter.Name));
}
return parameters;
}
}
private static bool TryGetAttributeValue<T>(AttributeData? attrib, string name, out T? value)
=> TryGetAttributeValue<T>(attrib, name, out value, out _);
private static bool TryGetAttributeValue<T>(AttributeData? attrib, string name, out T? value, out bool isNull)
{
if (attrib is not null)
{
foreach (var member in attrib.NamedArguments)
{
if (member.Key == name)
{
value = Parse(member.Value, out isNull);
return true;
}
}
var ctor = attrib.AttributeConstructor;
if (ctor is not null)
{
int index = 0;
foreach (var p in ctor.Parameters)
{
if (StringComparer.InvariantCultureIgnoreCase.Equals(p.Name == name))
{
value = Parse(attrib.ConstructorArguments[index], out isNull);
return true;
}
index++;
}
}
}
value = default;
isNull = false;
return false;
static T? Parse(TypedConstant value, out bool isNull)
{
if (isNull = value.IsNull)
{
return default;
}
if (value.Value is T typed)
{
return typed;
}
return default;
}
}
//public static ITypeSymbol MakeNullable(ITypeSymbol type)
//{
// if (type is null) return null!; // GIGO
// if (type.IsAsync() && type is INamedTypeSymbol named)
// {
// if (named.TypeArgumentNullableAnnotations.Length == 1 && named.TypeArgumentNullableAnnotations[0] != NullableAnnotation.Annotated)
// {
// return named.ConstructedFrom.Construct(named.TypeArguments, SingleAnnotated);
// }
// }
// else if (type.NullableAnnotation != NullableAnnotation.Annotated)
// {
// return type.WithNullableAnnotation(NullableAnnotation.Annotated);
// }
// return type;
//}
private static readonly ImmutableArray<NullableAnnotation> SingleAnnotated = new[] { NullableAnnotation.Annotated }.ToImmutableArray();
public static ITypeSymbol MakeNonNullable(ITypeSymbol type)
{
// think: type = Nullable.GetUnderlyingType(type) ?? type
if (type.IsValueType && type is INamedTypeSymbol { Arity: 1, ConstructedFrom.SpecialType: SpecialType.System_Nullable_T } named)
{
return named.TypeArguments[0];
}
return type.NullableAnnotation == NullableAnnotation.None
? type : type.WithNullableAnnotation(NullableAnnotation.None);
}
public static DbType? IdentifyDbType(ITypeSymbol? type, out string? readerMethod)
{
if (type is null)
{
readerMethod = null;
return null;
}
type = MakeNonNullable(type);
switch (type.SpecialType)
{
case SpecialType.System_Boolean:
readerMethod = nameof(DbDataReader.GetBoolean);
return DbType.Boolean;
case SpecialType.System_String:
readerMethod = nameof(DbDataReader.GetString);
return DbType.String;
case SpecialType.System_Single:
readerMethod = nameof(DbDataReader.GetFloat);
return DbType.Single;
case SpecialType.System_Double:
readerMethod = nameof(DbDataReader.GetDouble);
return DbType.Double;
case SpecialType.System_Decimal:
readerMethod = nameof(DbDataReader.GetDecimal);
return DbType.Decimal;
case SpecialType.System_DateTime:
readerMethod = nameof(DbDataReader.GetDateTime);
return DbType.DateTime;
case SpecialType.System_Int16:
readerMethod = nameof(DbDataReader.GetInt16);
return DbType.Int16;
case SpecialType.System_Int32:
readerMethod = nameof(DbDataReader.GetInt32);
return DbType.Int32;
case SpecialType.System_Int64:
readerMethod = nameof(DbDataReader.GetInt64);
return DbType.Int64;
case SpecialType.System_UInt16:
readerMethod = null;
return DbType.UInt16;
case SpecialType.System_UInt32:
readerMethod = null;
return DbType.UInt32;
case SpecialType.System_UInt64:
readerMethod = null;
return DbType.UInt64;
case SpecialType.System_Byte:
readerMethod = nameof(DbDataReader.GetByte);
return DbType.Byte;
case SpecialType.System_SByte:
readerMethod = null;
return DbType.SByte;
}
if (type.Name == nameof(Guid) && type.ContainingNamespace is { Name: "System", ContainingNamespace.IsGlobalNamespace: true })
{
readerMethod = nameof(DbDataReader.GetGuid);
return DbType.Guid;
}
if (type.Name == nameof(DateTimeOffset) && type.ContainingNamespace is { Name: "System", ContainingNamespace.IsGlobalNamespace: true })
{
readerMethod = null;
return DbType.DateTimeOffset;
}
readerMethod = null;
return null;
}
public static bool IsDapperMethod(this IInvocationOperation operation, out OperationFlags flags)
{
flags = OperationFlags.None;
var method = operation?.TargetMethod;
if (method is null || !method.IsExtensionMethod)
{
return false;
}
var type = method.ContainingType;
if (type is not { Name: Types.SqlMapper, ContainingNamespace: { Name: "Dapper", ContainingNamespace.IsGlobalNamespace: true } })
{
return false;
}
if (method.Name.EndsWith("Async"))
{
flags |= OperationFlags.Async;
}
if (method.IsGenericMethod)
{
flags |= OperationFlags.TypedResult;
}
switch (method.Name)
{
case "Query":
flags |= OperationFlags.Query;
if (method.Arity > 1) flags |= OperationFlags.NotAotSupported;
break;
case "QueryAsync":
case "QueryUnbufferedAsync":
flags |= method.Name.Contains("Unbuffered") ? OperationFlags.Unbuffered : OperationFlags.Buffered;
goto case "Query";
case "QueryFirst":
case "QueryFirstAsync":
flags |= OperationFlags.SingleRow | OperationFlags.AtLeastOne;
goto case "Query";
case "QueryFirstOrDefault":
case "QueryFirstOrDefaultAsync":
flags |= OperationFlags.SingleRow;
goto case "Query";
case "QuerySingle":
case "QuerySingleAsync":
flags |= OperationFlags.SingleRow | OperationFlags.AtLeastOne | OperationFlags.AtMostOne;
goto case "Query";
case "QuerySingleOrDefault":
case "QuerySingleOrDefaultAsync":
flags |= OperationFlags.SingleRow | OperationFlags.AtMostOne;
goto case "Query";
case "QueryMultiple":
case "QueryMultipleAsync":
flags |= OperationFlags.Query | OperationFlags.QueryMultiple | OperationFlags.NotAotSupported;
break;
case "Execute":
case "ExecuteAsync":
flags |= OperationFlags.Execute;
if (method.Arity != 0) flags |= OperationFlags.NotAotSupported;
break;
case "ExecuteScalar":
case "ExecuteScalarAsync":
flags |= OperationFlags.Execute | OperationFlags.Scalar;
if (method.Arity >= 2) flags |= OperationFlags.NotAotSupported;
break;
case "GetRowParser":