-
-
Notifications
You must be signed in to change notification settings - Fork 784
Expand file tree
/
Copy pathParser.cs
More file actions
647 lines (564 loc) · 24.4 KB
/
Parser.cs
File metadata and controls
647 lines (564 loc) · 24.4 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
using System.Collections.Immutable;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Refit.Generator;
internal static class Parser
{
/// <summary>
/// Generates the interface stubs.
/// </summary>
/// <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>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns></returns>
public static (
List<Diagnostic> diagnostics,
ContextGenerationModel contextGenerationSpec
) GenerateInterfaceStubs(
CSharpCompilation compilation,
string? refitInternalNamespace,
ImmutableArray<MethodDeclarationSyntax> candidateMethods,
ImmutableArray<InterfaceDeclarationSyntax> candidateInterfaces,
CancellationToken cancellationToken
)
{
if (compilation == null)
throw new ArgumentNullException(nameof(compilation));
var wellKnownTypes = new WellKnownTypes(compilation);
refitInternalNamespace = $"{refitInternalNamespace ?? string.Empty}RefitInternalGenerated";
// Remove - as they are valid in csproj, but invalid in a namespace
refitInternalNamespace = refitInternalNamespace.Replace('-', '_').Replace('@', '_');
// 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 = wellKnownTypes.Get(typeof(IDisposable));
var httpMethodBaseAttributeSymbol = wellKnownTypes.TryGet(
"Refit.HttpMethodAttribute"
);
var diagnostics = new List<Diagnostic>();
if (httpMethodBaseAttributeSymbol == null)
{
diagnostics.Add(Diagnostic.Create(DiagnosticDescriptors.RefitNotReferenced, null));
return (
diagnostics,
new ContextGenerationModel(
refitInternalNamespace,
string.Empty,
ImmutableEquatableArray.Empty<InterfaceModel>()
)
);
}
// 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,
cancellationToken: cancellationToken
);
if (!IsRefitMethod(methodSymbol, httpMethodBaseAttributeSymbol))
continue;
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<
IGrouping<INamedTypeSymbol, IMethodSymbol>,
INamedTypeSymbol,
List<IMethodSymbol>
>(g => g.Key, v => [.. v], SymbolEqualityComparer.Default);
// 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,
cancellationToken: cancellationToken
);
// 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(m => IsRefitMethod(m, httpMethodBaseAttributeSymbol));
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;
}
}
}
cancellationToken.ThrowIfCancellationRequested();
// Bail out if there aren't any interfaces to generate code for. This may be the case with transitives
if (interfaces.Count == 0)
return (
diagnostics,
new ContextGenerationModel(
refitInternalNamespace,
string.Empty,
ImmutableEquatableArray.Empty<InterfaceModel>()
)
);
var supportsNullable = options.LanguageVersion >= LanguageVersion.CSharp8;
var keyCount = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
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
";
// TODO: Delete?
// Is it necessary to add the attributes to the compilation now, does it affect the users ide experience?
// Is it needed in order to get the preserve attribute display name.
// Will the compilation ever change this.
compilation = compilation.AddSyntaxTrees(
CSharpSyntaxTree.ParseText(
SourceText.From(attributeText, Encoding.UTF8),
options,
cancellationToken: cancellationToken
)
);
// get the newly bound attribute
var preserveAttributeSymbol = compilation.GetTypeByMetadataName(
$"{refitInternalNamespace}.PreserveAttribute"
)!;
var preserveAttributeDisplayName = preserveAttributeSymbol.ToDisplayString(
SymbolDisplayFormat.FullyQualifiedFormat
);
var interfaceModels = new List<InterfaceModel>();
// group the fields by interface and generate the source
foreach (var group in interfaces)
{
cancellationToken.ThrowIfCancellationRequested();
// 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 keyName = group.Key.Name;
int value;
while (keyCount.TryGetValue(keyName, out value))
{
keyName = $"{keyName}{++value}";
}
keyCount[keyName] = value;
var fileName = $"{keyName}.g.cs";
var interfaceModel = ProcessInterface(
fileName,
diagnostics,
group.Key,
group.Value,
preserveAttributeDisplayName,
disposableInterfaceSymbol,
httpMethodBaseAttributeSymbol,
supportsNullable,
interfaceToNullableEnabledMap[group.Key]
);
interfaceModels.Add(interfaceModel);
}
var contextGenerationSpec = new ContextGenerationModel(
refitInternalNamespace,
preserveAttributeDisplayName,
interfaceModels.ToImmutableEquatableArray()
);
return (diagnostics, contextGenerationSpec);
}
static InterfaceModel ProcessInterface(
string fileName,
List<Diagnostic> diagnostics,
INamedTypeSymbol interfaceSymbol,
List<IMethodSymbol> refitMethods,
string preserveAttributeDisplayName,
ISymbol disposableInterfaceSymbol,
INamedTypeSymbol httpMethodBaseAttributeSymbol,
bool supportsNullable,
bool nullableEnabled
)
{
// Get the class name with the type parameters, then remove the namespace
var className = interfaceSymbol.ToDisplayString();
var lastDot = className.LastIndexOf('.');
if (lastDot > 0)
{
className = className.Substring(lastDot + 1);
}
var classDeclaration = $"{interfaceSymbol.ContainingType?.Name}{className}";
// Get the class name itself
var classSuffix = $"{interfaceSymbol.ContainingType?.Name}{interfaceSymbol.Name}";
var ns = interfaceSymbol.ContainingNamespace?.ToDisplayString();
// if it's the global namespace, our lookup rules say it should be the same as the class name
if (interfaceSymbol.ContainingNamespace is { IsGlobalNamespace: true })
{
ns = string.Empty;
}
// Remove dots
ns = ns!.Replace(".", "");
var interfaceDisplayName = interfaceSymbol.ToDisplayString(
SymbolDisplayFormat.FullyQualifiedFormat
);
// Get any other methods on the refit interfaces. We'll need to generate something for them and warn
var nonRefitMethods = interfaceSymbol
.GetMembers()
.OfType<IMethodSymbol>()
.Except(refitMethods, SymbolEqualityComparer.Default)
.Cast<IMethodSymbol>()
.ToArray();
// get methods for all inherited
var derivedMethods = interfaceSymbol
.AllInterfaces.SelectMany(i => i.GetMembers().OfType<IMethodSymbol>())
.ToList();
// Look for disposable
var disposeMethod = derivedMethods.Find(
m =>
m.ContainingType?.Equals(disposableInterfaceSymbol, SymbolEqualityComparer.Default)
== true
);
if (disposeMethod != null)
{
//remove it from the derived methods list so we don't process it with the rest
derivedMethods.Remove(disposeMethod);
}
// Pull out the refit methods from the derived types
var derivedRefitMethods = derivedMethods
.Where(m => IsRefitMethod(m, httpMethodBaseAttributeSymbol))
.ToArray();
var derivedNonRefitMethods = derivedMethods
.Except(derivedRefitMethods, SymbolEqualityComparer.Default)
.Cast<IMethodSymbol>()
.ToArray();
// Exclude base interface methods that the current interface explicitly implements.
// This avoids false positive RF001 diagnostics for cases like:
// interface IFoo { int Bar(); } and interface IRemoteFoo : IFoo { [Get] abstract int IFoo.Bar(); }
if (derivedNonRefitMethods.Length > 0)
{
var explicitlyImplementedBaseMethods = new HashSet<IMethodSymbol>(
SymbolEqualityComparer.Default
);
foreach (var member in interfaceSymbol.GetMembers().OfType<IMethodSymbol>())
{
foreach (var baseMethod in member.ExplicitInterfaceImplementations)
{
// Use OriginalDefinition for robustness when comparing generic methods
explicitlyImplementedBaseMethods.Add(
baseMethod.OriginalDefinition ?? baseMethod
);
}
}
if (explicitlyImplementedBaseMethods.Count > 0)
{
derivedNonRefitMethods = derivedNonRefitMethods
.Where(m => !explicitlyImplementedBaseMethods.Contains(m.OriginalDefinition ?? m))
.ToArray();
}
}
var memberNames = interfaceSymbol
.GetMembers()
.Select(x => x.Name)
.Distinct()
.ToImmutableEquatableArray();
// Handle Refit Methods
var refitMethodsArray = refitMethods
.Select(m => ParseMethod(m, true))
.ToImmutableEquatableArray();
// Only include refit methods discovered on base interfaces here.
// Do NOT duplicate the current interface's refit methods.
var derivedRefitMethodsArray = derivedRefitMethods
.Select(m => ParseMethod(m, false))
.ToImmutableEquatableArray();
// Handle non-refit Methods that aren't static or properties or have a method body
var nonRefitMethodModelList = new List<MethodModel>();
foreach (var method in nonRefitMethods)
{
if (
method.IsStatic
|| method.MethodKind == MethodKind.PropertyGet
|| method.MethodKind == MethodKind.PropertySet
|| !method.IsAbstract
)
continue;
nonRefitMethodModelList.Add(ParseNonRefitMethod(method, diagnostics, isDerived: false));
}
foreach (var method in derivedNonRefitMethods)
{
if (
method.IsStatic
|| method.MethodKind == MethodKind.PropertyGet
|| method.MethodKind == MethodKind.PropertySet
|| !method.IsAbstract
)
continue;
// Derived non-refit methods should be emitted as explicit interface implementations
nonRefitMethodModelList.Add(ParseNonRefitMethod(method, diagnostics, isDerived: true));
}
var nonRefitMethodModels = nonRefitMethodModelList.ToImmutableEquatableArray();
var constraints = GenerateConstraints(interfaceSymbol.TypeParameters, false);
var hasDispose = disposeMethod != null;
var nullability = (supportsNullable, nullableEnabled) switch
{
(false, _) => Nullability.None,
(true, true) => Nullability.Enabled,
(true, false) => Nullability.Disabled,
};
return new InterfaceModel(
preserveAttributeDisplayName,
fileName,
className,
ns,
classDeclaration,
interfaceDisplayName,
classSuffix,
constraints,
memberNames,
nonRefitMethodModels,
refitMethodsArray,
derivedRefitMethodsArray,
nullability,
hasDispose
);
}
private static MethodModel ParseNonRefitMethod(
IMethodSymbol methodSymbol,
List<Diagnostic> diagnostics,
bool isDerived
)
{
// report invalid error diagnostic
foreach (var location in methodSymbol.Locations)
{
var diagnostic = Diagnostic.Create(
DiagnosticDescriptors.InvalidRefitMember,
location,
methodSymbol.ContainingType.Name,
methodSymbol.Name
);
diagnostics.Add(diagnostic);
}
// Parse like a regular method, but force explicit implementation for derived base-interface methods
var explicitImpl = methodSymbol.ExplicitInterfaceImplementations.FirstOrDefault();
var containingTypeSymbol = explicitImpl?.ContainingType ?? methodSymbol.ContainingType;
var containingType = containingTypeSymbol.ToDisplayString(
SymbolDisplayFormat.FullyQualifiedFormat
);
// Method name should be simple name only (never include interface qualifier)
var declaredBaseName = methodSymbol.Name;
var lastDot = declaredBaseName.LastIndexOf('.');
if (lastDot >= 0)
{
declaredBaseName = declaredBaseName.Substring(lastDot + 1);
}
if (methodSymbol.TypeParameters.Length > 0)
{
var typeParams = string.Join(
", ",
methodSymbol.TypeParameters.Select(
tp => tp.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
)
);
declaredBaseName += $"<{typeParams}>";
}
var returnType = methodSymbol.ReturnType.ToDisplayString(
SymbolDisplayFormat.FullyQualifiedFormat
);
var returnTypeInfo = methodSymbol.ReturnType.MetadataName switch
{
"Task" => ReturnTypeInfo.AsyncVoid,
"Task`1" or "ValueTask`1" => ReturnTypeInfo.AsyncResult,
"Void" => ReturnTypeInfo.SyncVoid,
_ => ReturnTypeInfo.Return,
};
var parameters = methodSymbol.Parameters.Select(ParseParameter).ToImmutableEquatableArray();
var isExplicit = isDerived || explicitImpl is not null;
var constraints = GenerateConstraints(methodSymbol.TypeParameters, isExplicit);
return new MethodModel(
methodSymbol.Name,
returnType,
containingType,
declaredBaseName,
returnTypeInfo,
parameters,
constraints,
isExplicit
);
}
private static bool IsRefitMethod(
IMethodSymbol? methodSymbol,
INamedTypeSymbol httpMethodAttribute
)
{
return methodSymbol
?.GetAttributes()
.Any(ad => ad.AttributeClass?.InheritsFromOrEquals(httpMethodAttribute) == true)
== true;
}
private static ImmutableEquatableArray<TypeConstraint> GenerateConstraints(
ImmutableArray<ITypeParameterSymbol> typeParameters,
bool isOverrideOrExplicitImplementation
)
{
// Need to loop over the constraints and create them
return typeParameters
.Select(
typeParameter =>
ParseConstraintsForTypeParameter(
typeParameter,
isOverrideOrExplicitImplementation
)
)
.ToImmutableEquatableArray();
}
private static TypeConstraint ParseConstraintsForTypeParameter(
ITypeParameterSymbol typeParameter,
bool isOverrideOrExplicitImplementation
)
{
// Explicit interface implementations and overrides can only have class or struct constraints
var known = KnownTypeConstraint.None;
if (typeParameter.HasReferenceTypeConstraint)
{
known |= KnownTypeConstraint.Class;
}
if (typeParameter.HasUnmanagedTypeConstraint && !isOverrideOrExplicitImplementation)
{
known |= KnownTypeConstraint.Unmanaged;
}
// unmanaged constraints are both structs and unmanaged so the struct constraint is redundant
if (typeParameter.HasValueTypeConstraint && !typeParameter.HasUnmanagedTypeConstraint)
{
known |= KnownTypeConstraint.Struct;
}
if (typeParameter.HasNotNullConstraint && !isOverrideOrExplicitImplementation)
{
known |= KnownTypeConstraint.NotNull;
}
var constraints = ImmutableEquatableArray<string>.Empty;
if (!isOverrideOrExplicitImplementation)
{
constraints = typeParameter
.ConstraintTypes.Select(
typeConstraint =>
typeConstraint.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
)
.ToImmutableEquatableArray();
}
// new constraint has to be last
if (typeParameter.HasConstructorConstraint && !isOverrideOrExplicitImplementation)
{
known |= KnownTypeConstraint.New;
}
var declaredName = typeParameter.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
return new TypeConstraint(typeParameter.Name, declaredName, known, constraints);
}
private static ParameterModel ParseParameter(IParameterSymbol param)
{
var annotation =
!param.Type.IsValueType && param.NullableAnnotation == NullableAnnotation.Annotated;
var paramType = param.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
var isGeneric = ContainsTypeParameter(param.Type);
return new ParameterModel(param.MetadataName, paramType, annotation, isGeneric);
}
private 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;
}
private static MethodModel ParseMethod(IMethodSymbol methodSymbol, bool isImplicitInterface)
{
var returnType = methodSymbol.ReturnType.ToDisplayString(
SymbolDisplayFormat.FullyQualifiedFormat
);
// For explicit interface implementations, the containing type for the explicit method signature
// must be the interface being implemented (e.g. IFoo), not the interface that declares it.
var explicitImpl = methodSymbol.ExplicitInterfaceImplementations.FirstOrDefault();
var containingTypeSymbol = explicitImpl?.ContainingType ?? methodSymbol.ContainingType;
var containingType = containingTypeSymbol.ToDisplayString(
SymbolDisplayFormat.FullyQualifiedFormat
);
// Simple method name (strip any explicit interface qualifier if present)
var declaredBaseName = methodSymbol.Name;
var lastDot = declaredBaseName.LastIndexOf('.');
if (lastDot >= 0)
{
declaredBaseName = declaredBaseName.Substring(lastDot + 1);
}
if (methodSymbol.TypeParameters.Length > 0)
{
var typeParams = string.Join(
", ",
methodSymbol.TypeParameters.Select(
tp => tp.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
)
);
declaredBaseName += $"<{typeParams}>";
}
var returnTypeInfo = methodSymbol.ReturnType.MetadataName switch
{
"Task" => ReturnTypeInfo.AsyncVoid,
"Task`1" or "ValueTask`1" => ReturnTypeInfo.AsyncResult,
"Void" => ReturnTypeInfo.SyncVoid,
_ => ReturnTypeInfo.Return,
};
var parameters = methodSymbol.Parameters.Select(ParseParameter).ToImmutableEquatableArray();
var isExplicit = explicitImpl is not null;
var constraints = GenerateConstraints(methodSymbol.TypeParameters, isExplicit || !isImplicitInterface);
return new MethodModel(
methodSymbol.Name,
returnType,
containingType,
declaredBaseName,
returnTypeInfo,
parameters,
constraints,
isExplicit
);
}
}