-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathXmlCommentGenerator.Emitter.cs
603 lines (555 loc) · 24.1 KB
/
XmlCommentGenerator.Emitter.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.AspNetCore.OpenApi.SourceGenerators.Xml;
using System.Threading;
namespace Microsoft.AspNetCore.OpenApi.SourceGenerators;
public sealed partial class XmlCommentGenerator : IIncrementalGenerator
{
public static string GeneratedCodeConstructor => $@"System.CodeDom.Compiler.GeneratedCodeAttribute(""{typeof(XmlCommentGenerator).Assembly.FullName}"", ""{typeof(XmlCommentGenerator).Assembly.GetName().Version}"")";
public static string GeneratedCodeAttribute => $"[{GeneratedCodeConstructor}]";
internal static string GenerateXmlCommentSupportSource(string commentsFromXmlFile, string? commentsFromCompilation, ImmutableArray<(AddOpenApiInvocation Source, int Index, ImmutableArray<InterceptableLocation?> Elements)> groupedAddOpenApiInvocations) => $$"""
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#nullable enable
// Suppress warnings about obsolete types and members
// in generated code
#pragma warning disable CS0612, CS0618
namespace System.Runtime.CompilerServices
{
{{GeneratedCodeAttribute}}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
file sealed class InterceptsLocationAttribute : System.Attribute
{
public InterceptsLocationAttribute(int version, string data)
{
}
}
}
namespace Microsoft.AspNetCore.OpenApi.Generated
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Models.References;
using Microsoft.OpenApi.Any;
{{GeneratedCodeAttribute}}
file record XmlComment(
string? Summary,
string? Description,
string? Remarks,
string? Returns,
string? Value,
bool Deprecated,
List<string>? Examples,
List<XmlParameterComment>? Parameters,
List<XmlResponseComment>? Responses);
{{GeneratedCodeAttribute}}
file record XmlParameterComment(string? Name, string? Description, string? Example, bool Deprecated);
{{GeneratedCodeAttribute}}
file record XmlResponseComment(string Code, string? Description, string? Example);
{{GeneratedCodeAttribute}}
file static class XmlCommentCache
{
private static Dictionary<string, XmlComment>? _cache;
public static Dictionary<string, XmlComment> Cache => _cache ??= GenerateCacheEntries();
private static Dictionary<string, XmlComment> GenerateCacheEntries()
{
var _cache = new Dictionary<string, XmlComment>();
{{commentsFromXmlFile}}
{{commentsFromCompilation}}
return _cache;
}
}
file static class DocumentationCommentIdHelper
{
/// <summary>
/// Generates a documentation comment ID for a type.
/// Example: T:Namespace.Outer+Inner`1 becomes T:Namespace.Outer.Inner`1
/// </summary>
public static string CreateDocumentationId(this Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
return "T:" + GetTypeDocId(type, includeGenericArguments: false, omitGenericArity: false);
}
/// <summary>
/// Generates a documentation comment ID for a property.
/// Example: P:Namespace.ContainingType.PropertyName or for an indexer P:Namespace.ContainingType.Item(System.Int32)
/// </summary>
public static string CreateDocumentationId(this PropertyInfo property)
{
if (property == null)
{
throw new ArgumentNullException(nameof(property));
}
var sb = new StringBuilder();
sb.Append("P:");
if (property.DeclaringType != null)
{
sb.Append(GetTypeDocId(property.DeclaringType, includeGenericArguments: false, omitGenericArity: false));
}
sb.Append('.');
sb.Append(property.Name);
// For indexers, include the parameter list.
var indexParams = property.GetIndexParameters();
if (indexParams.Length > 0)
{
sb.Append('(');
sb.Append(string.Join(",", indexParams.Select(p => GetTypeDocId(p.ParameterType, includeGenericArguments: true, omitGenericArity: false))));
sb.Append(')');
}
return sb.ToString();
}
/// <summary>
/// Generates a documentation comment ID for a method (or constructor).
/// For example:
/// M:Namespace.ContainingType.MethodName(ParamType1,ParamType2)~ReturnType
/// M:Namespace.ContainingType.#ctor(ParamType)
/// </summary>
public static string CreateDocumentationId(this MethodInfo method)
{
System.Diagnostics.Debugger.Break();
if (method == null)
{
throw new ArgumentNullException(nameof(method));
}
var sb = new StringBuilder();
sb.Append("M:");
// Append the fully qualified name of the declaring type.
if (method.DeclaringType != null)
{
sb.Append(GetTypeDocId(method.DeclaringType, includeGenericArguments: false, omitGenericArity: false));
}
sb.Append('.');
// Append the method name, handling constructors specially.
if (method.IsConstructor)
{
sb.Append(method.IsStatic ? "#cctor" : "#ctor");
}
else
{
sb.Append(method.Name);
if (method.IsGenericMethod)
{
sb.Append("``");
sb.Append(method.GetGenericArguments().Length);
}
}
// Append the parameter list, if any.
var parameters = method.GetParameters();
if (parameters.Length > 0)
{
sb.Append('(');
sb.Append(string.Join(",", parameters.Select(p => GetTypeDocId(p.ParameterType, includeGenericArguments: true, omitGenericArity: true))));
sb.Append(')');
}
// Append the return type after a '~' (if the method returns a value).
if (method.ReturnType != typeof(void))
{
sb.Append('~');
// Omit the generic arity for the return type.
sb.Append(GetTypeDocId(method.ReturnType, includeGenericArguments: true, omitGenericArity: true));
}
return sb.ToString();
}
/// <summary>
/// Generates a documentation ID string for a type.
/// This method handles nested types (replacing '+' with '.'),
/// generic types, arrays, pointers, by-ref types, and generic parameters.
/// The <paramref name="includeGenericArguments"/> flag controls whether
/// constructed generic type arguments are emitted, while <paramref name="omitGenericArity"/>
/// controls whether the generic arity marker (e.g. "`1") is appended.
/// </summary>
private static string GetTypeDocId(Type type, bool includeGenericArguments, bool omitGenericArity)
{
if (type.IsGenericParameter)
{
// Use `` for method-level generic parameters and ` for type-level.
if (type.DeclaringMethod != null)
{
return "``" + type.GenericParameterPosition;
}
else if (type.DeclaringType != null)
{
return "`" + type.GenericParameterPosition;
}
else
{
return type.Name;
}
}
if (type.IsArray && type.GetElementType() is { } elementType)
{
int rank = type.GetArrayRank();
string elementTypeId = GetTypeDocId(elementType, includeGenericArguments, omitGenericArity);
return rank == 1 ? elementTypeId + "[]" : elementTypeId + "[" + new string(',', rank - 1) + "]";
}
if (type.IsGenericType)
{
// Get the generic type definition.
Type genericDef = type.GetGenericTypeDefinition();
string defName = genericDef.FullName != null
? genericDef.FullName.Replace('+', '.')
: genericDef.Name;
// Remove any existing generic arity marker.
int backtickIndex = defName.IndexOf('`');
if (backtickIndex >= 0)
{
defName = defName.Substring(0, backtickIndex);
}
// Append the generic arity unless omitted.
if (!omitGenericArity)
{
int arity = genericDef.GetGenericArguments().Length;
defName += "`" + arity;
}
// If requested, append the constructed generic arguments.
if (includeGenericArguments && !type.IsGenericTypeDefinition)
{
Type[] typeArgs = type.GetGenericArguments();
string args = string.Join(",", typeArgs.Select(t => GetTypeDocId(t, includeGenericArguments, omitGenericArity)));
return defName + "{" + args + "}";
}
else
{
return defName;
}
}
// For non-generic types, use FullName (if available) and replace nested type separators.
return (type.FullName ?? type.Name).Replace('+', '.');
}
}
{{GeneratedCodeAttribute}}
file class XmlCommentOperationTransformer : IOpenApiOperationTransformer
{
public Task TransformAsync(OpenApiOperation operation, OpenApiOperationTransformerContext context, CancellationToken cancellationToken)
{
var methodInfo = context.Description.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor
? controllerActionDescriptor.MethodInfo
: context.Description.ActionDescriptor.EndpointMetadata.OfType<MethodInfo>().SingleOrDefault();
if (methodInfo is null)
{
return Task.CompletedTask;
}
if (XmlCommentCache.Cache.TryGetValue(methodInfo.CreateDocumentationId(), out var methodComment))
{
if (methodComment.Summary is { } summary)
{
operation.Summary = summary;
}
if (methodComment.Description is { } description)
{
operation.Description = description;
}
if (methodComment.Remarks is { } remarks)
{
operation.Description = remarks;
}
if (methodComment.Parameters is { Count: > 0})
{
foreach (var parameterComment in methodComment.Parameters)
{
var parameterInfo = methodInfo.GetParameters().SingleOrDefault(info => info.Name == parameterComment.Name);
var operationParameter = operation.Parameters?.SingleOrDefault(parameter => parameter.Name == parameterComment.Name);
if (operationParameter is not null)
{
var targetOperationParameter = operationParameter is OpenApiParameterReference reference
? reference.Target
: (OpenApiParameter)operationParameter;
targetOperationParameter.Description = parameterComment.Description;
if (parameterComment.Example is { } jsonString)
{
targetOperationParameter.Example = jsonString.Parse();
}
targetOperationParameter.Deprecated = parameterComment.Deprecated;
}
else
{
var requestBody = operation.RequestBody;
if (requestBody is not null)
{
requestBody.Description = parameterComment.Description;
if (parameterComment.Example is { } jsonString)
{
foreach (var mediaType in requestBody.Content.Values)
{
mediaType.Example = jsonString.Parse();
}
}
}
}
}
}
if (methodComment.Responses is { Count: > 0} && operation.Responses is { Count: > 0 })
{
foreach (var response in operation.Responses)
{
var responseComment = methodComment.Responses.SingleOrDefault(xmlResponse => xmlResponse.Code == response.Key);
if (responseComment is not null)
{
response.Value.Description = responseComment.Description;
}
}
}
}
return Task.CompletedTask;
}
}
{{GeneratedCodeAttribute}}
file class XmlCommentSchemaTransformer : IOpenApiSchemaTransformer
{
public Task TransformAsync(OpenApiSchema schema, OpenApiSchemaTransformerContext context, CancellationToken cancellationToken)
{
if (context.JsonPropertyInfo is { AttributeProvider: PropertyInfo propertyInfo })
{
if (XmlCommentCache.Cache.TryGetValue(propertyInfo.CreateDocumentationId(), out var propertyComment))
{
schema.Description = propertyComment.Value ?? propertyComment.Returns ?? propertyComment.Summary;
if (propertyComment.Examples?.FirstOrDefault() is { } jsonString)
{
schema.Example = jsonString.Parse();
}
}
}
if (XmlCommentCache.Cache.TryGetValue(context.JsonTypeInfo.Type.CreateDocumentationId(), out var typeComment))
{
schema.Description = typeComment.Summary;
if (typeComment.Examples?.FirstOrDefault() is { } jsonString)
{
schema.Example = jsonString.Parse();
}
}
return Task.CompletedTask;
}
}
file static class JsonNodeExtensions
{
public static JsonNode? Parse(this string? json)
{
if (json is null)
{
return null;
}
try
{
return JsonNode.Parse(json);
}
catch (JsonException)
{
try
{
// If parsing fails, try wrapping in quotes to make it a valid JSON string
return JsonNode.Parse($"\"{json.Replace("\"", "\\\"")}\"");
}
catch (JsonException)
{
return null;
}
}
}
}
{{GeneratedCodeAttribute}}
file static class GeneratedServiceCollectionExtensions
{
{{GenerateAddOpenApiInterceptions(groupedAddOpenApiInvocations)}}
}
}
""";
internal static string GetAddOpenApiInterceptor(AddOpenApiOverloadVariant overloadVariant) => overloadVariant switch
{
AddOpenApiOverloadVariant.AddOpenApi => """
public static IServiceCollection AddOpenApi(this IServiceCollection services)
{
return services.AddOpenApi("v1", options =>
{
options.AddSchemaTransformer(new XmlCommentSchemaTransformer());
options.AddOperationTransformer(new XmlCommentOperationTransformer());
});
}
""",
AddOpenApiOverloadVariant.AddOpenApiDocumentName => """
public static IServiceCollection AddOpenApi(this IServiceCollection services, string documentName)
{
return services.AddOpenApi(documentName, options =>
{
options.AddSchemaTransformer(new XmlCommentSchemaTransformer());
options.AddOperationTransformer(new XmlCommentOperationTransformer());
});
}
""",
AddOpenApiOverloadVariant.AddOpenApiConfigureOptions => """
public static IServiceCollection AddOpenApi(this IServiceCollection services, Action<OpenApiOptions> configureOptions)
{
return services.AddOpenApi("v1", options =>
{
options.AddSchemaTransformer(new XmlCommentSchemaTransformer());
options.AddOperationTransformer(new XmlCommentOperationTransformer());
configureOptions(options);
});
}
""",
AddOpenApiOverloadVariant.AddOpenApiDocumentNameConfigureOptions => """
public static IServiceCollection AddOpenApi(this IServiceCollection services, string documentName, Action<OpenApiOptions> configureOptions)
{
// This overload is not intercepted.
return OpenApiServiceCollectionExtensions.AddOpenApi(services, documentName, options =>
{
options.AddSchemaTransformer(new XmlCommentSchemaTransformer());
options.AddOperationTransformer(new XmlCommentOperationTransformer());
configureOptions(options);
});
}
""",
_ => string.Empty // Effectively no-op for AddOpenApi invocations that do not conform to a variant
};
internal static string GenerateAddOpenApiInterceptions(ImmutableArray<(AddOpenApiInvocation Source, int Index, ImmutableArray<InterceptableLocation?> Elements)> groupedAddOpenApiInvocations)
{
var writer = new StringWriter();
var codeWriter = new CodeWriter(writer, baseIndent: 2);
foreach (var (source, _, locations) in groupedAddOpenApiInvocations)
{
foreach (var location in locations)
{
if (location is not null)
{
codeWriter.WriteLine(location.GetInterceptsLocationAttributeSyntax());
}
}
codeWriter.WriteLine(GetAddOpenApiInterceptor(source.Variant));
}
return writer.ToString();
}
internal static string EmitCommentsCache(IEnumerable<(string MemberKey, XmlComment? Comment)> comments, CancellationToken cancellationToken)
{
var writer = new StringWriter();
var codeWriter = new CodeWriter(writer, baseIndent: 3);
foreach (var (memberKey, comment) in comments)
{
if (comment is not null)
{
codeWriter.WriteLine($"_cache.Add({FormatStringForCode(memberKey)}, {EmitSourceGeneratedXmlComment(comment)});");
}
}
return writer.ToString();
}
private static string FormatStringForCode(string? input)
{
if (input == null)
{
return "null";
}
var formatted = input
.Replace("\"", "\"\""); // Escape double quotes
return $"@\"{formatted}\"";
}
internal static string EmitSourceGeneratedXmlComment(XmlComment comment)
{
var writer = new StringWriter();
var codeWriter = new CodeWriter(writer, baseIndent: 0);
codeWriter.Write($"new XmlComment(");
codeWriter.Write(FormatStringForCode(comment.Summary) + ", ");
codeWriter.Write(FormatStringForCode(comment.Description) + ", ");
codeWriter.Write(FormatStringForCode(comment.Remarks) + ", ");
codeWriter.Write(FormatStringForCode(comment.Returns) + ", ");
codeWriter.Write(FormatStringForCode(comment.Value) + ", ");
codeWriter.Write(comment.Deprecated == true ? "true" : "false" + ", ");
if (comment.Examples is null || comment.Examples.Count == 0)
{
codeWriter.Write("null, ");
}
else
{
codeWriter.Write("[");
for (var i = 0; i < comment.Examples.Count; i++)
{
var example = comment.Examples[i];
codeWriter.Write(FormatStringForCode(example));
if (i < comment.Examples.Count - 1)
{
codeWriter.Write(", ");
}
}
codeWriter.Write("], ");
}
if (comment.Parameters is null || comment.Parameters.Count == 0)
{
codeWriter.Write("null, ");
}
else
{
codeWriter.Write("[");
for (var i = 0; i < comment.Parameters.Count; i++)
{
var parameter = comment.Parameters[i];
var exampleLiteral = string.IsNullOrEmpty(parameter.Example)
? "null"
: FormatStringForCode(parameter.Example!);
codeWriter.Write("new XmlParameterComment(");
codeWriter.Write(FormatStringForCode(parameter.Name) + ", ");
codeWriter.Write(FormatStringForCode(parameter.Description) + ", ");
codeWriter.Write(exampleLiteral + ", ");
codeWriter.Write(parameter.Deprecated == true ? "true" : "false");
codeWriter.Write(")");
if (i < comment.Parameters.Count - 1)
{
codeWriter.Write(", ");
}
}
codeWriter.Write("], ");
}
if (comment.Responses is null || comment.Responses.Count == 0)
{
codeWriter.Write("null");
}
else
{
codeWriter.Write("[");
for (var i = 0; i < comment.Responses.Count; i++)
{
var response = comment.Responses[i];
codeWriter.Write("new XmlResponseComment(");
codeWriter.Write(FormatStringForCode(response.Code) + ", ");
codeWriter.Write(FormatStringForCode(response.Description) + ", ");
codeWriter.Write(response.Example is null ? "null)" : FormatStringForCode(response.Example) + ")");
if (i < comment.Responses.Count - 1)
{
codeWriter.Write(", ");
}
}
codeWriter.Write("]");
}
codeWriter.Write(")");
return writer.ToString();
}
internal static void Emit(SourceProductionContext context,
string commentsFromXmlFile,
string commentsFromCompilation,
ImmutableArray<(AddOpenApiInvocation Source, int Index, ImmutableArray<InterceptableLocation?> Elements)> groupedAddOpenApiInvocations)
{
context.AddSource("OpenApiXmlCommentSupport.generated.cs", GenerateXmlCommentSupportSource(commentsFromXmlFile, commentsFromCompilation, groupedAddOpenApiInvocations));
}
}