forked from thomhurst/TUnit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeoutCancellationTokenCodeFixProvider.cs
More file actions
190 lines (160 loc) · 7.5 KB
/
TimeoutCancellationTokenCodeFixProvider.cs
File metadata and controls
190 lines (160 loc) · 7.5 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
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
namespace TUnit.Analyzers.CodeFixers;
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(TimeoutCancellationTokenCodeFixProvider)), Shared]
public class TimeoutCancellationTokenCodeFixProvider : CodeFixProvider
{
private const string SystemThreadingNamespace = "System.Threading";
private const string CancellationTokenTypeName = "CancellationToken";
private const string ParameterName = "cancellationToken";
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(Rules.MissingTimeoutCancellationTokenAttributes.Id);
public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
if (root is null)
{
return;
}
foreach (var diagnostic in context.Diagnostics)
{
var node = root.FindNode(diagnostic.Location.SourceSpan);
var method = node.FirstAncestorOrSelf<MethodDeclarationSyntax>();
if (method is null)
{
continue;
}
context.RegisterCodeFix(
CodeAction.Create(
title: "Add CancellationToken parameter",
createChangedDocument: c => AddCancellationTokenAsync(context.Document, method, BodyMode.None, c),
equivalenceKey: "AddCancellationToken"),
diagnostic);
// Body-modifying actions only make sense when there's a block body to prepend to.
// For expression-bodied methods we'd silently no-op, which is worse than not offering.
if (method.Body is not null)
{
context.RegisterCodeFix(
CodeAction.Create(
title: "Add CancellationToken parameter with ThrowIfCancellationRequested",
createChangedDocument: c => AddCancellationTokenAsync(context.Document, method, BodyMode.ThrowIfCancellationRequested, c),
equivalenceKey: "AddCancellationTokenWithThrow"),
diagnostic);
context.RegisterCodeFix(
CodeAction.Create(
title: "Add CancellationToken parameter as discard",
createChangedDocument: c => AddCancellationTokenAsync(context.Document, method, BodyMode.Discard, c),
equivalenceKey: "AddCancellationTokenAsDiscard"),
diagnostic);
}
}
}
private enum BodyMode
{
None,
ThrowIfCancellationRequested,
Discard,
}
private static async Task<Document> AddCancellationTokenAsync(
Document document,
MethodDeclarationSyntax method,
BodyMode bodyMode,
CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (root is null)
{
return document;
}
var parameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier(ParameterName))
.WithType(SyntaxFactory.IdentifierName(CancellationTokenTypeName).WithTrailingTrivia(SyntaxFactory.Space));
MethodDeclarationSyntax updated = method
.WithParameterList(method.ParameterList.AddParameters(parameter));
if (bodyMode != BodyMode.None && updated.Body is { } body)
{
StatementSyntax statement = bodyMode == BodyMode.ThrowIfCancellationRequested
? SyntaxFactory.ParseStatement($"{ParameterName}.ThrowIfCancellationRequested();")
: SyntaxFactory.ParseStatement($"_ = {ParameterName};");
statement = statement
.WithLeadingTrivia(SyntaxFactory.ElasticMarker)
.WithTrailingTrivia(SyntaxFactory.ElasticLineFeed);
var newStatements = body.Statements.Insert(0, statement);
updated = updated.WithBody(body.WithStatements(newStatements));
}
updated = updated.WithAdditionalAnnotations(Formatter.Annotation);
var newRoot = root.ReplaceNode(method, updated);
if (newRoot is CompilationUnitSyntax compilationUnit
&& !await IsSystemThreadingInScopeAsync(document, method, cancellationToken).ConfigureAwait(false))
{
newRoot = EnsureSystemThreadingUsing(compilationUnit);
}
var newDocument = document.WithSyntaxRoot(newRoot);
return await Formatter.FormatAsync(newDocument, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
}
// Asks the semantic model whether `CancellationToken` already resolves to
// System.Threading.CancellationToken at the method's position. That covers file-level usings,
// same-file global usings, cross-file global usings, and SDK ImplicitUsings — so we skip
// adding a redundant `using System.Threading;` in every case where the compiler already sees it.
private static async Task<bool> IsSystemThreadingInScopeAsync(
Document document,
MethodDeclarationSyntax method,
CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (semanticModel is null)
{
return false;
}
var symbols = semanticModel.LookupSymbols(method.SpanStart, name: CancellationTokenTypeName);
foreach (var symbol in symbols)
{
if (symbol is INamedTypeSymbol type
&& type.ContainingNamespace?.ToDisplayString() == SystemThreadingNamespace)
{
return true;
}
}
return false;
}
private static CompilationUnitSyntax EnsureSystemThreadingUsing(CompilationUnitSyntax compilationUnit)
{
foreach (var usingDirective in compilationUnit.Usings)
{
if (usingDirective.Name?.ToString() == SystemThreadingNamespace)
{
return compilationUnit;
}
}
var newUsing = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(SystemThreadingNamespace))
.WithAdditionalAnnotations(Formatter.Annotation);
// Insert in sorted position within the System.* group, or append if no System.* group exists.
// Leaves non-System usings undisturbed to respect the file's existing organization.
var insertAt = -1;
for (var i = 0; i < compilationUnit.Usings.Count; i++)
{
var existing = compilationUnit.Usings[i].Name?.ToString();
if (existing is null || !existing.StartsWith("System", StringComparison.Ordinal))
{
continue;
}
if (string.CompareOrdinal(existing, SystemThreadingNamespace) > 0)
{
insertAt = i;
break;
}
insertAt = i + 1;
}
if (insertAt == -1)
{
return compilationUnit.AddUsings(newUsing);
}
return compilationUnit.WithUsings(compilationUnit.Usings.Insert(insertAt, newUsing));
}
}