forked from microsoft/vs-threading
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVSTHRD103UseAsyncOptionCodeFix.cs
More file actions
235 lines (203 loc) · 12.5 KB
/
Copy pathVSTHRD103UseAsyncOptionCodeFix.cs
File metadata and controls
235 lines (203 loc) · 12.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
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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.VisualStudio.Threading.Analyzers
{
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Text;
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.Simplification;
using Microsoft.VisualStudio.Threading;
/// <summary>
/// Provides a code action to fix calls to synchronous methods from async methods when async options exist.
/// </summary>
/// <remarks>
/// <![CDATA[
/// async Task MyMethod()
/// {
/// Task t;
/// t.Wait(); // Code action will change this to "await t;"
/// }
/// ]]>
/// </remarks>
[ExportCodeFixProvider(LanguageNames.CSharp)]
public class VSTHRD103UseAsyncOptionCodeFix : CodeFixProvider
{
private static readonly ImmutableArray<string> ReusableFixableDiagnosticIds = ImmutableArray.Create(
VSTHRD103UseAsyncOptionAnalyzer.Id);
/// <inheritdoc />
public override ImmutableArray<string> FixableDiagnosticIds => ReusableFixableDiagnosticIds;
/// <inheritdoc />
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
Diagnostic? diagnostic = context.Diagnostics.FirstOrDefault(d => d.Properties.ContainsKey(VSTHRD103UseAsyncOptionAnalyzer.AsyncMethodKeyName));
if (diagnostic is object)
{
// Check that the method we're replacing the sync blocking call with actually exists.
// This is particularly useful when the method is an extension method, since the using directive
// would need to be present (or the namespace imply it) and we don't yet add missing using directives.
bool asyncAlternativeExists = false;
string asyncMethodName = diagnostic.Properties[VSTHRD103UseAsyncOptionAnalyzer.AsyncMethodKeyName];
if (string.IsNullOrEmpty(asyncMethodName))
{
asyncMethodName = "GetAwaiter";
}
SemanticModel? semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
SyntaxNode? syntaxRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var blockingIdentifier = syntaxRoot.FindNode(diagnostic.Location.SourceSpan) as IdentifierNameSyntax;
var memberAccessExpression = blockingIdentifier?.Parent as MemberAccessExpressionSyntax;
// Check whether this code was already calling the awaiter (in a synchronous fashion).
asyncAlternativeExists |= memberAccessExpression?.Expression is InvocationExpressionSyntax invoke && invoke.Expression is MemberAccessExpressionSyntax parentMemberAccess && parentMemberAccess.Name.Identifier.Text == nameof(Task.GetAwaiter);
if (!asyncAlternativeExists)
{
// If we fail to recognize the container, assume it exists since the analyzer thought it would.
ITypeSymbol? container = memberAccessExpression is object ? semanticModel.GetTypeInfo(memberAccessExpression.Expression, context.CancellationToken).ConvertedType : null;
asyncAlternativeExists = container is null || semanticModel.LookupSymbols(diagnostic.Location.SourceSpan.Start, name: asyncMethodName, container: container, includeReducedExtensionMethods: true).Any();
}
if (asyncAlternativeExists)
{
context.RegisterCodeFix(new ReplaceSyncMethodCallWithAwaitAsync(context.Document, diagnostic), diagnostic);
}
}
}
/// <inheritdoc />
public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
private class ReplaceSyncMethodCallWithAwaitAsync : CodeAction
{
private readonly Document document;
private readonly Diagnostic diagnostic;
internal ReplaceSyncMethodCallWithAwaitAsync(Document document, Diagnostic diagnostic)
{
this.document = document;
this.diagnostic = diagnostic;
}
public override string Title
{
get
{
return !string.IsNullOrEmpty(this.AlternativeAsyncMethod)
? string.Format(CultureInfo.CurrentCulture, Strings.AwaitXInstead, this.AlternativeAsyncMethod)
: Strings.UseAwaitInstead;
}
}
/// <inheritdoc />
public override string? EquivalenceKey => null;
private string AlternativeAsyncMethod => this.diagnostic.Properties[VSTHRD103UseAsyncOptionAnalyzer.AsyncMethodKeyName];
private string ExtensionMethodNamespace => this.diagnostic.Properties[VSTHRD103UseAsyncOptionAnalyzer.ExtensionMethodNamespaceKeyName];
protected override async Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
{
Document? document = this.document;
SyntaxNode? root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// Find the synchronously blocking call member,
// and bookmark it so we can find it again after some mutations have taken place.
var syncAccessBookmark = new SyntaxAnnotation();
SimpleNameSyntax syncMethodName = (SimpleNameSyntax)root.FindNode(this.diagnostic.Location.SourceSpan);
if (syncMethodName is null)
{
MemberAccessExpressionSyntax? syncMemberAccess = root.FindNode(this.diagnostic.Location.SourceSpan).FirstAncestorOrSelf<MemberAccessExpressionSyntax>();
syncMethodName = syncMemberAccess.Name;
}
// When we give the Document a modified SyntaxRoot, yet another is created. So we first assign it to the Document,
// then we query for the SyntaxRoot from the Document.
document = document.WithSyntaxRoot(
root.ReplaceNode(syncMethodName, syncMethodName.WithAdditionalAnnotations(syncAccessBookmark)));
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
syncMethodName = (SimpleNameSyntax)root.GetAnnotatedNodes(syncAccessBookmark).Single();
// We'll need the semantic model later. But because we've annotated a node, that changes the SyntaxRoot
// and that renders the default semantic model broken (even though we've already updated the document's SyntaxRoot?!).
// So after acquiring the semantic model, update it with the new method body.
SemanticModel? semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
AnonymousFunctionExpressionSyntax? originalAnonymousMethodContainerIfApplicable = syncMethodName.FirstAncestorOrSelf<AnonymousFunctionExpressionSyntax>();
MethodDeclarationSyntax? originalMethodDeclaration = syncMethodName.FirstAncestorOrSelf<MethodDeclarationSyntax>();
ISymbol? enclosingSymbol = semanticModel.GetEnclosingSymbol(this.diagnostic.Location.SourceSpan.Start, cancellationToken);
var hasReturnValue = ((enclosingSymbol as IMethodSymbol)?.ReturnType as INamedTypeSymbol)?.IsGenericType ?? false;
// Ensure that the method or anonymous delegate is using the async keyword.
MethodDeclarationSyntax updatedMethod;
if (originalAnonymousMethodContainerIfApplicable is object)
{
updatedMethod = originalMethodDeclaration.ReplaceNode(
originalAnonymousMethodContainerIfApplicable,
originalAnonymousMethodContainerIfApplicable.MakeMethodAsync(hasReturnValue, semanticModel, cancellationToken));
}
else
{
(document, updatedMethod) = await originalMethodDeclaration.MakeMethodAsync(document, cancellationToken).ConfigureAwait(false);
semanticModel = null; // out-dated
}
if (updatedMethod != originalMethodDeclaration)
{
// Re-discover our synchronously blocking member.
syncMethodName = (SimpleNameSyntax)updatedMethod.GetAnnotatedNodes(syncAccessBookmark).Single();
}
ExpressionSyntax? syncExpression = GetSynchronousExpression(syncMethodName);
ExpressionSyntax awaitExpression;
if (!string.IsNullOrEmpty(this.AlternativeAsyncMethod))
{
// Replace the member being called and await the invocation expression.
// While doing so, move leading trivia to the surrounding await expression.
SimpleNameSyntax? asyncMethodName = syncMethodName.WithIdentifier(SyntaxFactory.Identifier(this.diagnostic.Properties[VSTHRD103UseAsyncOptionAnalyzer.AsyncMethodKeyName]));
awaitExpression = SyntaxFactory.AwaitExpression(
syncExpression.ReplaceNode(syncMethodName, asyncMethodName).WithoutLeadingTrivia())
.WithLeadingTrivia(syncExpression.GetLeadingTrivia());
}
else
{
// Remove the member being accessed that causes a synchronous block and simply await the object.
MemberAccessExpressionSyntax? syncMemberAccess = syncMethodName.FirstAncestorOrSelf<MemberAccessExpressionSyntax>();
ExpressionSyntax? syncMemberStrippedExpression = syncMemberAccess.Expression;
// Special case a common pattern of calling task.GetAwaiter().GetResult() and remove both method calls.
var expressionMethodCall = (syncMemberStrippedExpression as InvocationExpressionSyntax)?.Expression as MemberAccessExpressionSyntax;
if (expressionMethodCall?.Name.Identifier.Text == nameof(Task.GetAwaiter))
{
syncMemberStrippedExpression = expressionMethodCall.Expression;
}
awaitExpression = SyntaxFactory.AwaitExpression(syncMemberStrippedExpression.WithoutLeadingTrivia())
.WithLeadingTrivia(syncMemberStrippedExpression.GetLeadingTrivia());
}
if (!(syncExpression.Parent is ExpressionStatementSyntax))
{
awaitExpression = SyntaxFactory.ParenthesizedExpression(awaitExpression)
.WithAdditionalAnnotations(Simplifier.Annotation);
}
updatedMethod = updatedMethod
.ReplaceNode(syncExpression, awaitExpression);
SyntaxNode? newRoot = root.ReplaceNode(originalMethodDeclaration, updatedMethod);
Document? newDocument = document.WithSyntaxRoot(newRoot);
return newDocument.Project.Solution;
}
private static ExpressionSyntax GetSynchronousExpression(SimpleNameSyntax syncMethodName)
{
SyntaxNode current = syncMethodName;
while (true)
{
switch (current.Kind())
{
case SyntaxKind.InvocationExpression:
return (ExpressionSyntax)current;
case SyntaxKind.SimpleMemberAccessExpression:
if (current.Parent.IsKind(SyntaxKind.InvocationExpression))
{
return (ExpressionSyntax)current.Parent;
}
else
{
return (ExpressionSyntax)current;
}
default:
current = current.Parent;
break;
}
}
}
}
}
}