Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docfx/analyzers/VSTHRD200.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ Methods that return awaitable types such as `Task` or `ValueTask`
should have an Async suffix.
Methods that do not return awaitable types should not use the Async suffix.

Custom async-focused return types can be configured to require the suffix.
See the [configuration](configuration.md#types-that-require-the-async-suffix) topic.

## Examples of patterns that are flagged by this analyzer

This `Task`-returning method should have a name that ends with Async:
Expand Down
12 changes: 12 additions & 0 deletions docfx/analyzers/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,15 @@ excluded from VSTHRD103 analysis by specifying them in a configuration file.
**Sample:** `[System.Data.SqlClient.SqlDataReader]::Read`

**Generic sample:** ``[Microsoft.EntityFrameworkCore.DbSet`1]::Add``

## Types that require the Async suffix

VSTHRD200 requires methods returning `Task`, `ValueTask`, and other async-focused types
to end with the `Async` suffix. Libraries can identify additional async-focused return
types with this configuration file.

**Filename:** `vs-threading.AsyncSuffixRequiredTypes.txt`

**Line format:** `[Namespace.TypeName]`

**Sample:** `[Microsoft.VisualStudio.Shell.Interop.IVsTask]`
27 changes: 23 additions & 4 deletions src/Microsoft.VisualStudio.Threading.Analyzers/CommonInterest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public static class CommonInterest
public static readonly Regex FileNamePatternForMethodsThatAssertMainThread = new Regex(@"^vs-threading\.MainThreadAssertingMethods(\..*)?.txt$", FileNamePatternRegexOptions);
public static readonly Regex FileNamePatternForMethodsThatSwitchToMainThread = new Regex(@"^vs-threading\.MainThreadSwitchingMethods(\..*)?.txt$", FileNamePatternRegexOptions);
public static readonly Regex FileNamePatternForSyncMethodsToExcludeFromVSTHRD103 = new Regex(@"^vs-threading\.SyncMethodsToExcludeFromVSTHRD103(\..*)?.txt$", FileNamePatternRegexOptions);
public static readonly Regex FileNamePatternForAsyncSuffixRequiredTypes = new Regex(@"^vs-threading\.AsyncSuffixRequiredTypes(\..*)?.txt$", FileNamePatternRegexOptions);

public static readonly IEnumerable<SyncBlockingMethod> JTFSyncBlockers =
[
Expand Down Expand Up @@ -577,20 +578,38 @@ public AwaitableTypeTester(HashSet<ITypeSymbol> awaitableTypes)

public bool IsAwaitableType(ITypeSymbol typeSymbol)
{
if (this.awaitableTypes.Contains(typeSymbol))
if (this.IsKnownAwaitableType(typeSymbol))
{
return true;
}

if (typeSymbol is INamedTypeSymbol { IsGenericType: true } genericTypeSymbol)
if (typeSymbol is INamedTypeSymbol namedTypeSymbol)
{
if (this.awaitableTypes.Contains(genericTypeSymbol.ConstructUnboundGenericType()))
for (INamedTypeSymbol? baseType = namedTypeSymbol.BaseType; baseType is not null; baseType = baseType.BaseType)
{
return true;
if (this.IsKnownAwaitableType(baseType))
{
return true;
}
}

foreach (INamedTypeSymbol interfaceType in namedTypeSymbol.AllInterfaces)
{
if (this.IsKnownAwaitableType(interfaceType))
{
return true;
}
}
}

return false;
}

private bool IsKnownAwaitableType(ITypeSymbol typeSymbol)
{
return this.awaitableTypes.Contains(typeSymbol)
|| (typeSymbol is INamedTypeSymbol { IsGenericType: true } genericTypeSymbol
&& this.awaitableTypes.Contains(genericTypeSymbol.ConstructUnboundGenericType()));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,28 +52,37 @@ public override void Initialize(AnalysisContext context)
context.RegisterCompilationStartAction(context =>
{
CommonInterest.AwaitableTypeTester awaitableTypes = CommonInterest.CollectAwaitableTypes(context.Compilation, context.CancellationToken);
context.RegisterSymbolAction(Utils.DebuggableWrapper(context => this.AnalyzeNode(context, awaitableTypes)), SymbolKind.Method);
context.RegisterOperationAction(Utils.DebuggableWrapper(context => this.AnalyzeLocalFunction(context, awaitableTypes)), OperationKind.LocalFunction);
ImmutableArray<CommonInterest.TypeMatchSpec> asyncSuffixRequiredTypes = CommonInterest.ReadTypesAndMembers(
context.Options,
CommonInterest.FileNamePatternForAsyncSuffixRequiredTypes,
context.CancellationToken).ToImmutableArray();
context.RegisterSymbolAction(Utils.DebuggableWrapper(context => this.AnalyzeNode(context, awaitableTypes, asyncSuffixRequiredTypes)), SymbolKind.Method);
context.RegisterOperationAction(Utils.DebuggableWrapper(context => this.AnalyzeLocalFunction(context, awaitableTypes, asyncSuffixRequiredTypes)), OperationKind.LocalFunction);
});
}

private void AnalyzeLocalFunction(OperationAnalysisContext context, CommonInterest.AwaitableTypeTester awaitableTypes)
private void AnalyzeLocalFunction(OperationAnalysisContext context, CommonInterest.AwaitableTypeTester awaitableTypes, ImmutableArray<CommonInterest.TypeMatchSpec> asyncSuffixRequiredTypes)
{
if (this.AnalyzeMethodSymbol(context.Compilation, ((ILocalFunctionOperation)context.Operation).Symbol, awaitableTypes, context.CancellationToken) is Diagnostic diagnostic)
if (this.AnalyzeMethodSymbol(context.Compilation, ((ILocalFunctionOperation)context.Operation).Symbol, awaitableTypes, asyncSuffixRequiredTypes, context.CancellationToken) is Diagnostic diagnostic)
{
context.ReportDiagnostic(diagnostic);
}
}

private void AnalyzeNode(SymbolAnalysisContext context, CommonInterest.AwaitableTypeTester awaitableTypes)
private void AnalyzeNode(SymbolAnalysisContext context, CommonInterest.AwaitableTypeTester awaitableTypes, ImmutableArray<CommonInterest.TypeMatchSpec> asyncSuffixRequiredTypes)
{
if (this.AnalyzeMethodSymbol(context.Compilation, (IMethodSymbol)context.Symbol, awaitableTypes, context.CancellationToken) is Diagnostic diagnostic)
if (this.AnalyzeMethodSymbol(context.Compilation, (IMethodSymbol)context.Symbol, awaitableTypes, asyncSuffixRequiredTypes, context.CancellationToken) is Diagnostic diagnostic)
{
context.ReportDiagnostic(diagnostic);
}
}

private Diagnostic? AnalyzeMethodSymbol(Compilation compilation, IMethodSymbol methodSymbol, CommonInterest.AwaitableTypeTester awaitableTypes, CancellationToken cancellationToken)
private Diagnostic? AnalyzeMethodSymbol(
Compilation compilation,
IMethodSymbol methodSymbol,
CommonInterest.AwaitableTypeTester awaitableTypes,
ImmutableArray<CommonInterest.TypeMatchSpec> asyncSuffixRequiredTypes,
CancellationToken cancellationToken)
{
if (methodSymbol.AssociatedSymbol is IPropertySymbol)
{
Expand All @@ -93,7 +102,8 @@ private void AnalyzeNode(SymbolAnalysisContext context, CommonInterest.Awaitable
return null;
}

bool hasAsyncFocusedReturnType = Utils.HasAsyncCompatibleReturnType(methodSymbol);
bool hasAsyncFocusedReturnType = Utils.HasAsyncCompatibleReturnType(methodSymbol)
|| asyncSuffixRequiredTypes.Contains(methodSymbol.ReturnType, memberSymbol: null);

bool actuallyEndsWithAsync = methodSymbol.Name.EndsWith(MandatoryAsyncSuffix, StringComparison.CurrentCulture);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[TestNS.AsyncFocusedAwaitable]
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,35 @@ public void GetResult()
await CSVerify.VerifyAnalyzerAsync(test);
}

[Fact]
public async Task DerivedCustomAwaitable_ProducesDiagnostic()
{
string test = """
using System.Runtime.CompilerServices;

class Test
{
void Foo()
{
[|BarAsync()|];
}

DerivedCustomTask BarAsync() => new();
}

class CustomTask
{
public TaskAwaiter GetAwaiter() => default;
}

class DerivedCustomTask : CustomTask
{
}
""";

await CSVerify.VerifyAnalyzerAsync(test);
}

[Fact]
public async Task CustomAwaitableLikeType_ProducesNoDiagnostic()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -655,4 +655,62 @@ async Task BarAsync()
DiagnosticResult expected = CSVerify.Diagnostic(AddSuffixDescriptor).WithLocation(0);
await CSVerify.VerifyCodeFixAsync(test, expected, fix);
}

[Fact]
public async Task DerivedAwaitableReturningMethodWithSuffix_GeneratesNoWarning()
{
string test = """
using System.Runtime.CompilerServices;

class Awaitable
{
public TaskAwaiter GetAwaiter() => default;
}

class DerivedAwaitable : Awaitable
{
}

class Test
{
DerivedAwaitable GetValueAsync() => new();
}
""";

await CSVerify.VerifyAnalyzerAsync(test);
}

[Fact]
public async Task ConfiguredAsyncFocusedTypeWithoutSuffix_GeneratesWarning()
{
string test = """
namespace TestNS
{
class AsyncFocusedAwaitable
{
}

class Test
{
AsyncFocusedAwaitable {|#0:GetValue|}() => new();
}
}
""";
string fix = """
namespace TestNS
{
class AsyncFocusedAwaitable
{
}

class Test
{
AsyncFocusedAwaitable GetValueAsync() => new();
}
}
""";

DiagnosticResult expected = CSVerify.Diagnostic(AddSuffixDescriptor).WithLocation(0);
await CSVerify.VerifyCodeFixAsync(test, expected, fix);
}
}
Loading