forked from microsoft/vs-threading
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFixUtils.cs
More file actions
443 lines (385 loc) · 21.2 KB
/
Copy pathFixUtils.cs
File metadata and controls
443 lines (385 loc) · 21.2 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
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
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Simplification;
internal static class FixUtils
{
internal const string BookmarkAnnotationName = "Bookmark";
internal static AnonymousFunctionExpressionSyntax MakeMethodAsync(this AnonymousFunctionExpressionSyntax method, bool hasReturnValue, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (method.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword))
{
// already async
return method;
}
AnonymousFunctionExpressionSyntax? updated = null;
var simpleLambda = method as SimpleLambdaExpressionSyntax;
if (simpleLambda is object)
{
updated = simpleLambda
.WithAsyncKeyword(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))
.WithBody(UpdateStatementsForAsyncMethod(simpleLambda.Body, semanticModel, hasReturnValue, cancellationToken));
}
var parentheticalLambda = method as ParenthesizedLambdaExpressionSyntax;
if (parentheticalLambda is object)
{
updated = parentheticalLambda
.WithAsyncKeyword(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))
.WithBody(UpdateStatementsForAsyncMethod(parentheticalLambda.Body, semanticModel, hasReturnValue, cancellationToken));
}
var anonymousMethod = method as AnonymousMethodExpressionSyntax;
if (anonymousMethod is object)
{
updated = anonymousMethod
.WithAsyncKeyword(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))
.WithBody(UpdateStatementsForAsyncMethod(anonymousMethod.Body, semanticModel, hasReturnValue, cancellationToken));
}
if (updated is null)
{
throw new NotSupportedException();
}
return updated;
}
/// <summary>
/// Converts a synchronous method to be asynchronous, if it is not already async.
/// </summary>
/// <param name="method">The method to convert.</param>
/// <param name="document">The document.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// The new Document and method syntax, or the original if it was already async.
/// </returns>
/// <exception cref="System.ArgumentNullException">
/// <para>If <paramref name="method"/> is null.</para>
/// <para>-or-</para>
/// <para>If <paramref name="document"/> is null.</para>
/// </exception>
internal static async Task<Tuple<Document, MethodDeclarationSyntax>> MakeMethodAsync(this MethodDeclarationSyntax method, Document document, CancellationToken cancellationToken = default(CancellationToken))
{
if (method is null)
{
throw new ArgumentNullException(nameof(method));
}
if (document is null)
{
throw new ArgumentNullException(nameof(document));
}
if (method.Modifiers.Any(SyntaxKind.AsyncKeyword))
{
// Already asynchronous.
return Tuple.Create(document, method);
}
DocumentId documentId = document.Id;
SemanticModel? semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
IMethodSymbol? methodSymbol = semanticModel.GetDeclaredSymbol(method, cancellationToken);
bool hasReturnValue;
TypeSyntax returnType = method.ReturnType;
if (!Utils.HasAsyncCompatibleReturnType(methodSymbol))
{
hasReturnValue = (method.ReturnType as PredefinedTypeSyntax)?.Keyword.IsKind(SyntaxKind.VoidKeyword) is not true;
// Determine new return type.
returnType = hasReturnValue
? QualifyName(
Namespaces.SystemThreadingTasks,
SyntaxFactory.GenericName(SyntaxFactory.Identifier(nameof(Task)))
.AddTypeArgumentListArguments(method.ReturnType))
: SyntaxFactory.ParseTypeName(typeof(Task).FullName);
returnType = returnType
.WithAdditionalAnnotations(Simplifier.Annotation)
.WithTrailingTrivia(method.ReturnType.GetTrailingTrivia());
}
else
{
TypeSyntax t = method.ReturnType;
while (t is QualifiedNameSyntax q)
{
t = q.Right;
}
hasReturnValue = t is GenericNameSyntax;
}
// Fix up any return statements to await on the Task it would have returned.
bool returnTypeChanged = method.ReturnType != returnType;
BlockSyntax updatedBody = UpdateStatementsForAsyncMethod(
method.Body,
semanticModel,
hasReturnValue,
returnTypeChanged,
cancellationToken);
// Apply the changes to the document, and null out stale data.
SyntaxAnnotation methodBookmark;
(document, method, methodBookmark) = await UpdateDocumentAsync(
document,
method,
m => m
.WithBody(updatedBody)
.AddModifiers(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))
.WithReturnType(returnType),
cancellationToken).ConfigureAwait(false);
semanticModel = null;
methodSymbol = null;
// Rename the method to have an Async suffix if we changed the return type,
// and it doesn't already have that suffix.
if (returnTypeChanged && !method.Identifier.ValueText.EndsWith(VSTHRD200UseAsyncNamingConventionAnalyzer.MandatoryAsyncSuffix, StringComparison.Ordinal))
{
string newName = method.Identifier.ValueText + VSTHRD200UseAsyncNamingConventionAnalyzer.MandatoryAsyncSuffix;
semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
methodSymbol = semanticModel.GetDeclaredSymbol(method, cancellationToken);
// Don't rename entrypoint (i.e. "Main") methods.
if (!Utils.IsEntrypointMethod(methodSymbol, semanticModel, cancellationToken))
{
Solution? solution = await Renamer.RenameSymbolAsync(
document.Project.Solution,
methodSymbol,
newName,
document.Project.Solution.Workspace.Options,
cancellationToken).ConfigureAwait(false);
document = solution.GetDocument(document.Id);
semanticModel = null;
methodSymbol = null;
SyntaxNode? root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
method = (MethodDeclarationSyntax)root.GetAnnotatedNodes(methodBookmark).Single();
}
}
// Update callers to await calls to this method if we made it awaitable.
if (returnTypeChanged)
{
semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
methodSymbol = semanticModel.GetDeclaredSymbol(method, cancellationToken);
SyntaxAnnotation callerAnnotation;
Solution solution = document.Project.Solution;
List<DocumentId> annotatedDocumentIds;
(solution, callerAnnotation, annotatedDocumentIds) = await AnnotateAllCallersAsync(solution, methodSymbol, cancellationToken).ConfigureAwait(false);
foreach (DocumentId docId in annotatedDocumentIds)
{
document = solution.GetDocument(docId);
SyntaxTree? tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
SyntaxNode? root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var rewriter = new AwaitCallRewriter(callerAnnotation);
root = rewriter.Visit(root);
solution = solution.GetDocument(tree).WithSyntaxRoot(root).Project.Solution;
}
foreach (DocumentId docId in annotatedDocumentIds)
{
document = solution.GetDocument(docId);
SyntaxTree? tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
SyntaxNode? root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
for (SyntaxNode? node = root.GetAnnotatedNodes(callerAnnotation).FirstOrDefault(); node is object; node = root.GetAnnotatedNodes(callerAnnotation).FirstOrDefault())
{
MethodDeclarationSyntax? callingMethod = node.FirstAncestorOrSelf<MethodDeclarationSyntax>();
if (callingMethod is object)
{
(document, callingMethod) = await MakeMethodAsync(callingMethod, document, cancellationToken).ConfigureAwait(false);
// Clear all annotations of callers from this method so we don't revisit it.
root = await callingMethod.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var annotationRemover = new RemoveAnnotationRewriter(callerAnnotation);
root = root.ReplaceNode(callingMethod, annotationRemover.Visit(callingMethod));
document = document.WithSyntaxRoot(root);
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
}
else
{
// Clear all annotations of callers from this method so we don't revisit it.
root = await node.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
root = root.ReplaceNode(node, node.WithoutAnnotations(callerAnnotation));
document = document.WithSyntaxRoot(root);
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
}
}
solution = document.Project.Solution;
}
// Make sure we return the latest of everything.
document = solution.GetDocument(documentId);
SyntaxTree? finalTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
SyntaxNode? finalRoot = await finalTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
method = (MethodDeclarationSyntax)finalRoot.GetAnnotatedNodes(methodBookmark).Single();
}
return Tuple.Create(document, method);
}
internal static async Task<Tuple<Solution, SyntaxAnnotation, List<DocumentId>>> AnnotateAllCallersAsync(Solution solution, ISymbol symbol, CancellationToken cancellationToken)
{
var bookmark = new SyntaxAnnotation();
IEnumerable<SymbolCallerInfo>? callers = await SymbolFinder.FindCallersAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
IEnumerable<IGrouping<SyntaxTree, Location>>? callersByFile = from caller in callers
from location in caller.Locations
group location by location.SourceTree into file
select file;
var updatedDocs = new List<DocumentId>();
foreach (IGrouping<SyntaxTree, Location>? callerByFile in callersByFile)
{
SyntaxNode? root = await callerByFile.Key.GetRootAsync(cancellationToken).ConfigureAwait(false);
foreach (Location? caller in callerByFile)
{
SyntaxNode? node = root.FindNode(caller.SourceSpan);
InvocationExpressionSyntax? invocation = node.FirstAncestorOrSelf<InvocationExpressionSyntax>();
if (invocation is object)
{
root = root.ReplaceNode(invocation, invocation.WithAdditionalAnnotations(bookmark));
}
}
Document updatedDocument = solution.GetDocument(callerByFile.Key)
.WithSyntaxRoot(root);
updatedDocs.Add(updatedDocument.Id);
solution = updatedDocument.Project.Solution;
}
return Tuple.Create(solution, bookmark, updatedDocs);
}
internal static async Task<Tuple<Document, T, SyntaxAnnotation>> UpdateDocumentAsync<T>(Document document, T syntaxNode, Func<T, T> syntaxNodeTransform, CancellationToken cancellationToken)
where T : SyntaxNode
{
SyntaxAnnotation bookmark;
SyntaxNode root;
(bookmark, document, syntaxNode, root) = await BookmarkSyntaxAsync(document, syntaxNode, cancellationToken).ConfigureAwait(false);
T? newSyntaxNode = syntaxNodeTransform(syntaxNode);
if (!newSyntaxNode.HasAnnotation(bookmark))
{
newSyntaxNode = syntaxNode.CopyAnnotationsTo(newSyntaxNode);
}
root = root.ReplaceNode(syntaxNode, newSyntaxNode);
document = document.WithSyntaxRoot(root);
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
newSyntaxNode = (T)root.GetAnnotatedNodes(bookmark).Single();
return Tuple.Create(document, newSyntaxNode, bookmark);
}
internal static async Task<Tuple<SyntaxAnnotation, Document, T, SyntaxNode>> BookmarkSyntaxAsync<T>(Document document, T syntaxNode, CancellationToken cancellationToken)
where T : SyntaxNode
{
var bookmark = new SyntaxAnnotation(BookmarkAnnotationName);
SyntaxNode? root = await syntaxNode.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
root = root.ReplaceNode(syntaxNode, syntaxNode.WithAdditionalAnnotations(bookmark));
document = document.WithSyntaxRoot(root);
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
syntaxNode = (T)root.GetAnnotatedNodes(bookmark).Single();
return Tuple.Create(bookmark, document, syntaxNode, root);
}
internal static NameSyntax QualifyName(IReadOnlyList<string> qualifiers, SimpleNameSyntax simpleName)
{
if (qualifiers is null)
{
throw new ArgumentNullException(nameof(qualifiers));
}
if (simpleName is null)
{
throw new ArgumentNullException(nameof(simpleName));
}
if (qualifiers.Count == 0)
{
throw new ArgumentException("At least one qualifier required.");
}
NameSyntax result = SyntaxFactory.IdentifierName(qualifiers[0]);
for (int i = 1; i < qualifiers.Count; i++)
{
IdentifierNameSyntax? rightSide = SyntaxFactory.IdentifierName(qualifiers[i]);
result = SyntaxFactory.QualifiedName(result, rightSide);
}
return SyntaxFactory.QualifiedName(result, simpleName);
}
private static CSharpSyntaxNode UpdateStatementsForAsyncMethod(CSharpSyntaxNode body, SemanticModel semanticModel, bool hasResultValue, CancellationToken cancellationToken)
{
var blockBody = body as BlockSyntax;
if (blockBody is object)
{
bool returnTypeChanged = false; // probably not right, but we don't have a failing test yet.
return UpdateStatementsForAsyncMethod(blockBody, semanticModel, hasResultValue, returnTypeChanged, cancellationToken);
}
var expressionBody = body as ExpressionSyntax;
if (expressionBody is object)
{
return SyntaxFactory.AwaitExpression(expressionBody).TrySimplify(expressionBody, semanticModel, cancellationToken);
}
throw new NotSupportedException();
}
private static BlockSyntax UpdateStatementsForAsyncMethod(BlockSyntax body, SemanticModel semanticModel, bool hasResultValue, bool returnTypeChanged, CancellationToken cancellationToken)
{
BlockSyntax? fixedUpBlock = body.ReplaceNodes(
body.DescendantNodes().OfType<ReturnStatementSyntax>(),
(f, n) =>
{
if (hasResultValue)
{
return returnTypeChanged
? n
: n.WithExpression(SyntaxFactory.AwaitExpression(n.Expression).TrySimplify(f.Expression, semanticModel, cancellationToken));
}
if (body.Statements.Last() == f)
{
// If it is the last statement in the method, we can remove it since a return is implied.
return null;
}
return n
.WithExpression(null) // don't return any value
.WithReturnKeyword(n.ReturnKeyword.WithTrailingTrivia(SyntaxFactory.TriviaList())); // remove the trailing space after the keyword
});
return fixedUpBlock;
}
private static ExpressionSyntax TrySimplify(this AwaitExpressionSyntax awaitExpression, ExpressionSyntax originalSyntax, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (awaitExpression is null)
{
throw new ArgumentNullException(nameof(awaitExpression));
}
// await Task.FromResult(x) => x.
if (semanticModel is object)
{
if (awaitExpression.Expression is InvocationExpressionSyntax awaitedInvocation
&& awaitedInvocation.Expression is MemberAccessExpressionSyntax awaitedInvocationMemberAccess
&& awaitedInvocationMemberAccess.Name.Identifier.Text == nameof(Task.FromResult))
{
// Is the FromResult method on the Task or Task<T> class?
ISymbol? memberOwnerSymbol = semanticModel.GetSymbolInfo(originalSyntax, cancellationToken).Symbol;
if (Utils.IsTask(memberOwnerSymbol?.ContainingType))
{
ExpressionSyntax? simplified = awaitedInvocation.ArgumentList.Arguments.Single().Expression;
return simplified;
}
}
}
return awaitExpression;
}
private class AwaitCallRewriter : CSharpSyntaxRewriter
{
private readonly SyntaxAnnotation callAnnotation;
public AwaitCallRewriter(SyntaxAnnotation callAnnotation)
: base(visitIntoStructuredTrivia: false)
{
this.callAnnotation = callAnnotation ?? throw new ArgumentNullException(nameof(callAnnotation));
}
public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
{
if (node.HasAnnotation(this.callAnnotation))
{
return SyntaxFactory.ParenthesizedExpression(
SyntaxFactory.AwaitExpression(node))
.WithAdditionalAnnotations(Simplifier.Annotation);
}
return base.VisitInvocationExpression(node);
}
}
private class RemoveAnnotationRewriter : CSharpSyntaxRewriter
{
private readonly SyntaxAnnotation annotationToRemove;
public RemoveAnnotationRewriter(SyntaxAnnotation annotationToRemove)
: base(visitIntoStructuredTrivia: false)
{
this.annotationToRemove = annotationToRemove ?? throw new ArgumentNullException(nameof(annotationToRemove));
}
public override SyntaxNode Visit(SyntaxNode node)
{
return base.Visit(
(node?.HasAnnotation(this.annotationToRemove) ?? false)
? node.WithoutAnnotations(this.annotationToRemove)
: node);
}
}
}
}