Skip to content
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

Ensure ForwardCancellationTokenAnalyzer treats usages of default expressions properly #6617

Merged
merged 3 commits into from
Dec 2, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,79 @@ public class Bar {}");
public class ForwardCancellationTokenTestsCSharp8 : ForwardCancellationTokenTests
{
protected override LanguageVersion AnalyzerLanguageVersion => LanguageVersion.CSharp8;

[TestCase("default(CancellationToken)")]
[TestCase("default")]
[TestCase("CancellationToken.None")]
[TestCase("new CancellationToken(true)")]
[TestCase("context.CancellationToken")]
public Task DefaultTokenParameters(string parameterValue) => Assert(ForwardCancellationTokenAnalyzer.DiagnosticId, @"
using System;
using System.Threading;
using System.Threading.Tasks;
using NServiceBus;
public class Foo : IHandleMessages<TestMessage>
{
public async Task Handle(TestMessage message, IMessageHandlerContext context)
{
await Test(""hi"", 1, DateTime.Now, " + parameterValue + @");
await Test(default(string), default(int), default(DateTime), " + parameterValue + @");
await Test(default, default, default, " + parameterValue + @");

await [|Test(""hi"", 1, DateTime.Now)|];
await [|Test(default(string), default(int), default(DateTime))|];
await [|Test(default, default, default)|];
}

Task Test(string s, int i, DateTime d, CancellationToken token = default)
{
System.Console.WriteLine($""{{s}} {{i}} {{d}}"");
return Task.Delay(i, token);
}
}
public class TestMessage : ICommand {}
");

#if NET // IAsyncEnumerable requires package Microsoft.Bcl.AsyncInterfaces on .NET Framework

[TestCase("AsyncEnumerator(context.CancellationToken)")]
[TestCase("AsyncEnumerator(CancellationToken.None)")]
[TestCase("AsyncEnumerator(default(CancellationToken))")]
[TestCase("AsyncEnumerator(default)")]
[TestCase("[|AsyncEnumerator()|]")]
[TestCase("[|AsyncEnumerator()|].WithCancellation(context.CancellationToken)")]
[TestCase("[|AsyncEnumerator()|].WithCancellation(CancellationToken.None)")]
[TestCase("[|AsyncEnumerator()|].WithCancellation(default(CancellationToken))")]
[TestCase("[|AsyncEnumerator()|].WithCancellation(default)")]
public Task AwaitForeach(string asyncCall) => Assert(ForwardCancellationTokenAnalyzer.DiagnosticId, @"
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using NServiceBus;
using System.Threading;
using System.Threading.Tasks;
public class Foo : IHandleMessages<TestMessage>
{
public async Task Handle(TestMessage message, IMessageHandlerContext context)
{
await foreach (int item in " + asyncCall + @")
{
Console.WriteLine(item);
}
}

static async IAsyncEnumerable<int> AsyncEnumerator([EnumeratorCancellation] CancellationToken cancellationToken = default)
{
for (int i = 0; i < 10; i++)
{
await Task.Delay(0, cancellationToken);
yield return i;
}
}
}
public class TestMessage : ICommand {}
");
#endif
}

public class ForwardCancellationTokenTestsCSharp9 : ForwardCancellationTokenTestsCSharp8
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ static AnalyzerTestFixture()
MetadataReference.CreateFromFile(typeof(System.Linq.Expressions.Expression).GetTypeInfo().Assembly.Location),
#if NET
MetadataReference.CreateFromFile(Assembly.Load("System.Runtime").Location),
MetadataReference.CreateFromFile(Assembly.Load("System.Console").Location),
MetadataReference.CreateFromFile(Assembly.Load("System.Private.CoreLib").Location),
#endif
MetadataReference.CreateFromFile(typeof(EndpointConfiguration).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(IUniformSession).GetTypeInfo().Assembly.Location));
Expand Down
38 changes: 32 additions & 6 deletions src/NServiceBus.Core.Analyzer/ForwardCancellationTokenAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,20 +177,46 @@ static bool LooksLikeCancellationToken(ExpressionSyntax expression, string calle
}
}

if (expression is ObjectCreationExpressionSyntax objectCreation &&
objectCreation.Type is IdentifierNameSyntax objectCreationTypeName &&
objectCreationTypeName.Identifier.ValueText == "CancellationToken")
// new CancellationToken(...)
if (expression is ObjectCreationExpressionSyntax objectCreation && TypeSyntaxLooksLikeCancellationToken(objectCreation.Type))
{
return true;
}

// default(CancellationToken)
if (expression is DefaultExpressionSyntax defaultSyntax && TypeSyntaxLooksLikeCancellationToken(defaultSyntax.Type))
{
return true;
}

// Note: `default` on its own is a LiteralExpressionSyntax, not a DefaultExpressionSyntax, so when this is used
// as a parameter we can't tell whether it's a CancellationToken at the lexical level and must allow IsCancellationToken
// to make the determination by consulting the semantic model
return false;
}

static bool TypeSyntaxLooksLikeCancellationToken(TypeSyntax typeSyntax) =>
typeSyntax is IdentifierNameSyntax identifierSyntax && identifierSyntax.Identifier.ValueText == "CancellationToken";

static bool IsCancellationToken(ExpressionSyntax expressionSyntax, SyntaxNodeAnalysisContext context, INamedTypeSymbol cancellationTokenType)
{
var expressionSymbol = context.SemanticModel.GetSymbolInfo(expressionSyntax, context.CancellationToken).Symbol;
return expressionSymbol.GetTypeSymbolOrDefault()?.Equals(cancellationTokenType, SymbolEqualityComparer.IncludeNullability) ?? false;
var typeSymbol = GetTypeSymbolFromExpression(expressionSyntax, context);
return typeSymbol?.Equals(cancellationTokenType, SymbolEqualityComparer.IncludeNullability) ?? false;
}

static ITypeSymbol GetTypeSymbolFromExpression(ExpressionSyntax expression, SyntaxNodeAnalysisContext context)
{
if (expression is LiteralExpressionSyntax) // `default` as a parameter
{
var typeInfo = context.SemanticModel.GetTypeInfo(expression, context.CancellationToken);
return typeInfo.Type;
}
else
{
var symbolInfo = context.SemanticModel.GetSymbolInfo(expression, context.CancellationToken);
var expressionSymbol = symbolInfo.Symbol;
return expressionSymbol.GetTypeSymbolOrDefault();
}
}

static IMethodSymbol GetRecommendedMethod(
Expand Down Expand Up @@ -247,7 +273,7 @@ static bool IsCancellationToken(ExpressionSyntax expressionSyntax, SyntaxNodeAna

// if adding a cancellation token to the args will not put it in the right place
static string GetRequiredArgName(IMethodSymbol recommendedMethod, IParameterSymbol extraParam, SeparatedSyntaxList<ArgumentSyntax> args) =>
!recommendedMethod.Parameters[args.Count].Equals(extraParam, SymbolEqualityComparer.IncludeNullability) ? extraParam.Name : null;
args.Count < recommendedMethod.Parameters.Length && !recommendedMethod.Parameters[args.Count].Equals(extraParam, SymbolEqualityComparer.IncludeNullability) ? extraParam.Name : null;

static INamedTypeSymbol GetCalledType(InvocationExpressionSyntax call, IMethodSymbol calledMethod, SyntaxNodeAnalysisContext context)
{
Expand Down