Skip to content

Commit 50117fb

Browse files
Add INTL0304 Task.Delay(0) analyzer
Implement analyzer and code fix for Task.Delay(0), including cancellation-token semantics and runtime-source documentation links. Add release metadata, docs updates, and expanded tests for await, CancellationToken.None, and safe code-fix applicability.
1 parent 9d6a6db commit 50117fb

7 files changed

Lines changed: 639 additions & 27 deletions

File tree

‎Directory.Packages.props‎

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
1-
<Project>
2-
<PropertyGroup>
3-
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
4-
<CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled>
5-
</PropertyGroup>
6-
<ItemGroup>
7-
<PackageVersion Include="coverlet.collector" Version="10.0.0" />
8-
<PackageVersion Include="IntelliTect.Analyzers" Version="0.2.0" />
9-
<PackageVersion Include="Microsoft.Build.Framework" Version="18.4.0" />
10-
<PackageVersion Include="Microsoft.Build.Locator" Version="1.11.2" />
11-
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="5.3.0" />
12-
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="5.3.0" />
13-
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="5.3.0" />
14-
<PackageVersion Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="10.0.203" />
15-
<PackageVersion Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="5.3.0" />
16-
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.5.1" />
17-
<PackageVersion Include="MSTest.TestAdapter" Version="4.2.2" />
18-
<PackageVersion Include="MSTest.TestFramework" Version="4.2.2" />
19-
<PackageVersion Include="System.CommandLine.DragonFruit" Version="0.4.0-alpha.25320.106" />
20-
<!-- Reference-only packages for test framework namespace resolution in analyzer tests -->
21-
<PackageVersion Include="xunit.v3.core" Version="3.2.2" />
22-
<PackageVersion Include="NUnit" Version="4.6.0" />
23-
<PackageVersion Include="TUnit.Core" Version="1.44.0" />
24-
</ItemGroup>
25-
</Project>
1+
<Project>
2+
<PropertyGroup>
3+
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
4+
<CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled>
5+
</PropertyGroup>
6+
<ItemGroup>
7+
<PackageVersion Include="coverlet.collector" Version="10.0.0" />
8+
<PackageVersion Include="IntelliTect.Analyzers" Version="0.2.0" />
9+
<PackageVersion Include="Microsoft.Build.Framework" Version="18.4.0" />
10+
<PackageVersion Include="Microsoft.Build.Locator" Version="1.11.2" />
11+
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="5.3.0" />
12+
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="5.3.0" />
13+
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="5.3.0" />
14+
<PackageVersion Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="10.0.203" />
15+
<PackageVersion Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="5.3.0" />
16+
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.5.1" />
17+
<PackageVersion Include="MSTest.TestAdapter" Version="4.2.2" />
18+
<PackageVersion Include="MSTest.TestFramework" Version="4.2.2" />
19+
<PackageVersion Include="System.CommandLine.DragonFruit" Version="0.4.0-alpha.25320.106" />
20+
<!-- Reference-only packages for test framework namespace resolution in analyzer tests -->
21+
<PackageVersion Include="xunit.v3.core" Version="3.2.2" />
22+
<PackageVersion Include="NUnit" Version="4.6.0" />
23+
<PackageVersion Include="TUnit.Core" Version="1.44.0" />
24+
</ItemGroup>
25+
</Project>
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
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

Comments
 (0)