-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdapterGenerator.cs
More file actions
1015 lines (883 loc) · 42.3 KB
/
AdapterGenerator.cs
File metadata and controls
1015 lines (883 loc) · 42.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Text;
namespace PatternKit.Generators.Adapter;
/// <summary>
/// Source generator for the Adapter pattern.
/// Generates object adapters that implement a target contract by delegating to an adaptee through mapping methods.
/// </summary>
[Generator]
public sealed class AdapterGenerator : IIncrementalGenerator
{
// Symbol display format for generated code (fully qualified with global::, but use keywords for special types)
private static readonly SymbolDisplayFormat FullyQualifiedFormat = new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
// Diagnostic IDs
private const string DiagIdHostNotStaticPartial = "PKADP001";
private const string DiagIdTargetNotInterfaceOrAbstract = "PKADP002";
private const string DiagIdMissingMapping = "PKADP003";
private const string DiagIdDuplicateMapping = "PKADP004";
private const string DiagIdSignatureMismatch = "PKADP005";
private const string DiagIdTypeNameConflict = "PKADP006";
private const string DiagIdInvalidAdapteeType = "PKADP007";
private const string DiagIdMapMethodNotStatic = "PKADP008";
private const string DiagIdEventsNotSupported = "PKADP009";
private const string DiagIdGenericMethodsNotSupported = "PKADP010";
private const string DiagIdOverloadedMethodsNotSupported = "PKADP011";
private const string DiagIdAbstractClassNoParameterlessCtor = "PKADP012";
private const string DiagIdSettablePropertiesNotSupported = "PKADP013";
private const string DiagIdNestedOrGenericHost = "PKADP014";
private const string DiagIdMappingMethodNotAccessible = "PKADP015";
private const string DiagIdStaticMembersNotSupported = "PKADP016";
private const string DiagIdRefReturnNotSupported = "PKADP017";
private static readonly DiagnosticDescriptor HostNotStaticPartialDescriptor = new(
id: DiagIdHostNotStaticPartial,
title: "Adapter host must be static partial",
messageFormat: "Type '{0}' is marked with [GenerateAdapter] but is not declared as 'static partial'",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor TargetNotInterfaceOrAbstractDescriptor = new(
id: DiagIdTargetNotInterfaceOrAbstract,
title: "Target must be interface or abstract class",
messageFormat: "Target type '{0}' must be an interface or abstract class",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor MissingMappingDescriptor = new(
id: DiagIdMissingMapping,
title: "Missing mapping for target member",
messageFormat: "No [AdapterMap] method found for target member '{0}.{1}'",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor DuplicateMappingDescriptor = new(
id: DiagIdDuplicateMapping,
title: "Duplicate mapping for target member",
messageFormat: "Multiple [AdapterMap] methods found for target member '{0}'",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor SignatureMismatchDescriptor = new(
id: DiagIdSignatureMismatch,
title: "Mapping method signature mismatch",
messageFormat: "Mapping method '{0}' signature does not match target member '{1}': {2}",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor TypeNameConflictDescriptor = new(
id: DiagIdTypeNameConflict,
title: "Adapter type name conflicts with existing type",
messageFormat: "Adapter type name '{0}' conflicts with an existing type in namespace '{1}'",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor InvalidAdapteeTypeDescriptor = new(
id: DiagIdInvalidAdapteeType,
title: "Invalid adaptee type",
messageFormat: "Adaptee type '{0}' must be a concrete class or struct",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor MapMethodNotStaticDescriptor = new(
id: DiagIdMapMethodNotStatic,
title: "Mapping method must be static",
messageFormat: "Mapping method '{0}' must be declared as static",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor EventsNotSupportedDescriptor = new(
id: DiagIdEventsNotSupported,
title: "Events are not supported",
messageFormat: "Target type '{0}' contains event '{1}' which is not supported by the adapter generator",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor GenericMethodsNotSupportedDescriptor = new(
id: DiagIdGenericMethodsNotSupported,
title: "Generic methods are not supported",
messageFormat: "Target type '{0}' contains generic method '{1}' which is not supported by the adapter generator",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor OverloadedMethodsNotSupportedDescriptor = new(
id: DiagIdOverloadedMethodsNotSupported,
title: "Overloaded methods are not supported",
messageFormat: "Target type '{0}' contains overloaded method '{1}' which is not supported by the adapter generator",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor AbstractClassNoParameterlessCtorDescriptor = new(
id: DiagIdAbstractClassNoParameterlessCtor,
title: "Abstract class target requires accessible parameterless constructor",
messageFormat: "Abstract class '{0}' does not have an accessible parameterless constructor",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor SettablePropertiesNotSupportedDescriptor = new(
id: DiagIdSettablePropertiesNotSupported,
title: "Settable properties are not supported",
messageFormat: "Target type '{0}' contains settable property '{1}' which is not supported by the adapter generator",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor NestedOrGenericHostDescriptor = new(
id: DiagIdNestedOrGenericHost,
title: "Nested or generic host not supported",
messageFormat: "Adapter host '{0}' cannot be nested or generic",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor MappingMethodNotAccessibleDescriptor = new(
id: DiagIdMappingMethodNotAccessible,
title: "Mapping method must be accessible",
messageFormat: "Mapping method '{0}' must be public or internal to be accessible from generated adapter",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor StaticMembersNotSupportedDescriptor = new(
id: DiagIdStaticMembersNotSupported,
title: "Static members are not supported",
messageFormat: "Target type '{0}' contains static member '{1}' which is not supported by the adapter generator",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor RefReturnNotSupportedDescriptor = new(
id: DiagIdRefReturnNotSupported,
title: "Ref-return members are not supported",
messageFormat: "Target type '{0}' contains ref-return member '{1}' which is not supported by the adapter generator",
category: "PatternKit.Generators.Adapter",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Find all class declarations with [GenerateAdapter] attribute
var adapterHosts = context.SyntaxProvider.ForAttributeWithMetadataName(
fullyQualifiedMetadataName: "PatternKit.Generators.Adapter.GenerateAdapterAttribute",
predicate: static (node, _) => node is ClassDeclarationSyntax,
transform: static (ctx, _) => ctx
);
// Generate for each host
context.RegisterSourceOutput(adapterHosts, (spc, typeContext) =>
{
if (typeContext.TargetSymbol is not INamedTypeSymbol hostSymbol)
return;
var node = typeContext.TargetNode;
// Process each [GenerateAdapter] attribute on the host
foreach (var attr in typeContext.Attributes.Where(a =>
a.AttributeClass?.ToDisplayString() == "PatternKit.Generators.Adapter.GenerateAdapterAttribute"))
{
GenerateAdapterForAttribute(spc, hostSymbol, attr, node, typeContext.SemanticModel);
}
});
}
private void GenerateAdapterForAttribute(
SourceProductionContext context,
INamedTypeSymbol hostSymbol,
AttributeData attribute,
SyntaxNode node,
SemanticModel semanticModel)
{
// Validate host is static partial
if (!IsStaticPartial(node))
{
context.ReportDiagnostic(Diagnostic.Create(
HostNotStaticPartialDescriptor,
node.GetLocation(),
hostSymbol.Name));
return;
}
// Validate host is not nested or generic
if (hostSymbol.ContainingType is not null || hostSymbol.TypeParameters.Length > 0)
{
context.ReportDiagnostic(Diagnostic.Create(
NestedOrGenericHostDescriptor,
node.GetLocation(),
hostSymbol.Name));
return;
}
// Parse attribute arguments
var config = ParseAdapterConfig(attribute);
if (config.TargetType is null || config.AdapteeType is null)
return; // Attribute error, let compiler handle
// Reject unbound/open generic target types (e.g., typeof(IFoo<>))
if (config.TargetType.IsUnboundGenericType)
{
context.ReportDiagnostic(Diagnostic.Create(
TargetNotInterfaceOrAbstractDescriptor,
node.GetLocation(),
config.TargetType.ToDisplayString()));
return;
}
// Reject unbound/open generic adaptee types (e.g., typeof(IFoo<>))
if (config.AdapteeType.IsUnboundGenericType)
{
context.ReportDiagnostic(Diagnostic.Create(
InvalidAdapteeTypeDescriptor,
node.GetLocation(),
config.AdapteeType.ToDisplayString()));
return;
}
// Validate target is interface or abstract class
if (!IsValidTargetType(config.TargetType))
{
context.ReportDiagnostic(Diagnostic.Create(
TargetNotInterfaceOrAbstractDescriptor,
node.GetLocation(),
config.TargetType.ToDisplayString()));
return;
}
// Validate adaptee is concrete type
if (!IsValidAdapteeType(config.AdapteeType))
{
context.ReportDiagnostic(Diagnostic.Create(
InvalidAdapteeTypeDescriptor,
node.GetLocation(),
config.AdapteeType.ToDisplayString()));
return;
}
// For abstract class targets, validate accessible parameterless constructor exists
if (config.TargetType.TypeKind == TypeKind.Class && config.TargetType.IsAbstract)
{
var hasAccessibleParameterlessCtor = config.TargetType.InstanceConstructors
.Any(c => c.Parameters.Length == 0 &&
(c.DeclaredAccessibility == Accessibility.Public ||
c.DeclaredAccessibility == Accessibility.Protected ||
c.DeclaredAccessibility == Accessibility.ProtectedOrInternal ||
c.DeclaredAccessibility == Accessibility.Internal));
if (!hasAccessibleParameterlessCtor)
{
context.ReportDiagnostic(Diagnostic.Create(
AbstractClassNoParameterlessCtorDescriptor,
node.GetLocation(),
config.TargetType.ToDisplayString()));
return;
}
}
// Check for unsupported members (events, generic methods, overloads)
var unsupportedMemberErrors = ValidateTargetMembers(config.TargetType, node.GetLocation());
foreach (var diagnostic in unsupportedMemberErrors)
{
context.ReportDiagnostic(diagnostic);
}
if (unsupportedMemberErrors.Any())
return;
// Get all mapping methods from host
var mappingMethods = GetMappingMethods(hostSymbol, config.AdapteeType);
// Validate mapping methods are static and accessible
foreach (var (method, _) in mappingMethods)
{
if (!method.IsStatic)
{
context.ReportDiagnostic(Diagnostic.Create(
MapMethodNotStaticDescriptor,
method.Locations.FirstOrDefault() ?? node.GetLocation(),
method.Name));
return;
}
// Validate method is accessible (public or internal)
if (method.DeclaredAccessibility != Accessibility.Public &&
method.DeclaredAccessibility != Accessibility.Internal)
{
context.ReportDiagnostic(Diagnostic.Create(
MappingMethodNotAccessibleDescriptor,
method.Locations.FirstOrDefault() ?? node.GetLocation(),
method.Name));
return;
}
}
// Get target members that need mapping
var targetMembers = GetTargetMembers(config.TargetType);
// Build mapping dictionary and validate
var memberMappings = new Dictionary<ISymbol, IMethodSymbol>(SymbolEqualityComparer.Default);
var hasErrors = false;
foreach (var targetMember in targetMembers)
{
var memberName = targetMember.Name;
var matchingMaps = mappingMethods.Where(m => m.TargetMember == memberName).ToList();
if (matchingMaps.Count == 0)
{
if (config.MissingMapPolicy == AdapterMissingMapPolicyValue.Error)
{
context.ReportDiagnostic(Diagnostic.Create(
MissingMappingDescriptor,
node.GetLocation(),
config.TargetType.Name,
memberName));
hasErrors = true;
}
// For ThrowingStub, we'll generate the stub later
}
else if (matchingMaps.Count > 1)
{
context.ReportDiagnostic(Diagnostic.Create(
DuplicateMappingDescriptor,
matchingMaps[1].Method.Locations.FirstOrDefault() ?? node.GetLocation(),
memberName));
hasErrors = true;
}
else
{
var mapping = matchingMaps[0];
var signatureError = ValidateSignature(targetMember, mapping.Method, config.AdapteeType);
if (signatureError is not null)
{
context.ReportDiagnostic(Diagnostic.Create(
SignatureMismatchDescriptor,
mapping.Method.Locations.FirstOrDefault() ?? node.GetLocation(),
mapping.Method.Name,
memberName,
signatureError));
hasErrors = true;
}
else
{
memberMappings[targetMember] = mapping.Method;
}
}
}
if (hasErrors)
return;
// Determine adapter type name
var adapterTypeName = config.AdapterTypeName
?? $"{config.AdapteeType.Name}To{config.TargetType.Name}Adapter";
// Determine namespace
var ns = config.Namespace
?? (hostSymbol.ContainingNamespace.IsGlobalNamespace
? string.Empty
: hostSymbol.ContainingNamespace.ToDisplayString());
// Check for type name conflict (PKADP006)
if (HasTypeNameConflict(semanticModel.Compilation, ns, adapterTypeName))
{
context.ReportDiagnostic(Diagnostic.Create(
TypeNameConflictDescriptor,
node.GetLocation(),
adapterTypeName,
string.IsNullOrEmpty(ns) ? "<global>" : ns));
return;
}
// Generate adapter
var source = GenerateAdapterCode(
adapterTypeName,
ns,
config.TargetType,
config.AdapteeType,
hostSymbol,
targetMembers,
memberMappings,
config.MissingMapPolicy,
config.Sealed);
var hintName = string.IsNullOrEmpty(ns)
? $"{adapterTypeName}.Adapter.g.cs"
: $"{ns}.{adapterTypeName}.Adapter.g.cs";
context.AddSource(hintName, source);
}
private static bool IsStaticPartial(SyntaxNode node)
{
if (node is not ClassDeclarationSyntax classDecl)
return false;
var hasStatic = classDecl.Modifiers.Any(SyntaxKind.StaticKeyword);
var hasPartial = classDecl.Modifiers.Any(SyntaxKind.PartialKeyword);
return hasStatic && hasPartial;
}
private static bool IsValidTargetType(INamedTypeSymbol type)
{
return type.TypeKind == TypeKind.Interface ||
(type.TypeKind == TypeKind.Class && type.IsAbstract);
}
private static bool IsValidAdapteeType(INamedTypeSymbol type)
{
return (type.TypeKind == TypeKind.Class || type.TypeKind == TypeKind.Struct) &&
!type.IsAbstract;
}
private static bool HasTypeNameConflict(Compilation compilation, string ns, string typeName)
{
var fullName = string.IsNullOrEmpty(ns) ? typeName : $"{ns}.{typeName}";
return compilation.GetTypeByMetadataName(fullName) is not null;
}
private List<Diagnostic> ValidateTargetMembers(INamedTypeSymbol targetType, Location location)
{
var diagnostics = new List<Diagnostic>();
var isAbstractClass = targetType.TypeKind == TypeKind.Class && targetType.IsAbstract;
// Track method signatures to detect true overloads vs diamond inheritance
// Key: method name, Value: set of full signatures for that name
var methodSignatures = new Dictionary<string, HashSet<string>>();
// Collect all members from the type hierarchy
var typesToProcess = new Queue<INamedTypeSymbol>();
typesToProcess.Enqueue(targetType);
var processed = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default);
while (typesToProcess.Count > 0)
{
var type = typesToProcess.Dequeue();
if (!processed.Add(type))
continue;
var membersToCheck = type.GetMembers()
.Where(m => !isAbstractClass || m.IsAbstract);
foreach (var member in membersToCheck)
{
// Check for static members (not supported)
if (member.IsStatic)
{
diagnostics.Add(Diagnostic.Create(
StaticMembersNotSupportedDescriptor,
location,
targetType.Name,
member.Name));
}
// Check for events (not supported)
if (member is IEventSymbol evt)
{
diagnostics.Add(Diagnostic.Create(
EventsNotSupportedDescriptor,
location,
targetType.Name,
evt.Name));
}
// Check for settable properties (not supported)
if (member is IPropertySymbol prop && !prop.IsIndexer && prop.SetMethod is not null)
{
diagnostics.Add(Diagnostic.Create(
SettablePropertiesNotSupportedDescriptor,
location,
targetType.Name,
prop.Name));
}
// Check for ref-return properties (not supported)
if (member is IPropertySymbol refProp && refProp.ReturnsByRef)
{
diagnostics.Add(Diagnostic.Create(
RefReturnNotSupportedDescriptor,
location,
targetType.Name,
refProp.Name));
}
// Check for generic methods (not supported)
if (member is IMethodSymbol method && method.MethodKind == MethodKind.Ordinary)
{
if (method.IsGenericMethod)
{
diagnostics.Add(Diagnostic.Create(
GenericMethodsNotSupportedDescriptor,
location,
targetType.Name,
method.Name));
}
// Check for ref-return methods (not supported)
if (method.ReturnsByRef || method.ReturnsByRefReadonly)
{
diagnostics.Add(Diagnostic.Create(
RefReturnNotSupportedDescriptor,
location,
targetType.Name,
method.Name));
}
// Track full method signature for overload detection
var sig = GetMemberSignature(method);
if (!methodSignatures.TryGetValue(method.Name, out var sigs))
{
sigs = new HashSet<string>();
methodSignatures[method.Name] = sigs;
}
sigs.Add(sig);
}
}
// Add base interfaces
foreach (var iface in type.Interfaces)
typesToProcess.Enqueue(iface);
// Add base class (for abstract classes)
if (type.BaseType is not null && type.BaseType.IsAbstract)
typesToProcess.Enqueue(type.BaseType);
}
// Check for true overloaded methods (same name, different signatures)
// Diamond inheritance (same signature from multiple paths) is OK
foreach (var kvp in methodSignatures.Where(kvp => kvp.Value.Count > 1))
{
diagnostics.Add(Diagnostic.Create(
OverloadedMethodsNotSupportedDescriptor,
location,
targetType.Name,
kvp.Key));
}
return diagnostics;
}
private static AdapterConfig ParseAdapterConfig(AttributeData attribute)
{
var config = new AdapterConfig();
foreach (var named in attribute.NamedArguments)
{
switch (named.Key)
{
case "Target":
config.TargetType = named.Value.Value as INamedTypeSymbol;
break;
case "Adaptee":
config.AdapteeType = named.Value.Value as INamedTypeSymbol;
break;
case "AdapterTypeName":
config.AdapterTypeName = named.Value.Value as string;
break;
case "MissingMap":
if (named.Value.Value is int missingMapValue &&
global::System.Enum.IsDefined(typeof(AdapterMissingMapPolicyValue), missingMapValue))
{
config.MissingMapPolicy = (AdapterMissingMapPolicyValue)missingMapValue;
}
break;
case "Sealed":
if (named.Value.Value is bool sealedValue)
config.Sealed = sealedValue;
break;
case "Namespace":
config.Namespace = named.Value.Value as string;
break;
}
}
return config;
}
private static List<(IMethodSymbol Method, string TargetMember)> GetMappingMethods(
INamedTypeSymbol hostSymbol,
INamedTypeSymbol adapteeType)
{
var mappings = new List<(IMethodSymbol, string)>();
foreach (var member in hostSymbol.GetMembers().OfType<IMethodSymbol>())
{
var mapAttr = member.GetAttributes().FirstOrDefault(a =>
a.AttributeClass?.ToDisplayString() == "PatternKit.Generators.Adapter.AdapterMapAttribute");
if (mapAttr is null)
continue;
// Filter by first parameter type matching the adaptee type
if (member.Parameters.Length == 0)
continue;
var firstParamType = member.Parameters[0].Type;
if (!SymbolEqualityComparer.Default.Equals(firstParamType, adapteeType))
continue;
var targetMember = mapAttr.NamedArguments
.FirstOrDefault(na => na.Key == "TargetMember")
.Value.Value as string;
if (targetMember is not null)
{
mappings.Add((member, targetMember));
}
}
return mappings;
}
private static List<ISymbol> GetTargetMembers(INamedTypeSymbol targetType)
{
var members = new List<ISymbol>();
var seenSignatures = new HashSet<string>();
var isAbstractClass = targetType.TypeKind == TypeKind.Class && targetType.IsAbstract;
// Get members from this type and all base interfaces/classes
var typesToProcess = new Queue<INamedTypeSymbol>();
typesToProcess.Enqueue(targetType);
var processed = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default);
while (typesToProcess.Count > 0)
{
var type = typesToProcess.Dequeue();
if (!processed.Add(type))
continue;
var membersToProcess = type.GetMembers()
.Where(m => !m.IsStatic) // Exclude static members
.Where(m => !isAbstractClass || m.IsAbstract);
foreach (var member in membersToProcess)
{
// Include methods (not constructors), properties (not events - not supported)
if (member is IMethodSymbol method && method.MethodKind == MethodKind.Ordinary)
{
// De-duplicate by signature for interface diamonds
var sig = GetMemberSignature(method);
if (seenSignatures.Add(sig))
members.Add(member);
}
else if (member is IPropertySymbol prop && !prop.IsIndexer)
{
// De-duplicate by name+type for properties
var sig = $"P:{prop.Name}:{prop.Type.ToDisplayString(FullyQualifiedFormat)}";
if (seenSignatures.Add(sig))
members.Add(member);
}
// Events are intentionally excluded - not supported by this generator
}
// Add base interfaces
foreach (var iface in type.Interfaces)
{
typesToProcess.Enqueue(iface);
}
// Add base class (for abstract classes)
if (type.BaseType is not null && type.BaseType.IsAbstract)
{
typesToProcess.Enqueue(type.BaseType);
}
}
// Ensure stable, deterministic ordering by kind+name+signature
// This provides a predictable output order even if member traversal is non-deterministic
return members.OrderBy(m => m.Kind)
.ThenBy(m => m.Name)
.ThenBy(m => m.ToDisplayString(FullyQualifiedFormat))
.ToList();
}
private static string GetMemberSignature(IMethodSymbol method)
{
var paramSig = string.Join(",", method.Parameters.Select(p =>
$"{p.RefKind}:{p.Type.ToDisplayString(FullyQualifiedFormat)}"));
return $"M:{method.Name}({paramSig}):{method.ReturnType.ToDisplayString(FullyQualifiedFormat)}";
}
private static string? ValidateSignature(ISymbol targetMember, IMethodSymbol mapMethod, INamedTypeSymbol adapteeType)
{
// First parameter must be the adaptee type
if (mapMethod.Parameters.Length == 0)
return $"First parameter must be of type '{adapteeType.ToDisplayString()}'.";
var firstParam = mapMethod.Parameters[0];
if (!SymbolEqualityComparer.Default.Equals(firstParam.Type, adapteeType))
return $"First parameter must be of type '{adapteeType.ToDisplayString()}', but was '{firstParam.Type.ToDisplayString()}'.";
// Adaptee parameter must be passed by value (no ref/in/out) and cannot be a 'this' or 'scoped' parameter,
// because the generated call site always passes `_adaptee` without any modifier.
if (firstParam.RefKind != RefKind.None)
return "Adaptee parameter must not have a ref, in, or out modifier.";
if (firstParam.IsThis)
return "Adaptee parameter cannot be declared with the 'this' modifier.";
if (firstParam.ScopedKind != ScopedKind.None)
return "Adaptee parameter cannot be declared with the 'scoped' modifier.";
if (targetMember is IMethodSymbol targetMethod)
{
// Check return type with nullability
if (!SymbolEqualityComparer.IncludeNullability.Equals(mapMethod.ReturnType, targetMethod.ReturnType))
return $"Return type must be '{targetMethod.ReturnType.ToDisplayString()}', but was '{mapMethod.ReturnType.ToDisplayString()}'.";
// Check remaining parameters (after adaptee)
var mapParams = mapMethod.Parameters.Skip(1).ToList();
var targetParams = targetMethod.Parameters.ToList();
if (mapParams.Count != targetParams.Count)
return $"Expected {targetParams.Count} parameters (after adaptee), but found {mapParams.Count}.";
for (int i = 0; i < targetParams.Count; i++)
{
var mapParam = mapParams[i];
var targetParam = targetParams[i];
if (!SymbolEqualityComparer.IncludeNullability.Equals(mapParam.Type, targetParam.Type))
return $"Parameter '{targetParam.Name}' type mismatch: expected '{targetParam.Type.ToDisplayString()}', but was '{mapParam.Type.ToDisplayString()}'.";
if (mapParam.RefKind != targetParam.RefKind)
return $"Parameter '{targetParam.Name}' ref kind mismatch: expected '{targetParam.RefKind}', but was '{mapParam.RefKind}'.";
}
}
else if (targetMember is IPropertySymbol targetProp)
{
// For property getters, no additional parameters
if (mapMethod.Parameters.Length != 1)
return $"Property getter mapping must have exactly one parameter (the adaptee).";
// Check return type with nullability
if (!SymbolEqualityComparer.IncludeNullability.Equals(mapMethod.ReturnType, targetProp.Type))
return $"Return type must be '{targetProp.Type.ToDisplayString()}', but was '{mapMethod.ReturnType.ToDisplayString()}'.";
}
return null; // Valid
}
private static string GenerateAdapterCode(
string adapterTypeName,
string ns,
INamedTypeSymbol targetType,
INamedTypeSymbol adapteeType,
INamedTypeSymbol hostSymbol,
List<ISymbol> targetMembers,
Dictionary<ISymbol, IMethodSymbol> memberMappings,
AdapterMissingMapPolicyValue missingMapPolicy,
bool isSealed)
{
var sb = new StringBuilder();
// File header
sb.AppendLine("// <auto-generated/>");
sb.AppendLine("#nullable enable");
sb.AppendLine();
// Namespace
if (!string.IsNullOrEmpty(ns))
{
sb.AppendLine($"namespace {ns};");
sb.AppendLine();
}
// Class declaration
var sealedModifier = isSealed ? "sealed " : "";
var targetTypeName = targetType.ToDisplayString(FullyQualifiedFormat);
var adapteeTypeName = adapteeType.ToDisplayString(FullyQualifiedFormat);
var hostTypeName = hostSymbol.ToDisplayString(FullyQualifiedFormat);
sb.AppendLine("/// <summary>");
sb.AppendLine($"/// Adapter that implements <see cref=\"{targetTypeName}\"/> by delegating to <see cref=\"{adapteeTypeName}\"/>.");
sb.AppendLine("/// </summary>");
sb.AppendLine($"public {sealedModifier}partial class {adapterTypeName} : {targetTypeName}");
sb.AppendLine("{");
// Field
sb.AppendLine($" private readonly {adapteeTypeName} _adaptee;");
sb.AppendLine();
// Constructor
var isValueTypeAdaptee = adapteeType.IsValueType;
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// Initializes a new instance of the <see cref=\"{adapterTypeName}\"/> class.");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" /// <param name=\"adaptee\">The adaptee instance to delegate to.</param>");
if (!isValueTypeAdaptee)
{
sb.AppendLine($" /// <exception cref=\"global::System.ArgumentNullException\">Thrown when <paramref name=\"adaptee\"/> is null.</exception>");
}
sb.AppendLine($" public {adapterTypeName}({adapteeTypeName} adaptee)");
sb.AppendLine(" {");
if (isValueTypeAdaptee)
{
sb.AppendLine(" _adaptee = adaptee;");
}
else
{
sb.AppendLine(" _adaptee = adaptee ?? throw new global::System.ArgumentNullException(nameof(adaptee));");
}
sb.AppendLine(" }");
sb.AppendLine();
// Generate members
var isAbstractClassTarget = targetType.TypeKind == TypeKind.Class && targetType.IsAbstract;
foreach (var member in targetMembers)
{
if (memberMappings.TryGetValue(member, out var mapMethod))
{
GenerateMappedMember(sb, member, mapMethod, hostTypeName, isAbstractClassTarget);
}
else if (missingMapPolicy == AdapterMissingMapPolicyValue.ThrowingStub)
{
GenerateThrowingStub(sb, member, isAbstractClassTarget);
}
// Ignore policy: don't generate anything (will cause compile error if interface)
}
sb.AppendLine("}");
return sb.ToString();
}
private static void GenerateMappedMember(StringBuilder sb, ISymbol member, IMethodSymbol mapMethod, string hostTypeName, bool isAbstractClassTarget)
{
// Determine if we need 'override' keyword (for abstract class members)
var overrideKeyword = isAbstractClassTarget && member.IsAbstract ? "override " : "";
if (member is IMethodSymbol targetMethod)
{
// Generate method
var returnType = targetMethod.ReturnType.ToDisplayString(FullyQualifiedFormat);
var methodName = targetMethod.Name;
var parameters = string.Join(", ", targetMethod.Parameters.Select(p =>
$"{GetParameterModifiers(p)}{p.Type.ToDisplayString(FullyQualifiedFormat)} {p.Name}{GetDefaultValue(p)}"));
var parameterNames = string.Join(", ", targetMethod.Parameters.Select(p =>
$"{GetArgumentModifier(p)}{p.Name}"));
var isVoid = targetMethod.ReturnsVoid;
var callExpression = $"{hostTypeName}.{mapMethod.Name}(_adaptee{(string.IsNullOrEmpty(parameterNames) ? "" : ", " + parameterNames)})";
sb.AppendLine($" /// <inheritdoc/>");
sb.AppendLine($" public {overrideKeyword}{returnType} {methodName}({parameters})");
sb.AppendLine(" {");
if (isVoid)
{
sb.AppendLine($" {callExpression};");
}
else
{
sb.AppendLine($" return {callExpression};");
}
sb.AppendLine(" }");
sb.AppendLine();
}
else if (member is IPropertySymbol targetProp)
{
// Generate property
var propType = targetProp.Type.ToDisplayString(FullyQualifiedFormat);
var propName = targetProp.Name;
sb.AppendLine($" /// <inheritdoc/>");
sb.AppendLine($" public {overrideKeyword}{propType} {propName}");
sb.AppendLine(" {");
// Only read-only properties are supported (setters are caught by PKADP013)
if (targetProp.GetMethod is not null)
{
sb.AppendLine($" get => {hostTypeName}.{mapMethod.Name}(_adaptee);");
}
sb.AppendLine(" }");
sb.AppendLine();
}
}
private static void GenerateThrowingStub(StringBuilder sb, ISymbol member, bool isAbstractClassTarget)
{
var overrideKeyword = isAbstractClassTarget && member.IsAbstract ? "override " : "";
if (member is IMethodSymbol targetMethod)
{
var returnType = targetMethod.ReturnType.ToDisplayString(FullyQualifiedFormat);
var methodName = targetMethod.Name;
var parameters = string.Join(", ", targetMethod.Parameters.Select(p =>
$"{GetParameterModifiers(p)}{p.Type.ToDisplayString(FullyQualifiedFormat)} {p.Name}{GetDefaultValue(p)}"));
sb.AppendLine($" /// <inheritdoc/>");
sb.AppendLine($" /// <remarks>This member is not mapped and will throw <see cref=\"global::System.NotImplementedException\"/>.</remarks>");
sb.AppendLine($" public {overrideKeyword}{returnType} {methodName}({parameters})");
sb.AppendLine(" {");
sb.AppendLine($" throw new global::System.NotImplementedException(\"No [AdapterMap] provided for '{methodName}'.\");");
sb.AppendLine(" }");
sb.AppendLine();
}
else if (member is IPropertySymbol targetProp)
{
var propType = targetProp.Type.ToDisplayString(FullyQualifiedFormat);
var propName = targetProp.Name;
sb.AppendLine($" /// <inheritdoc/>");
sb.AppendLine($" /// <remarks>This property is not mapped and will throw <see cref=\"global::System.NotImplementedException\"/>.</remarks>");
sb.AppendLine($" public {overrideKeyword}{propType} {propName}");
sb.AppendLine(" {");
// Only read-only properties are supported (setters are caught by PKADP013)
if (targetProp.GetMethod is not null)
{
sb.AppendLine($" get => throw new global::System.NotImplementedException(\"No [AdapterMap] provided for '{propName}'.\");");
}
sb.AppendLine(" }");
sb.AppendLine();
}
}
private static string GetParameterModifiers(IParameterSymbol param)
{
return param.RefKind switch
{
RefKind.Ref => "ref ",
RefKind.Out => "out ",
RefKind.In => "in ",
RefKind.RefReadOnlyParameter => "ref readonly ",
_ => ""
};
}
private static string GetArgumentModifier(IParameterSymbol param)
{
return param.RefKind switch
{
RefKind.Ref => "ref ",
RefKind.Out => "out ",
RefKind.In => "in ",
RefKind.RefReadOnlyParameter => "in ",
_ => ""
};
}
private static string GetDefaultValue(IParameterSymbol param)
{
if (!param.HasExplicitDefaultValue)
return "";
var value = param.ExplicitDefaultValue;
if (value is null)
{
// For reference types or nullable value types, emit 'null'; otherwise, use 'default'
if (param.Type.IsReferenceType || param.NullableAnnotation == NullableAnnotation.Annotated)
return " = null";
return " = default";
}
var literal = SymbolDisplay.FormatPrimitive(value, quoteStrings: true, useHexadecimalNumbers: false);
return " = " + literal;
}
// Helper types
private enum AdapterMissingMapPolicyValue
{