-
-
Notifications
You must be signed in to change notification settings - Fork 782
Expand file tree
/
Copy pathInterfaceStubGenerator.cs
More file actions
827 lines (717 loc) · 31 KB
/
InterfaceStubGenerator.cs
File metadata and controls
827 lines (717 loc) · 31 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
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Refit.Generator
{
// * Search for all Interfaces, find the method definitions
// and make sure there's at least one Refit attribute on one
// * Generate the data we need for the template based on interface method
// defn's
/// <summary>
/// InterfaceStubGeneratorV2.
/// </summary>
[Generator]
#if ROSLYN_4
public class InterfaceStubGeneratorV2 : IIncrementalGenerator
#else
public class InterfaceStubGenerator : ISourceGenerator
#endif
{
private const string TypeParameterVariableName = "______typeParameters";
#pragma warning disable RS2008 // Enable analyzer release tracking
static readonly DiagnosticDescriptor InvalidRefitMember =
new(
"RF001",
"Refit types must have Refit HTTP method attributes",
"Method {0}.{1} either has no Refit HTTP method attribute or you've used something other than a string literal for the 'path' argument",
"Refit",
DiagnosticSeverity.Warning,
true
);
static readonly DiagnosticDescriptor RefitNotReferenced =
new(
"RF002",
"Refit must be referenced",
"Refit is not referenced. Add a reference to Refit.",
"Refit",
DiagnosticSeverity.Error,
true
);
#pragma warning restore RS2008 // Enable analyzer release tracking
#if !ROSLYN_4
/// <summary>
/// Executes the specified context.
/// </summary>
/// <param name="context">The context.</param>
public void Execute(GeneratorExecutionContext context)
{
if (context.SyntaxReceiver is not SyntaxReceiver receiver)
return;
context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(
"build_property.RefitInternalNamespace",
out var refitInternalNamespace
);
GenerateInterfaceStubs(
context,
static (context, diagnostic) => context.ReportDiagnostic(diagnostic),
static (context, hintName, sourceText) => context.AddSource(hintName, sourceText),
(CSharpCompilation)context.Compilation,
refitInternalNamespace,
receiver.CandidateMethods.ToImmutableArray(),
receiver.CandidateInterfaces.ToImmutableArray()
);
}
#endif
/// <summary>
/// Generates the interface stubs.
/// </summary>
/// <typeparam name="TContext">The type of the context.</typeparam>
/// <param name="context">The context.</param>
/// <param name="reportDiagnostic">The report diagnostic.</param>
/// <param name="addSource">The add source.</param>
/// <param name="compilation">The compilation.</param>
/// <param name="refitInternalNamespace">The refit internal namespace.</param>
/// <param name="candidateMethods">The candidate methods.</param>
/// <param name="candidateInterfaces">The candidate interfaces.</param>
/// <returns></returns>
public void GenerateInterfaceStubs<TContext>(
TContext context,
Action<TContext, Diagnostic> reportDiagnostic,
Action<TContext, string, SourceText> addSource,
CSharpCompilation compilation,
string? refitInternalNamespace,
ImmutableArray<MethodDeclarationSyntax> candidateMethods,
ImmutableArray<InterfaceDeclarationSyntax> candidateInterfaces
)
{
refitInternalNamespace =
$"{refitInternalNamespace ?? string.Empty}RefitInternalGenerated";
// we're going to create a new compilation that contains the attribute.
// TODO: we should allow source generators to provide source during initialize, so that this step isn't required.
var options = (CSharpParseOptions)compilation.SyntaxTrees[0].Options;
var disposableInterfaceSymbol = compilation.GetTypeByMetadataName(
"System.IDisposable"
)!;
var httpMethodBaseAttributeSymbol = compilation.GetTypeByMetadataName(
"Refit.HttpMethodAttribute"
);
if (httpMethodBaseAttributeSymbol == null)
{
reportDiagnostic(context, Diagnostic.Create(RefitNotReferenced, null));
return;
}
var refitMetadata = new RefitMetadata(disposableInterfaceSymbol, httpMethodBaseAttributeSymbol);
// Check the candidates and keep the ones we're actually interested in
#pragma warning disable RS1024 // Compare symbols correctly
var interfaceToNullableEnabledMap = new Dictionary<INamedTypeSymbol, bool>(
SymbolEqualityComparer.Default
);
#pragma warning restore RS1024 // Compare symbols correctly
var methodSymbols = new List<IMethodSymbol>();
foreach (var group in candidateMethods.GroupBy(m => m.SyntaxTree))
{
var model = compilation.GetSemanticModel(group.Key);
foreach (var method in group)
{
// Get the symbol being declared by the method
var methodSymbol = model.GetDeclaredSymbol(method);
if (refitMetadata.IsRefitMethod(methodSymbol))
{
var isAnnotated =
compilation.Options.NullableContextOptions
== NullableContextOptions.Enable
|| model.GetNullableContext(method.SpanStart)
== NullableContext.Enabled;
interfaceToNullableEnabledMap[methodSymbol!.ContainingType] = isAnnotated;
methodSymbols.Add(methodSymbol!);
}
}
}
var interfaces = methodSymbols
.GroupBy<IMethodSymbol, INamedTypeSymbol>(
m => m.ContainingType,
SymbolEqualityComparer.Default
)
.ToDictionary(g => g.Key, v => v.ToList());
// Look through the candidate interfaces
var interfaceSymbols = new List<INamedTypeSymbol>();
foreach (var group in candidateInterfaces.GroupBy(i => i.SyntaxTree))
{
var model = compilation.GetSemanticModel(group.Key);
foreach (var iface in group)
{
// get the symbol belonging to the interface
var ifaceSymbol = model.GetDeclaredSymbol(iface);
// See if we already know about it, might be a dup
if (ifaceSymbol is null || interfaces.ContainsKey(ifaceSymbol))
continue;
// The interface has no refit methods, but its base interfaces might
var hasDerivedRefit = ifaceSymbol.AllInterfaces
.SelectMany(i => i.GetMembers().OfType<IMethodSymbol>())
.Any(refitMetadata.IsRefitMethod);
if (hasDerivedRefit)
{
// Add the interface to the generation list with an empty set of methods
// The logic already looks for base refit methods
interfaces.Add(ifaceSymbol, []);
var isAnnotated =
model.GetNullableContext(iface.SpanStart) == NullableContext.Enabled;
interfaceToNullableEnabledMap[ifaceSymbol] = isAnnotated;
}
}
}
// Bail out if there aren't any interfaces to generate code for. This may be the case with transitives
if (interfaces.Count == 0)
return;
var supportsNullable = options.LanguageVersion >= LanguageVersion.CSharp8;
var keyCount = new Dictionary<string, int>();
var attributeText =
@$"
#pragma warning disable
namespace {refitInternalNamespace}
{{
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
[global::System.AttributeUsage (global::System.AttributeTargets.Class | global::System.AttributeTargets.Struct | global::System.AttributeTargets.Enum | global::System.AttributeTargets.Constructor | global::System.AttributeTargets.Method | global::System.AttributeTargets.Property | global::System.AttributeTargets.Field | global::System.AttributeTargets.Event | global::System.AttributeTargets.Interface | global::System.AttributeTargets.Delegate)]
sealed class PreserveAttribute : global::System.Attribute
{{
//
// Fields
//
public bool AllMembers;
public bool Conditional;
}}
}}
#pragma warning restore
";
compilation = compilation.AddSyntaxTrees(
CSharpSyntaxTree.ParseText(SourceText.From(attributeText, Encoding.UTF8), options)
);
// add the attribute text
addSource(
context,
"PreserveAttribute.g.cs",
SourceText.From(attributeText, Encoding.UTF8)
);
// get the newly bound attribute
var preserveAttributeSymbol = compilation.GetTypeByMetadataName(
$"{refitInternalNamespace}.PreserveAttribute"
)!;
var generatedClassText =
@$"
#pragma warning disable
namespace Refit.Implementation
{{
/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
[{preserveAttributeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}]
[global::System.Reflection.Obfuscation(Exclude=true)]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal static partial class Generated
{{
#if NET5_0_OR_GREATER
[System.Runtime.CompilerServices.ModuleInitializer]
[System.Diagnostics.CodeAnalysis.DynamicDependency(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All, typeof(global::Refit.Implementation.Generated))]
public static void Initialize()
{{
}}
#endif
}}
}}
#pragma warning restore
";
addSource(
context,
"Generated.g.cs",
SourceText.From(generatedClassText, Encoding.UTF8)
);
compilation = compilation.AddSyntaxTrees(
CSharpSyntaxTree.ParseText(
SourceText.From(generatedClassText, Encoding.UTF8),
options
)
);
// group the fields by interface and generate the source
foreach (var group in interfaces)
{
// each group is keyed by the Interface INamedTypeSymbol and contains the members
// with a refit attribute on them. Types may contain other members, without the attribute, which we'll
// need to check for and error out on
var model = new RefitClientModel(group.Key, group.Value, refitMetadata);
var classSource = ProcessInterface(context,
reportDiagnostic,
model,
preserveAttributeSymbol,
supportsNullable,
interfaceToNullableEnabledMap[model.RefitInterface]);
var keyName = model.FileName;
int value;
while (keyCount.TryGetValue(keyName, out value))
{
keyName = $"{keyName}{++value}";
}
keyCount[keyName] = value;
addSource(context, $"{keyName}.g.cs", SourceText.From(classSource, Encoding.UTF8));
}
}
static string ProcessInterface<TContext>(
TContext context,
Action<TContext, Diagnostic> reportDiagnostic,
RefitClientModel interfaceModel,
ISymbol preserveAttributeSymbol,
bool supportsNullable,
bool nullableEnabled
)
{
INamedTypeSymbol interfaceSymbol = interfaceModel.RefitInterface;
List<IMethodSymbol> refitMethods = interfaceModel.RefitMethods;
// See what the nullable context is
var source = new StringBuilder();
if (supportsNullable)
{
source.Append("#nullable ");
if (nullableEnabled)
{
source.Append("enable");
}
else
{
source.Append("disable");
}
}
source.Append(
$@"
#pragma warning disable
namespace Refit.Implementation
{{
partial class Generated
{{
/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
[{preserveAttributeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}]
[global::System.Reflection.Obfuscation(Exclude=true)]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
partial class {interfaceModel.NamespacePrefix}{interfaceModel.ClassDeclaration}
: {interfaceModel.BaseInterfaceDeclaration}{GenerateConstraints(interfaceSymbol.TypeParameters, false)}
{{
/// <inheritdoc />
public global::System.Net.Http.HttpClient Client {{ get; }}
readonly global::Refit.IRequestBuilder requestBuilder;
/// <inheritdoc />
public {interfaceModel.NamespacePrefix}{interfaceModel.ClassSuffix}(global::System.Net.Http.HttpClient client, global::Refit.IRequestBuilder requestBuilder)
{{
Client = client;
this.requestBuilder = requestBuilder;
}}
");
var memberNames = new HashSet<string>(interfaceSymbol.GetMembers().Select(x => x.Name));
// Handle Refit Methods
foreach (var method in refitMethods)
{
ProcessRefitMethod(source, method, true, memberNames);
}
foreach (var method in interfaceModel.AllRefitMethods)
{
ProcessRefitMethod(source, method, false, memberNames);
}
// Handle non-refit Methods that aren't static or properties or have a method body
foreach (var method in interfaceModel.NonRefitMethods)
{
ProcessNonRefitMethod(context, reportDiagnostic, source, method);
}
// Handle Dispose
if (interfaceModel.DisposeMethod != null)
{
ProcessDisposableMethod(source, interfaceModel.DisposeMethod);
}
source.Append(
@"
}
}
}
#pragma warning restore
"
);
return source.ToString();
}
/// <summary>
/// Generates the body of the Refit method
/// </summary>
/// <param name="source"></param>
/// <param name="methodSymbol"></param>
/// <param name="isTopLevel">True if directly from the type we're generating for, false for methods found on base interfaces</param>
/// <param name="memberNames">Contains the unique member names in the interface scope.</param>
static void ProcessRefitMethod(
StringBuilder source,
IMethodSymbol methodSymbol,
bool isTopLevel,
HashSet<string> memberNames
)
{
var parameterTypesExpression = GenerateTypeParameterExpression(
source,
methodSymbol,
memberNames
);
var returnType = methodSymbol.ReturnType.ToDisplayString(
SymbolDisplayFormat.FullyQualifiedFormat
);
var (isAsync, @return, configureAwait) = methodSymbol.ReturnType.MetadataName switch
{
"Task" => (true, "await (", ").ConfigureAwait(false)"),
"Task`1" or "ValueTask`1" => (true, "return await (", ").ConfigureAwait(false)"),
_ => (false, "return ", ""),
};
WriteMethodOpening(source, methodSymbol, !isTopLevel, isAsync);
// Build the list of args for the array
var argList = new List<string>();
foreach (var param in methodSymbol.Parameters)
{
argList.Add($"@{param.MetadataName}");
}
// List of generic arguments
var genericList = new List<string>();
foreach (var typeParam in methodSymbol.TypeParameters)
{
genericList.Add(
$"typeof({typeParam.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)})"
);
}
var argumentsArrayString =
argList.Count == 0
? "global::System.Array.Empty<object>()"
: $"new object[] {{ {string.Join(", ", argList)} }}";
var genericString =
genericList.Count > 0
? $", new global::System.Type[] {{ {string.Join(", ", genericList)} }}"
: string.Empty;
source.Append(
@$"
var ______arguments = {argumentsArrayString};
var ______func = requestBuilder.BuildRestResultFuncForMethod(""{methodSymbol.Name}"", {parameterTypesExpression}{genericString} );
try
{{
{@return}({returnType})______func(this.Client, ______arguments){configureAwait};
}}
catch (global::System.Exception ______ex)
{{
throw ______ex;
}}
"
);
WriteMethodClosing(source);
}
static void ProcessDisposableMethod(StringBuilder source, IMethodSymbol methodSymbol)
{
WriteMethodOpening(source, methodSymbol, true);
source.Append(
@"
Client?.Dispose();
"
);
WriteMethodClosing(source);
}
static string GenerateConstraints(
ImmutableArray<ITypeParameterSymbol> typeParameters,
bool isOverrideOrExplicitImplementation
)
{
var source = new StringBuilder();
// Need to loop over the constraints and create them
foreach (var typeParameter in typeParameters)
{
WriteConstraitsForTypeParameter(
source,
typeParameter,
isOverrideOrExplicitImplementation
);
}
return source.ToString();
}
static void WriteConstraitsForTypeParameter(
StringBuilder source,
ITypeParameterSymbol typeParameter,
bool isOverrideOrExplicitImplementation
)
{
// Explicit interface implementations and overrides can only have class or struct constraints
var parameters = new List<string>();
if (typeParameter.HasReferenceTypeConstraint)
{
parameters.Add("class");
}
if (typeParameter.HasUnmanagedTypeConstraint && !isOverrideOrExplicitImplementation)
{
parameters.Add("unmanaged");
}
if (typeParameter.HasValueTypeConstraint)
{
parameters.Add("struct");
}
if (typeParameter.HasNotNullConstraint && !isOverrideOrExplicitImplementation)
{
parameters.Add("notnull");
}
if (!isOverrideOrExplicitImplementation)
{
foreach (var typeConstraint in typeParameter.ConstraintTypes)
{
parameters.Add(
typeConstraint.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
);
}
}
// new constraint has to be last
if (typeParameter.HasConstructorConstraint && !isOverrideOrExplicitImplementation)
{
parameters.Add("new()");
}
if (parameters.Count > 0)
{
source.Append(
@$"
where {typeParameter.Name} : {string.Join(", ", parameters)}"
);
}
}
static void ProcessNonRefitMethod<TContext>(
TContext context,
Action<TContext, Diagnostic> reportDiagnostic,
StringBuilder source,
IMethodSymbol methodSymbol
)
{
WriteMethodOpening(source, methodSymbol, true);
source.Append(
@"
throw new global::System.NotImplementedException(""Either this method has no Refit HTTP method attribute or you've used something other than a string literal for the 'path' argument."");
"
);
WriteMethodClosing(source);
foreach (var location in methodSymbol.Locations)
{
var diagnostic = Diagnostic.Create(
InvalidRefitMember,
location,
methodSymbol.ContainingType.Name,
methodSymbol.Name
);
reportDiagnostic(context, diagnostic);
}
}
static string GenerateTypeParameterExpression(
StringBuilder source,
IMethodSymbol methodSymbol,
HashSet<string> memberNames
)
{
// use Array.Empty if method has no parameters.
if (methodSymbol.Parameters.Length == 0)
return "global::System.Array.Empty<global::System.Type>()";
// if one of the parameters is/contains a type parameter then it cannot be cached as it will change type between calls.
if (methodSymbol.Parameters.Any(x => ContainsTypeParameter(x.Type)))
{
var typeEnumerable = methodSymbol.Parameters.Select(
param =>
$"typeof({param.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)})"
);
return $"new global::System.Type[] {{ {string.Join(", ", typeEnumerable)} }}";
}
// find a name and generate field declaration.
var typeParameterFieldName = UniqueName(TypeParameterVariableName, memberNames);
var types = string.Join(
", ",
methodSymbol.Parameters.Select(
x =>
$"typeof({x.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)})"
)
);
source.Append(
$$"""
private static readonly global::System.Type[] {{typeParameterFieldName}} = new global::System.Type[] {{{types}} };
"""
);
return typeParameterFieldName;
static bool ContainsTypeParameter(ITypeSymbol symbol)
{
if (symbol is ITypeParameterSymbol)
return true;
if (symbol is not INamedTypeSymbol { TypeParameters.Length: > 0 } namedType)
return false;
foreach (var typeArg in namedType.TypeArguments)
{
if (ContainsTypeParameter(typeArg))
return true;
}
return false;
}
}
static void WriteMethodOpening(
StringBuilder source,
IMethodSymbol methodSymbol,
bool isExplicitInterface,
bool isAsync = false
)
{
var visibility = !isExplicitInterface ? "public " : string.Empty;
var async = isAsync ? "async " : "";
source.Append(
@$"
/// <inheritdoc />
{visibility}{async}{methodSymbol.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)} "
);
if (isExplicitInterface)
{
source.Append(
@$"{methodSymbol.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}."
);
}
source.Append(
@$"{methodSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}("
);
if (methodSymbol.Parameters.Length > 0)
{
var list = new List<string>();
foreach (var param in methodSymbol.Parameters)
{
var annotation =
!param.Type.IsValueType
&& param.NullableAnnotation == NullableAnnotation.Annotated;
list.Add(
$@"{param.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}{(annotation ? '?' : string.Empty)} @{param.MetadataName}"
);
}
source.Append(string.Join(", ", list));
}
source.Append(
@$"){GenerateConstraints(methodSymbol.TypeParameters, isExplicitInterface)}
{{"
);
}
static void WriteMethodClosing(StringBuilder source) => source.Append(@" }");
static string UniqueName(string name, HashSet<string> methodNames)
{
var candidateName = name;
var counter = 0;
while (methodNames.Contains(candidateName))
{
candidateName = $"{name}{counter}";
counter++;
}
methodNames.Add(candidateName);
return candidateName;
}
#if ROSLYN_4
/// <summary>
/// Initializes the specified context.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// We're looking for methods with an attribute that are in an interface
var candidateMethodsProvider = context.SyntaxProvider.CreateSyntaxProvider(
(syntax, cancellationToken) =>
syntax
is MethodDeclarationSyntax
{
Parent: InterfaceDeclarationSyntax,
AttributeLists.Count: > 0
},
(context, cancellationToken) => (MethodDeclarationSyntax)context.Node
);
// We also look for interfaces that derive from others, so we can see if any base methods contain
// Refit methods
var candidateInterfacesProvider = context.SyntaxProvider.CreateSyntaxProvider(
(syntax, cancellationToken) =>
syntax is InterfaceDeclarationSyntax { BaseList: not null },
(context, cancellationToken) => (InterfaceDeclarationSyntax)context.Node
);
var refitInternalNamespace = context.AnalyzerConfigOptionsProvider.Select(
(analyzerConfigOptionsProvider, cancellationToken) =>
analyzerConfigOptionsProvider.GlobalOptions.TryGetValue(
"build_property.RefitInternalNamespace",
out var refitInternalNamespace
)
? refitInternalNamespace
: null
);
var inputs = candidateMethodsProvider
.Collect()
.Combine(candidateInterfacesProvider.Collect())
.Select(
(combined, cancellationToken) =>
(candidateMethods: combined.Left, candidateInterfaces: combined.Right)
)
.Combine(refitInternalNamespace)
.Combine(context.CompilationProvider)
.Select(
(combined, cancellationToken) =>
(
combined.Left.Left.candidateMethods,
combined.Left.Left.candidateInterfaces,
refitInternalNamespace: combined.Left.Right,
compilation: combined.Right
)
);
context.RegisterSourceOutput(
inputs,
(context, collectedValues) =>
{
GenerateInterfaceStubs(
context,
static (context, diagnostic) => context.ReportDiagnostic(diagnostic),
static (context, hintName, sourceText) =>
context.AddSource(hintName, sourceText),
(CSharpCompilation)collectedValues.compilation,
collectedValues.refitInternalNamespace,
collectedValues.candidateMethods,
collectedValues.candidateInterfaces
);
}
);
}
#else
/// <summary>
/// Initializes the specified context.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
}
class SyntaxReceiver : ISyntaxReceiver
{
public List<MethodDeclarationSyntax> CandidateMethods { get; } = new();
public List<InterfaceDeclarationSyntax> CandidateInterfaces { get; } = new();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
// We're looking for methods with an attribute that are in an interfaces
if (
syntaxNode is MethodDeclarationSyntax methodDeclarationSyntax
&& methodDeclarationSyntax.Parent is InterfaceDeclarationSyntax
&& methodDeclarationSyntax.AttributeLists.Count > 0
)
{
CandidateMethods.Add(methodDeclarationSyntax);
}
// We also look for interfaces that derive from others, so we can see if any base methods contain
// Refit methods
if (syntaxNode is InterfaceDeclarationSyntax iface && iface.BaseList is not null)
{
CandidateInterfaces.Add(iface);
}
}
}
#endif
}
}