-
Notifications
You must be signed in to change notification settings - Fork 509
Expand file tree
/
Copy pathSA1609SA1610CodeFixProvider.cs
More file actions
214 lines (185 loc) · 8.79 KB
/
SA1609SA1610CodeFixProvider.cs
File metadata and controls
214 lines (185 loc) · 8.79 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
// 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 StyleCop.Analyzers.Helpers;
/// <summary>
/// Implements a code fix for <see cref="SA1609PropertyDocumentationMustHaveValue"/> and
/// <see cref="SA1610PropertyDocumentationMustHaveValueText"/>.
/// </summary>
/// <remarks>
/// <para>To fix a violation of this rule, fill-in a description of the value held by the property within the
/// <value> tag.</para>
/// </remarks>
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SA1609SA1610CodeFixProvider))]
[Shared]
internal class SA1609SA1610CodeFixProvider : CodeFixProvider
{
/// <inheritdoc/>
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(SA1609PropertyDocumentationMustHaveValue.DiagnosticId, SA1610PropertyDocumentationMustHaveValueText.DiagnosticId);
/// <inheritdoc/>
public override FixAllProvider GetFixAllProvider()
{
return CustomFixAllProviders.BatchFixer;
}
/// <inheritdoc/>
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
if (!diagnostic.Properties.ContainsKey(PropertyDocumentationBase.NoCodeFixKey))
{
context.RegisterCodeFix(
CodeAction.Create(
DocumentationResources.SA1609SA1610CodeFix,
cancellationToken => this.GetTransformedDocumentAsync(context.Document, diagnostic, cancellationToken),
nameof(SA1609SA1610CodeFixProvider)),
diagnostic);
}
}
return SpecializedTasks.CompletedTask;
}
private static bool IsContentElement(XmlNodeSyntax syntax)
{
switch (syntax.Kind())
{
case SyntaxKind.XmlCDataSection:
case SyntaxKind.XmlElement:
case SyntaxKind.XmlEmptyElement:
case SyntaxKind.XmlText:
return true;
default:
return false;
}
}
private 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;
}
PropertyDeclarationSyntax propertyDeclarationSyntax = syntax.FirstAncestorOrSelf<PropertyDeclarationSyntax>();
if (propertyDeclarationSyntax == null)
{
return document;
}
DocumentationCommentTriviaSyntax documentationComment = propertyDeclarationSyntax.GetDocumentationCommentTriviaSyntax();
if (documentationComment == null)
{
return document;
}
if (!(documentationComment.Content.GetFirstXmlElement(XmlCommentHelper.SummaryXmlTag) is XmlElementSyntax summaryElement))
{
return document;
}
SyntaxList<XmlNodeSyntax> summaryContent = summaryElement.Content;
if (!this.TryRemoveSummaryPrefix(ref summaryContent, "Gets or sets "))
{
if (!this.TryRemoveSummaryPrefix(ref summaryContent, "Gets "))
{
this.TryRemoveSummaryPrefix(ref summaryContent, "Sets ");
}
}
SyntaxList<XmlNodeSyntax> content = summaryContent.WithoutFirstAndLastNewlines();
if (!string.IsNullOrWhiteSpace(content.ToFullString()))
{
// wrap the content in a <placeholder> element for review
content = XmlSyntaxFactory.List(XmlSyntaxFactory.PlaceholderElement(content));
}
string newLineText = document.Project.Solution.Workspace.Options.GetOption(FormattingOptions.NewLine, LanguageNames.CSharp);
XmlElementSyntax valueElement = XmlSyntaxFactory.MultiLineElement(XmlCommentHelper.ValueXmlTag, newLineText, 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 = CommonDocumentationHelper.GetLastDocumentationCommentExteriorTrivia(documentationComment);
if (!exteriorTrivia.Token.IsMissing)
{
leadingNewLine = leadingNewLine.ReplaceExteriorTrivia(exteriorTrivia);
valueElement = valueElement.ReplaceExteriorTrivia(exteriorTrivia);
}
// Try to replace an existing <value> element if the comment contains one. Otherwise, add it as a new element.
SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
SyntaxNode newRoot;
XmlNodeSyntax existingValue = documentationComment.Content.GetFirstXmlElement(XmlCommentHelper.ValueXmlTag);
if (existingValue != null)
{
newRoot = root.ReplaceNode(existingValue, valueElement);
}
else
{
DocumentationCommentTriviaSyntax newDocumentationComment = documentationComment.WithContent(
documentationComment.Content.InsertRange(
documentationComment.Content.Count - 1,
XmlSyntaxFactory.List(leadingNewLine, valueElement)));
newRoot = root.ReplaceNode(documentationComment, newDocumentationComment);
}
return document.WithSyntaxRoot(newRoot);
}
private bool TryRemoveSummaryPrefix(ref SyntaxList<XmlNodeSyntax> summaryContent, string prefix)
{
XmlNodeSyntax firstContent = summaryContent.FirstOrDefault(IsContentElement);
if (!(firstContent is XmlTextSyntax firstText))
{
return false;
}
string firstTextContent = string.Concat(firstText.DescendantTokens());
if (!firstTextContent.TrimStart().StartsWith(prefix, StringComparison.Ordinal))
{
return false;
}
// Find the token containing the prefix, such as "Gets or sets "
SyntaxToken prefixToken = default;
foreach (SyntaxToken textToken in firstText.TextTokens)
{
if (textToken.IsMissing)
{
continue;
}
if (!textToken.Text.TrimStart().StartsWith(prefix, StringComparison.Ordinal))
{
continue;
}
prefixToken = textToken;
break;
}
if (prefixToken.IsMissingOrDefault())
{
return false;
}
string text = prefixToken.Text;
string valueText = prefixToken.ValueText;
int index = text.IndexOf(prefix);
if (index >= 0)
{
bool additionalCharacters = index + prefix.Length < text.Length;
text = text.Substring(0, index)
+ (additionalCharacters ? char.ToUpperInvariant(text[index + prefix.Length]).ToString() : string.Empty)
+ text.Substring(index + (additionalCharacters ? (prefix.Length + 1) : prefix.Length));
}
index = valueText.IndexOf(prefix);
if (index >= 0)
{
valueText = valueText.Remove(index, prefix.Length);
}
SyntaxToken replaced = SyntaxFactory.Token(prefixToken.LeadingTrivia, prefixToken.Kind(), text, valueText, prefixToken.TrailingTrivia);
summaryContent = summaryContent.Replace(firstText, firstText.ReplaceToken(prefixToken, replaced));
return true;
}
}
}