-
Notifications
You must be signed in to change notification settings - Fork 16
feat: Add INTL0304 analyzer for Task.Delay(0) usage #443
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BenjaminMichaelis
wants to merge
4
commits into
main
Choose a base branch
from
benjaminmichaelis/issue-55-plan
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
50117fb
Add INTL0304 Task.Delay(0) analyzer
BenjaminMichaelis b3c18a2
Eliminate DRY violations in INTL0304 implementation
BenjaminMichaelis ed2cb5d
Address PR review feedback for INTL0304 code fix
BenjaminMichaelis 156725d
chore: merge origin/main into issue-55-plan
BenjaminMichaelis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,25 +1,25 @@ | ||
| <Project> | ||
| <PropertyGroup> | ||
| <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally> | ||
| <CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled> | ||
| </PropertyGroup> | ||
| <ItemGroup> | ||
| <PackageVersion Include="coverlet.collector" Version="10.0.0" /> | ||
| <PackageVersion Include="IntelliTect.Analyzers" Version="0.2.0" /> | ||
| <PackageVersion Include="Microsoft.Build.Framework" Version="18.4.0" /> | ||
| <PackageVersion Include="Microsoft.Build.Locator" Version="1.11.2" /> | ||
| <PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="5.3.0" /> | ||
| <PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="5.3.0" /> | ||
| <PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="5.3.0" /> | ||
| <PackageVersion Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="10.0.203" /> | ||
| <PackageVersion Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="5.3.0" /> | ||
| <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.5.1" /> | ||
| <PackageVersion Include="MSTest.TestAdapter" Version="4.2.2" /> | ||
| <PackageVersion Include="MSTest.TestFramework" Version="4.2.2" /> | ||
| <PackageVersion Include="System.CommandLine.DragonFruit" Version="0.4.0-alpha.25320.106" /> | ||
| <!-- Reference-only packages for test framework namespace resolution in analyzer tests --> | ||
| <PackageVersion Include="xunit.v3.core" Version="3.2.2" /> | ||
| <PackageVersion Include="NUnit" Version="4.6.0" /> | ||
| <PackageVersion Include="TUnit.Core" Version="1.44.0" /> | ||
| </ItemGroup> | ||
| </Project> | ||
| <Project> | ||
| <PropertyGroup> | ||
| <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally> | ||
| <CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled> | ||
| </PropertyGroup> | ||
| <ItemGroup> | ||
| <PackageVersion Include="coverlet.collector" Version="10.0.0" /> | ||
| <PackageVersion Include="IntelliTect.Analyzers" Version="0.2.0" /> | ||
| <PackageVersion Include="Microsoft.Build.Framework" Version="18.4.0" /> | ||
| <PackageVersion Include="Microsoft.Build.Locator" Version="1.11.2" /> | ||
| <PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="5.3.0" /> | ||
| <PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="5.3.0" /> | ||
| <PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="5.3.0" /> | ||
| <PackageVersion Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="10.0.203" /> | ||
| <PackageVersion Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="5.3.0" /> | ||
| <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.5.1" /> | ||
| <PackageVersion Include="MSTest.TestAdapter" Version="4.2.2" /> | ||
| <PackageVersion Include="MSTest.TestFramework" Version="4.2.2" /> | ||
| <PackageVersion Include="System.CommandLine.DragonFruit" Version="0.4.0-alpha.25320.106" /> | ||
| <!-- Reference-only packages for test framework namespace resolution in analyzer tests --> | ||
| <PackageVersion Include="xunit.v3.core" Version="3.2.2" /> | ||
| <PackageVersion Include="NUnit" Version="4.6.0" /> | ||
| <PackageVersion Include="TUnit.Core" Version="1.44.0" /> | ||
| </ItemGroup> | ||
| </Project> |
163 changes: 163 additions & 0 deletions
163
IntelliTect.Analyzer/IntelliTect.Analyzer.CodeFixes/TaskDelayZero.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| 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 Microsoft.CodeAnalysis.Operations; | ||
| using Microsoft.CodeAnalysis.Text; | ||
|
|
||
| namespace IntelliTect.Analyzer.CodeFixes | ||
| { | ||
| [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(TaskDelayZero))] | ||
| [Shared] | ||
| public class TaskDelayZero : CodeFixProvider | ||
| { | ||
| private const string Title = "Use Task.CompletedTask"; | ||
|
|
||
| public sealed override ImmutableArray<string> FixableDiagnosticIds => | ||
| ImmutableArray.Create(Analyzers.TaskDelayZero.DiagnosticId); | ||
|
|
||
| public sealed override FixAllProvider GetFixAllProvider() => | ||
| WellKnownFixAllProviders.BatchFixer; | ||
|
|
||
| public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| SyntaxNode? root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
| if (root is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| Diagnostic diagnostic = context.Diagnostics.First(); | ||
| TextSpan diagnosticSpan = diagnostic.Location.SourceSpan; | ||
|
|
||
| InvocationExpressionSyntax? invocation = root.FindToken(diagnosticSpan.Start) | ||
| .Parent?.AncestorsAndSelf() | ||
| .OfType<InvocationExpressionSyntax>() | ||
| .FirstOrDefault(); | ||
| if (invocation is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| SemanticModel? semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); | ||
| if (semanticModel is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| if (semanticModel.GetOperation(invocation, context.CancellationToken) is not IInvocationOperation invocationOperation) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| ExpressionSyntax? replacement = CreateReplacementExpression(invocationOperation); | ||
| if (replacement is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title: Title, | ||
| createChangedDocument: c => ReplaceInvocationAsync(context.Document, invocation, replacement, c), | ||
| equivalenceKey: Title), | ||
| diagnostic); | ||
| } | ||
|
|
||
| private static ExpressionSyntax? CreateReplacementExpression(IInvocationOperation invocation) | ||
| { | ||
| if (!IntelliTect.Analyzer.Analyzers.TaskDelayZero.IsTaskDelayWithIntMilliseconds(invocation.TargetMethod)) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| IArgumentOperation? millisecondsDelayArgument = invocation.Arguments | ||
| .FirstOrDefault(a => a.Parameter?.Name == "millisecondsDelay"); | ||
| if (millisecondsDelayArgument?.Value.ConstantValue is not { HasValue: true, Value: int millisecondsDelay } | ||
| || millisecondsDelay != 0) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| IArgumentOperation? cancellationTokenArgument = invocation.Arguments | ||
| .FirstOrDefault(a => a.Parameter?.Name == "cancellationToken"); | ||
| if (cancellationTokenArgument is null) | ||
| { | ||
| return SyntaxFactory.ParseExpression("global::System.Threading.Tasks.Task.CompletedTask"); | ||
| } | ||
|
|
||
| if (cancellationTokenArgument.Value.Syntax is not ExpressionSyntax cancellationTokenExpression) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| if (!IsSideEffectFree(cancellationTokenArgument.Value)) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| string tokenExpressionText = NormalizeCancellationTokenExpression(cancellationTokenExpression); | ||
|
|
||
| // Runtime behavior reference: | ||
| // https://github.com/dotnet/runtime/blob/1acc89c305165239a5a824567a3176b6b3342790/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs#L5907-L5911 | ||
| // Task.Delay(0, token) maps to: | ||
| // token.IsCancellationRequested ? Task.FromCanceled(token) : Task.CompletedTask | ||
| return SyntaxFactory.ParseExpression( | ||
| $"({tokenExpressionText}.IsCancellationRequested ? global::System.Threading.Tasks.Task.FromCanceled({tokenExpressionText}) : global::System.Threading.Tasks.Task.CompletedTask)"); | ||
| } | ||
|
|
||
| private static string NormalizeCancellationTokenExpression(ExpressionSyntax cancellationTokenExpression) | ||
| { | ||
| return cancellationTokenExpression.Kind() switch | ||
| { | ||
| SyntaxKind.DefaultLiteralExpression => "default(global::System.Threading.CancellationToken)", | ||
| SyntaxKind.DefaultExpression => cancellationTokenExpression.WithoutTrivia().ToString() == "default" | ||
| ? "default(global::System.Threading.CancellationToken)" | ||
| : cancellationTokenExpression.WithoutTrivia().ToString(), | ||
| _ => cancellationTokenExpression.WithoutTrivia().ToString() | ||
| }; | ||
| } | ||
|
|
||
| private static bool IsSideEffectFree(IOperation operation) | ||
| { | ||
| return operation switch | ||
| { | ||
| ILocalReferenceOperation => true, | ||
| IParameterReferenceOperation => true, | ||
| IDefaultValueOperation => true, | ||
| IConversionOperation conversion => IsSideEffectFree(conversion.Operand), | ||
| IParenthesizedOperation parenthesized => IsSideEffectFree(parenthesized.Operand), | ||
| IPropertyReferenceOperation propertyReference | ||
| when propertyReference.Instance is null | ||
| && propertyReference.Property.Name == "None" | ||
| && propertyReference.Property.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) | ||
| == "global::System.Threading.CancellationToken" => true, | ||
| _ => false | ||
| }; | ||
| } | ||
|
|
||
| private static async Task<Document> ReplaceInvocationAsync( | ||
| Document document, | ||
| InvocationExpressionSyntax invocation, | ||
| ExpressionSyntax replacement, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false) | ||
| ?? throw new System.InvalidOperationException("Could not get syntax root"); | ||
|
|
||
| ExpressionSyntax replacementExpression = replacement | ||
| .WithTriviaFrom(invocation) | ||
| .WithAdditionalAnnotations(Formatter.Annotation); | ||
|
|
||
| SyntaxNode newRoot = oldRoot.ReplaceNode(invocation, replacementExpression); | ||
| return document.WithSyntaxRoot(newRoot); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.