-
Notifications
You must be signed in to change notification settings - Fork 509
Expand file tree
/
Copy pathSA1615SA1616CodeFixProvider.cs
More file actions
206 lines (180 loc) · 9.73 KB
/
SA1615SA1616CodeFixProvider.cs
File metadata and controls
206 lines (180 loc) · 9.73 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
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.DocumentationRules
{
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Simplification;
using StyleCop.Analyzers.Helpers;
/// <summary>
/// Implements a code fix for <see cref="SA1615ElementReturnValueMustBeDocumented"/> and
/// <see cref="SA1616ElementReturnValueDocumentationMustHaveText"/>.
/// </summary>
/// <remarks>
/// <para>To fix a violation of this rule, add and fill-in documentation text within a <returns> tag
/// describing the value returned from the element.</para>
/// </remarks>
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SA1615SA1616CodeFixProvider))]
[Shared]
internal class SA1615SA1616CodeFixProvider : CodeFixProvider
{
/// <inheritdoc/>
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(SA1615ElementReturnValueMustBeDocumented.DiagnosticId, SA1616ElementReturnValueDocumentationMustHaveText.DiagnosticId);
/// <inheritdoc/>
public override FixAllProvider GetFixAllProvider()
{
return CustomFixAllProviders.BatchFixer;
}
/// <inheritdoc/>
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(
CodeAction.Create(
DocumentationResources.SA1615SA1616CodeFix,
cancellationToken => GetTransformedDocumentAsync(context.Document, diagnostic, cancellationToken),
nameof(SA1615SA1616CodeFixProvider)),
diagnostic);
}
return SpecializedTasks.CompletedTask;
}
private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var documentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
SyntaxNode syntax = documentRoot.FindNode(diagnostic.Location.SourceSpan);
if (syntax == null)
{
return document;
}
MethodDeclarationSyntax methodDeclarationSyntax = syntax.FirstAncestorOrSelf<MethodDeclarationSyntax>();
DelegateDeclarationSyntax delegateDeclarationSyntax = syntax.FirstAncestorOrSelf<DelegateDeclarationSyntax>();
if (methodDeclarationSyntax == null && delegateDeclarationSyntax == null)
{
return document;
}
DocumentationCommentTriviaSyntax documentationComment =
methodDeclarationSyntax?.GetDocumentationCommentTriviaSyntax()
?? delegateDeclarationSyntax?.GetDocumentationCommentTriviaSyntax();
bool canIgnoreDocumentation =
documentationComment == null
|| documentationComment.Content
.Where(x => x is XmlElementSyntax || x is XmlEmptyElementSyntax)
.All(x => string.Equals(x.GetName()?.ToString(), XmlCommentHelper.IncludeXmlTag));
if (canIgnoreDocumentation)
{
return document;
}
SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
bool isTask;
bool isAsynchronousTestMethod;
if (methodDeclarationSyntax != null)
{
isTask = TaskHelper.IsTaskReturningType(semanticModel, methodDeclarationSyntax.ReturnType, cancellationToken);
isAsynchronousTestMethod = isTask && IsAsynchronousTestMethod(semanticModel, methodDeclarationSyntax, cancellationToken);
}
else
{
isTask = TaskHelper.IsTaskReturningMethod(semanticModel, delegateDeclarationSyntax, cancellationToken);
isAsynchronousTestMethod = false;
}
XmlNodeSyntax returnsElement = documentationComment.Content.GetFirstXmlElement(XmlCommentHelper.ReturnsXmlTag);
if (returnsElement != null && !isTask)
{
// This code fix doesn't know how to do anything more than document Task-returning methods.
return document;
}
SyntaxList<XmlNodeSyntax> content = XmlSyntaxFactory.List();
if (isTask)
{
content = content.Add(XmlSyntaxFactory.Text("A "));
content = content.Add(XmlSyntaxFactory.SeeElement(SyntaxFactory.TypeCref(SyntaxFactory.ParseTypeName("global::System.Threading.Tasks.Task"))).WithAdditionalAnnotations(Simplifier.Annotation));
string operationKind = isAsynchronousTestMethod ? "unit test" : "operation";
content = content.Add(XmlSyntaxFactory.Text($" representing the asynchronous {operationKind}."));
// wrap the generated content in a <placeholder> element for review.
content = XmlSyntaxFactory.List(XmlSyntaxFactory.PlaceholderElement(content));
}
// Try to replace an existing <returns> element if the comment contains one. Otherwise, add it as a new element.
SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
SyntaxNode newRoot;
if (returnsElement != null)
{
if (returnsElement is XmlEmptyElementSyntax emptyElement)
{
XmlElementSyntax updatedReturns = XmlSyntaxFactory.Element(XmlCommentHelper.ReturnsXmlTag, content)
.WithLeadingTrivia(returnsElement.GetLeadingTrivia())
.WithTrailingTrivia(returnsElement.GetTrailingTrivia());
newRoot = root.ReplaceNode(returnsElement, updatedReturns);
}
else
{
XmlElementSyntax updatedReturns = ((XmlElementSyntax)returnsElement).WithContent(content);
newRoot = root.ReplaceNode(returnsElement, updatedReturns);
}
}
else
{
string newLineText = document.Project.Solution.Workspace.Options.GetOption(FormattingOptions.NewLine, LanguageNames.CSharp);
returnsElement = XmlSyntaxFactory.Element(XmlCommentHelper.ReturnsXmlTag, content);
XmlNodeSyntax leadingNewLine = XmlSyntaxFactory.NewLine(newLineText);
// HACK: The formatter isn't working when contents are added to an existing documentation comment, so we
// manually apply the indentation from the last line of the existing comment to each new line of the
// generated content.
SyntaxTrivia exteriorTrivia = GetLastDocumentationCommentExteriorTrivia(documentationComment);
if (!exteriorTrivia.Token.IsMissing)
{
leadingNewLine = leadingNewLine.ReplaceExteriorTrivia(exteriorTrivia);
returnsElement = returnsElement.ReplaceExteriorTrivia(exteriorTrivia);
}
DocumentationCommentTriviaSyntax newDocumentationComment = documentationComment.WithContent(
documentationComment.Content.InsertRange(
documentationComment.Content.Count - 1,
XmlSyntaxFactory.List(leadingNewLine, returnsElement)));
newRoot = root.ReplaceNode(documentationComment, newDocumentationComment);
}
return document.WithSyntaxRoot(newRoot);
}
private static bool IsAsynchronousTestMethod(SemanticModel semanticModel, MethodDeclarationSyntax methodDeclarationSyntax, CancellationToken cancellationToken)
{
foreach (AttributeListSyntax attributeList in methodDeclarationSyntax.AttributeLists)
{
if (attributeList.Target != null)
{
continue;
}
foreach (AttributeSyntax attribute in attributeList.Attributes)
{
if (!(semanticModel.GetSymbolInfo(attribute.Name, cancellationToken).Symbol is IMethodSymbol methodSymbol))
{
continue;
}
if (string.Equals(methodSymbol.ContainingType.Name, "TestMethodAttribute", StringComparison.Ordinal)
|| string.Equals(methodSymbol.ContainingType.Name, "FactAttribute", StringComparison.Ordinal)
|| string.Equals(methodSymbol.ContainingType.Name, "TheoryAttribute", StringComparison.Ordinal)
|| string.Equals(methodSymbol.ContainingType.Name, "TestAttribute", StringComparison.Ordinal))
{
return true;
}
}
}
return false;
}
private static SyntaxTrivia GetLastDocumentationCommentExteriorTrivia(SyntaxNode node)
{
return node
.DescendantTrivia(descendIntoTrivia: true)
.LastOrDefault(trivia => trivia.IsKind(SyntaxKind.DocumentationCommentExteriorTrivia));
}
}
}