|
| 1 | +using System.Collections.Immutable; |
| 2 | +using System.Composition; |
| 3 | +using System.Linq; |
| 4 | +using System.Threading; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using Microsoft.CodeAnalysis; |
| 7 | +using Microsoft.CodeAnalysis.CodeActions; |
| 8 | +using Microsoft.CodeAnalysis.CodeFixes; |
| 9 | +using Microsoft.CodeAnalysis.CSharp; |
| 10 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 11 | +using Microsoft.CodeAnalysis.Formatting; |
| 12 | +using Microsoft.CodeAnalysis.Operations; |
| 13 | +using Microsoft.CodeAnalysis.Text; |
| 14 | + |
| 15 | +namespace IntelliTect.Analyzer.CodeFixes |
| 16 | +{ |
| 17 | + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(TaskDelayZero))] |
| 18 | + [Shared] |
| 19 | + public class TaskDelayZero : CodeFixProvider |
| 20 | + { |
| 21 | + private const string Title = "Use Task.CompletedTask"; |
| 22 | + |
| 23 | + public sealed override ImmutableArray<string> FixableDiagnosticIds => |
| 24 | + ImmutableArray.Create(Analyzers.TaskDelayZero.DiagnosticId); |
| 25 | + |
| 26 | + public sealed override FixAllProvider GetFixAllProvider() => |
| 27 | + WellKnownFixAllProviders.BatchFixer; |
| 28 | + |
| 29 | + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) |
| 30 | + { |
| 31 | + SyntaxNode? root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); |
| 32 | + if (root is null) |
| 33 | + { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + Diagnostic diagnostic = context.Diagnostics.First(); |
| 38 | + TextSpan diagnosticSpan = diagnostic.Location.SourceSpan; |
| 39 | + |
| 40 | + InvocationExpressionSyntax? invocation = root.FindToken(diagnosticSpan.Start) |
| 41 | + .Parent?.AncestorsAndSelf() |
| 42 | + .OfType<InvocationExpressionSyntax>() |
| 43 | + .FirstOrDefault(); |
| 44 | + if (invocation is null) |
| 45 | + { |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + SemanticModel? semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); |
| 50 | + if (semanticModel is null) |
| 51 | + { |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + if (semanticModel.GetOperation(invocation, context.CancellationToken) is not IInvocationOperation invocationOperation) |
| 56 | + { |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + ExpressionSyntax? replacement = CreateReplacementExpression(invocationOperation); |
| 61 | + if (replacement is null) |
| 62 | + { |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + context.RegisterCodeFix( |
| 67 | + CodeAction.Create( |
| 68 | + title: Title, |
| 69 | + createChangedDocument: c => ReplaceInvocationAsync(context.Document, invocation, replacement, c), |
| 70 | + equivalenceKey: Title), |
| 71 | + diagnostic); |
| 72 | + } |
| 73 | + |
| 74 | + private static ExpressionSyntax? CreateReplacementExpression(IInvocationOperation invocation) |
| 75 | + { |
| 76 | + if (!IsTaskDelayWithIntMilliseconds(invocation.TargetMethod)) |
| 77 | + { |
| 78 | + return null; |
| 79 | + } |
| 80 | + |
| 81 | + IArgumentOperation? millisecondsDelayArgument = invocation.Arguments |
| 82 | + .FirstOrDefault(a => a.Parameter?.Name == "millisecondsDelay"); |
| 83 | + if (millisecondsDelayArgument?.Value.ConstantValue is not { HasValue: true, Value: int millisecondsDelay } |
| 84 | + || millisecondsDelay != 0) |
| 85 | + { |
| 86 | + return null; |
| 87 | + } |
| 88 | + |
| 89 | + IArgumentOperation? cancellationTokenArgument = invocation.Arguments |
| 90 | + .FirstOrDefault(a => a.Parameter?.Name == "cancellationToken"); |
| 91 | + if (cancellationTokenArgument is null) |
| 92 | + { |
| 93 | + return SyntaxFactory.ParseExpression("global::System.Threading.Tasks.Task.CompletedTask"); |
| 94 | + } |
| 95 | + |
| 96 | + if (cancellationTokenArgument.Value.Syntax is not ExpressionSyntax cancellationTokenExpression) |
| 97 | + { |
| 98 | + return null; |
| 99 | + } |
| 100 | + |
| 101 | + if (!IsSideEffectFree(cancellationTokenArgument.Value)) |
| 102 | + { |
| 103 | + return null; |
| 104 | + } |
| 105 | + |
| 106 | + string tokenExpressionText = NormalizeCancellationTokenExpression(cancellationTokenExpression); |
| 107 | + |
| 108 | + // Runtime behavior reference: |
| 109 | + // https://github.com/dotnet/runtime/blob/1acc89c305165239a5a824567a3176b6b3342790/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs#L5907-L5911 |
| 110 | + // Task.Delay(0, token) maps to: |
| 111 | + // token.IsCancellationRequested ? Task.FromCanceled(token) : Task.CompletedTask |
| 112 | + return SyntaxFactory.ParseExpression( |
| 113 | + $"({tokenExpressionText}.IsCancellationRequested ? global::System.Threading.Tasks.Task.FromCanceled({tokenExpressionText}) : global::System.Threading.Tasks.Task.CompletedTask)"); |
| 114 | + } |
| 115 | + |
| 116 | + private static string NormalizeCancellationTokenExpression(ExpressionSyntax cancellationTokenExpression) |
| 117 | + { |
| 118 | + return cancellationTokenExpression.Kind() switch |
| 119 | + { |
| 120 | + SyntaxKind.DefaultLiteralExpression => "default(global::System.Threading.CancellationToken)", |
| 121 | + SyntaxKind.DefaultExpression => cancellationTokenExpression.WithoutTrivia().ToString() == "default" |
| 122 | + ? "default(global::System.Threading.CancellationToken)" |
| 123 | + : cancellationTokenExpression.WithoutTrivia().ToString(), |
| 124 | + _ => cancellationTokenExpression.WithoutTrivia().ToString() |
| 125 | + }; |
| 126 | + } |
| 127 | + |
| 128 | + private static bool IsSideEffectFree(IOperation operation) |
| 129 | + { |
| 130 | + return operation switch |
| 131 | + { |
| 132 | + ILocalReferenceOperation => true, |
| 133 | + IParameterReferenceOperation => true, |
| 134 | + IDefaultValueOperation => true, |
| 135 | + IConversionOperation conversion => IsSideEffectFree(conversion.Operand), |
| 136 | + IParenthesizedOperation parenthesized => IsSideEffectFree(parenthesized.Operand), |
| 137 | + IPropertyReferenceOperation propertyReference |
| 138 | + when propertyReference.Instance is null |
| 139 | + && propertyReference.Property.Name == "None" |
| 140 | + && propertyReference.Property.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) |
| 141 | + == "global::System.Threading.CancellationToken" => true, |
| 142 | + _ => false |
| 143 | + }; |
| 144 | + } |
| 145 | + |
| 146 | + private static bool IsTaskDelayWithIntMilliseconds(IMethodSymbol methodSymbol) |
| 147 | + { |
| 148 | + if (methodSymbol.Name != "Delay") |
| 149 | + { |
| 150 | + return false; |
| 151 | + } |
| 152 | + |
| 153 | + if (methodSymbol.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) |
| 154 | + != "global::System.Threading.Tasks.Task") |
| 155 | + { |
| 156 | + return false; |
| 157 | + } |
| 158 | + |
| 159 | + return methodSymbol.Parameters.Length >= 1 |
| 160 | + && methodSymbol.Parameters[0].Name == "millisecondsDelay" |
| 161 | + && methodSymbol.Parameters[0].Type.SpecialType == SpecialType.System_Int32; |
| 162 | + } |
| 163 | + |
| 164 | + private static async Task<Document> ReplaceInvocationAsync( |
| 165 | + Document document, |
| 166 | + InvocationExpressionSyntax invocation, |
| 167 | + ExpressionSyntax replacement, |
| 168 | + CancellationToken cancellationToken) |
| 169 | + { |
| 170 | + SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false) |
| 171 | + ?? throw new System.InvalidOperationException("Could not get syntax root"); |
| 172 | + |
| 173 | + ExpressionSyntax replacementExpression = replacement |
| 174 | + .WithTriviaFrom(invocation) |
| 175 | + .WithAdditionalAnnotations(Formatter.Annotation); |
| 176 | + |
| 177 | + SyntaxNode newRoot = oldRoot.ReplaceNode(invocation, replacementExpression); |
| 178 | + return document.WithSyntaxRoot(newRoot); |
| 179 | + } |
| 180 | + } |
| 181 | +} |
0 commit comments