diff --git a/docfx/analyzers/VSTHRD003.md b/docfx/analyzers/VSTHRD003.md index 49d8ad87b..c40a3d0fc 100644 --- a/docfx/analyzers/VSTHRD003.md +++ b/docfx/analyzers/VSTHRD003.md @@ -10,6 +10,47 @@ When required to await a task that was started earlier, start it within a delega `JoinableTaskFactory.RunAsync`, storing the resulting `JoinableTask` in a field or variable. You can safely await the `JoinableTask` later. +## Suppressing warnings for completed tasks + +If you have a property, method, or field that returns a pre-completed task (such as a cached task with a known value), +you can suppress this warning by applying the `[CompletedTask]` attribute to the member. +This attribute is automatically included when you install the `Microsoft.VisualStudio.Threading.Analyzers` package. + +```csharp +[Microsoft.VisualStudio.Threading.CompletedTask] +private static readonly Task TrueTask = Task.FromResult(true); + +async Task MyMethodAsync() +{ + await TrueTask; // No warning - TrueTask is marked as a completed task +} +``` + +**Important restrictions:** +- Fields must be marked `readonly` when using this attribute +- Properties must not have non-private setters (getter-only or private setters are allowed) + +### Marking external types + +You can also apply the attribute at the assembly level to mark members in external types that you don't control: + +```csharp +[assembly: Microsoft.VisualStudio.Threading.CompletedTask(Member = "ExternalLibrary.ExternalClass.CompletedTaskProperty")] +``` + +This is useful when you're using third-party libraries that have pre-completed tasks but aren't annotated with the attribute. +The `Member` property should contain the fully qualified name of the member in the format `Namespace.TypeName.MemberName`. + +The analyzer already recognizes the following as safe to await without the attribute: +- `Task.CompletedTask` +- `Task.FromResult(...)` +- `Task.FromCanceled(...)` +- `Task.FromException(...)` +- `TplExtensions.CompletedTask` +- `TplExtensions.CanceledTask` +- `TplExtensions.TrueTask` +- `TplExtensions.FalseTask` + ## Simple examples of patterns that are flagged by this analyzer The following example would likely deadlock if `MyMethod` were called on the main thread, diff --git a/src/Microsoft.VisualStudio.Threading.Analyzers.CSharp/VSTHRD003UseJtfRunAsyncAnalyzer.cs b/src/Microsoft.VisualStudio.Threading.Analyzers.CSharp/VSTHRD003UseJtfRunAsyncAnalyzer.cs index 19864c651..4c4051ae6 100644 --- a/src/Microsoft.VisualStudio.Threading.Analyzers.CSharp/VSTHRD003UseJtfRunAsyncAnalyzer.cs +++ b/src/Microsoft.VisualStudio.Threading.Analyzers.CSharp/VSTHRD003UseJtfRunAsyncAnalyzer.cs @@ -40,6 +40,15 @@ public class VSTHRD003UseJtfRunAsyncAnalyzer : DiagnosticAnalyzer { public const string Id = "VSTHRD003"; + public static readonly DiagnosticDescriptor InvalidAttributeUseDescriptor = new DiagnosticDescriptor( + id: Id, + title: new LocalizableResourceString(nameof(Strings.VSTHRD003InvalidAttributeUse_Title), Strings.ResourceManager, typeof(Strings)), + messageFormat: new LocalizableResourceString(nameof(Strings.VSTHRD003InvalidAttributeUse_MessageFormat), Strings.ResourceManager, typeof(Strings)), + helpLinkUri: Utils.GetHelpLink(Id), + category: "Usage", + defaultSeverity: DiagnosticSeverity.Warning, + isEnabledByDefault: true); + internal static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( id: Id, title: new LocalizableResourceString(nameof(Strings.VSTHRD003_Title), Strings.ResourceManager, typeof(Strings)), @@ -54,7 +63,7 @@ public override ImmutableArray SupportedDiagnostics { get { - return ImmutableArray.Create(Descriptor); + return ImmutableArray.Create(InvalidAttributeUseDescriptor, Descriptor); } } @@ -69,20 +78,77 @@ public override void Initialize(AnalysisContext context) context.RegisterSyntaxNodeAction(Utils.DebuggableWrapper(this.AnalyzeArrowExpressionClause), SyntaxKind.ArrowExpressionClause); context.RegisterSyntaxNodeAction(Utils.DebuggableWrapper(this.AnalyzeLambdaExpression), SyntaxKind.SimpleLambdaExpression); context.RegisterSyntaxNodeAction(Utils.DebuggableWrapper(this.AnalyzeLambdaExpression), SyntaxKind.ParenthesizedLambdaExpression); + context.RegisterSymbolAction(Utils.DebuggableWrapper(this.AnalyzeSymbolForInvalidAttributeUse), SymbolKind.Field, SymbolKind.Property, SymbolKind.Method); } - private static bool IsSymbolAlwaysOkToAwait(ISymbol? symbol) + private static bool IsSymbolAlwaysOkToAwait(ISymbol? symbol, Compilation compilation) { - if (symbol is IFieldSymbol field) + if (symbol is null) { - // Allow the TplExtensions.CompletedTask and related fields. - if (field.ContainingType.Name == Types.TplExtensions.TypeName && field.BelongsToNamespace(Types.TplExtensions.Namespace) && - (field.Name == Types.TplExtensions.CompletedTask || field.Name == Types.TplExtensions.CanceledTask || field.Name == Types.TplExtensions.TrueTask || field.Name == Types.TplExtensions.FalseTask)) + return false; + } + + // Check if the symbol has the CompletedTaskAttribute directly applied + if (symbol.GetAttributes().Any(attr => + attr.AttributeClass?.Name == Types.CompletedTaskAttribute.TypeName && + attr.AttributeClass.BelongsToNamespace(Types.CompletedTaskAttribute.Namespace))) + { + // Validate that the attribute is used correctly + if (symbol is IFieldSymbol fieldSymbol) { - return true; + // Fields must be readonly + if (!fieldSymbol.IsReadOnly) + { + return false; + } + } + else if (symbol is IPropertySymbol propertySymbol) + { + // Properties must not have non-private setters + // Init accessors are only allowed if the property itself is private + if (propertySymbol.SetMethod is not null) + { + if (propertySymbol.SetMethod.IsInitOnly) + { + // Init accessor - only allowed if property is private + if (propertySymbol.DeclaredAccessibility != Accessibility.Private) + { + return false; + } + } + else if (propertySymbol.SetMethod.DeclaredAccessibility != Accessibility.Private) + { + // Regular setter must be private + return false; + } + } } + + return true; } - else if (symbol is IPropertySymbol property) + + // Check for assembly-level CompletedTaskAttribute + foreach (AttributeData assemblyAttr in compilation.Assembly.GetAttributes()) + { + if (assemblyAttr.AttributeClass?.Name == Types.CompletedTaskAttribute.TypeName && + assemblyAttr.AttributeClass.BelongsToNamespace(Types.CompletedTaskAttribute.Namespace)) + { + // Look for the Member named argument + foreach (KeyValuePair namedArg in assemblyAttr.NamedArguments) + { + if (namedArg.Key == "Member" && namedArg.Value.Value is string memberName) + { + // Check if this symbol matches the specified member name + if (IsSymbolMatchingMemberName(symbol, memberName)) + { + return true; + } + } + } + } + } + + if (symbol is IPropertySymbol property) { // Explicitly allow Task.CompletedTask if (property.ContainingType.Name == Types.Task.TypeName && property.BelongsToNamespace(Types.Task.Namespace) && @@ -95,6 +161,102 @@ private static bool IsSymbolAlwaysOkToAwait(ISymbol? symbol) return false; } + private static bool IsSymbolMatchingMemberName(ISymbol symbol, string memberName) + { + // Build the fully qualified name of the symbol + string fullyQualifiedName = GetFullyQualifiedName(symbol); + + // Compare with the member name (case-sensitive) + return string.Equals(fullyQualifiedName, memberName, StringComparison.Ordinal); + } + + private static string GetFullyQualifiedName(ISymbol symbol) + { + if (symbol.ContainingType is null) + { + return symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + } + + // For members (properties, fields, methods), construct: Namespace.TypeName.MemberName + List parts = new List(); + + // Add member name + parts.Add(symbol.Name); + + // Add containing type hierarchy + INamedTypeSymbol? currentType = symbol.ContainingType; + while (currentType is not null) + { + parts.Insert(0, currentType.Name); + currentType = currentType.ContainingType; + } + + // Add namespace + if (symbol.ContainingNamespace is not null && !symbol.ContainingNamespace.IsGlobalNamespace) + { + parts.Insert(0, symbol.ContainingNamespace.ToDisplayString()); + } + + return string.Join(".", parts); + } + + private void AnalyzeSymbolForInvalidAttributeUse(SymbolAnalysisContext context) + { + ISymbol symbol = context.Symbol; + + // Check if the symbol has the CompletedTaskAttribute + AttributeData? completedTaskAttr = symbol.GetAttributes().FirstOrDefault(attr => + attr.AttributeClass?.Name == Types.CompletedTaskAttribute.TypeName && + attr.AttributeClass.BelongsToNamespace(Types.CompletedTaskAttribute.Namespace)); + + if (completedTaskAttr is null) + { + return; + } + + string? errorMessage = null; + + if (symbol is IFieldSymbol fieldSymbol) + { + // Fields must be readonly + if (!fieldSymbol.IsReadOnly) + { + errorMessage = Strings.VSTHRD003InvalidAttributeUse_FieldNotReadonly; + } + } + else if (symbol is IPropertySymbol propertySymbol) + { + // Check for init accessor (which is a special kind of setter) + if (propertySymbol.SetMethod is not null) + { + // Init accessors are only allowed if the property itself is private + if (propertySymbol.SetMethod.IsInitOnly) + { + if (propertySymbol.DeclaredAccessibility != Accessibility.Private) + { + errorMessage = Strings.VSTHRD003InvalidAttributeUse_PropertyWithNonPrivateInit; + } + } + else if (propertySymbol.SetMethod.DeclaredAccessibility != Accessibility.Private) + { + // Non-private setters are not allowed + errorMessage = Strings.VSTHRD003InvalidAttributeUse_PropertyWithNonPrivateSetter; + } + } + } + + // Methods are always allowed + if (errorMessage is not null) + { + // Report diagnostic on the attribute location + Location? location = completedTaskAttr.ApplicationSyntaxReference?.GetSyntax(context.CancellationToken).GetLocation(); + if (location is not null) + { + context.ReportDiagnostic(Diagnostic.Create(InvalidAttributeUseDescriptor, location, errorMessage)); + } + } + } + private void AnalyzeArrowExpressionClause(SyntaxNodeAnalysisContext context) { var arrowExpressionClause = (ArrowExpressionClauseSyntax)context.Node; @@ -183,7 +345,7 @@ private void AnalyzeAwaitExpression(SyntaxNodeAnalysisContext context) symbolType = localSymbol.Type; dataflowAnalysisCompatibleVariable = true; break; - case IPropertySymbol propertySymbol when !IsSymbolAlwaysOkToAwait(propertySymbol): + case IPropertySymbol propertySymbol when !IsSymbolAlwaysOkToAwait(propertySymbol, context.Compilation): symbolType = propertySymbol.Type; if (focusedExpression is MemberAccessExpressionSyntax memberAccessExpression) @@ -277,7 +439,7 @@ private void AnalyzeAwaitExpression(SyntaxNodeAnalysisContext context) } ISymbol? definition = declarationSemanticModel.GetSymbolInfo(memberAccessSyntax, cancellationToken).Symbol; - if (IsSymbolAlwaysOkToAwait(definition)) + if (IsSymbolAlwaysOkToAwait(definition, context.Compilation)) { return null; } @@ -288,6 +450,12 @@ private void AnalyzeAwaitExpression(SyntaxNodeAnalysisContext context) break; case IMethodSymbol methodSymbol: + // Check if the method itself has the CompletedTaskAttribute + if (IsSymbolAlwaysOkToAwait(methodSymbol, context.Compilation)) + { + return null; + } + if (Utils.IsTask(methodSymbol.ReturnType) && focusedExpression is InvocationExpressionSyntax invocationExpressionSyntax) { // Consider all arguments diff --git a/src/Microsoft.VisualStudio.Threading.Analyzers.CodeFixes/buildTransitive/AdditionalFiles/CompletedTaskAttribute.cs b/src/Microsoft.VisualStudio.Threading.Analyzers.CodeFixes/buildTransitive/AdditionalFiles/CompletedTaskAttribute.cs new file mode 100644 index 000000000..4a2b0bb66 --- /dev/null +++ b/src/Microsoft.VisualStudio.Threading.Analyzers.CodeFixes/buildTransitive/AdditionalFiles/CompletedTaskAttribute.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +#if !COMPLETEDTASKATTRIBUTE_INCLUDED +#define COMPLETEDTASKATTRIBUTE_INCLUDED + +namespace Microsoft.VisualStudio.Threading; + +/// +/// Indicates that a property, method, or field returns a task that is already completed. +/// This suppresses VSTHRD003 warnings when awaiting the returned task. +/// +/// +/// +/// Apply this attribute to properties, methods, or fields that return cached, pre-completed tasks +/// such as singleton instances with well-known immutable values. +/// The VSTHRD003 analyzer will not report warnings when these members are awaited, +/// as awaiting an already-completed task does not pose a risk of deadlock. +/// +/// +/// This attribute can also be applied at the assembly level to mark members in external types +/// that you don't control: +/// +/// [assembly: CompletedTask(Member = "System.Threading.Tasks.TplExtensions.TrueTask")] +/// +/// +/// +[System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field | System.AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)] +#pragma warning disable SA1649 // File name should match first type name +internal sealed class CompletedTaskAttribute : System.Attribute +{ + /// + /// Initializes a new instance of the class. + /// + public CompletedTaskAttribute() + { + } + + /// + /// Gets or sets the fully qualified name of the member that returns a completed task. + /// This is only used when the attribute is applied at the assembly level. + /// + /// + /// The format should be: "Namespace.TypeName.MemberName". + /// For example: "System.Threading.Tasks.TplExtensions.TrueTask". + /// + public string? Member { get; set; } +} +#pragma warning restore SA1649 // File name should match first type name + +#endif diff --git a/src/Microsoft.VisualStudio.Threading.Analyzers.CodeFixes/buildTransitive/Microsoft.VisualStudio.Threading.Analyzers.targets b/src/Microsoft.VisualStudio.Threading.Analyzers.CodeFixes/buildTransitive/Microsoft.VisualStudio.Threading.Analyzers.targets index afce69710..a2a8bcc2c 100644 --- a/src/Microsoft.VisualStudio.Threading.Analyzers.CodeFixes/buildTransitive/Microsoft.VisualStudio.Threading.Analyzers.targets +++ b/src/Microsoft.VisualStudio.Threading.Analyzers.CodeFixes/buildTransitive/Microsoft.VisualStudio.Threading.Analyzers.targets @@ -1,8 +1,11 @@  - + false + + false + diff --git a/src/Microsoft.VisualStudio.Threading.Analyzers/Strings.resx b/src/Microsoft.VisualStudio.Threading.Analyzers/Strings.resx index 97e248e4d..a21467e21 100644 --- a/src/Microsoft.VisualStudio.Threading.Analyzers/Strings.resx +++ b/src/Microsoft.VisualStudio.Threading.Analyzers/Strings.resx @@ -353,4 +353,22 @@ Start the work within this context, or use JoinableTaskFactory.RunAsync to start Use 'JoinableTaskContext.CreateNoOpContext' instead. + + Invalid use of CompletedTaskAttribute + + + CompletedTaskAttribute can only be applied to readonly fields, properties without non-private setters, or methods. {0} + + + Fields must be readonly. + Error message shown when the CompletedTaskAttribute is applied to a field that is not marked as readonly. The attribute is only valid on readonly fields to ensure the task value cannot be changed. + + + Properties must not have non-private setters. + Error message shown when the CompletedTaskAttribute is applied to a property that has a public, internal, or protected setter. The attribute is only valid on properties with private setters or no setter (getter-only) to ensure the task value cannot be changed from outside the class. + + + Properties with init accessors must be private. + Error message shown when the CompletedTaskAttribute is applied to a property that has an init accessor and the property itself is not private (i.e., it's public, internal, or protected). Init accessors allow setting the property during object initialization. When using this attribute on a property with an init accessor, the entire property must be declared as private to ensure the task value cannot be changed from outside the class. + \ No newline at end of file diff --git a/src/Microsoft.VisualStudio.Threading.Analyzers/Types.cs b/src/Microsoft.VisualStudio.Threading.Analyzers/Types.cs index f6d24b8db..aa6ac3c6e 100644 --- a/src/Microsoft.VisualStudio.Threading.Analyzers/Types.cs +++ b/src/Microsoft.VisualStudio.Threading.Analyzers/Types.cs @@ -246,4 +246,11 @@ public static class TypeLibTypeAttribute public static readonly ImmutableArray Namespace = Namespaces.SystemRuntimeInteropServices; } + + public static class CompletedTaskAttribute + { + public const string TypeName = "CompletedTaskAttribute"; + + public static readonly ImmutableArray Namespace = Namespaces.MicrosoftVisualStudioThreading; + } } diff --git a/src/Microsoft.VisualStudio.Threading/CompletedTaskAttribute.cs b/src/Microsoft.VisualStudio.Threading/CompletedTaskAttribute.cs new file mode 100644 index 000000000..1952e33e2 --- /dev/null +++ b/src/Microsoft.VisualStudio.Threading/CompletedTaskAttribute.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; + +namespace Microsoft.VisualStudio.Threading; + +/// +/// Indicates that a property, method, or field returns a task that is already completed. +/// This suppresses VSTHRD003 warnings when awaiting the returned task. +/// +/// +/// +/// Apply this attribute to properties, methods, or fields that return cached, pre-completed tasks +/// such as singleton instances with well-known immutable values. +/// The VSTHRD003 analyzer will not report warnings when these members are awaited, +/// as awaiting an already-completed task does not pose a risk of deadlock. +/// +/// +/// This attribute can also be applied at the assembly level to mark members in external types +/// that you don't control: +/// +/// [assembly: CompletedTask(Member = "ExternalLibrary.ExternalClass.CompletedTaskProperty")] +/// +/// +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)] +public sealed class CompletedTaskAttribute : Attribute +{ + /// + /// Initializes a new instance of the class. + /// + public CompletedTaskAttribute() + { + } + + /// + /// Gets or sets the fully qualified name of the member that returns a completed task. + /// This is only used when the attribute is applied at the assembly level. + /// + /// + /// The format should be: "Namespace.TypeName.MemberName". + /// For example: "ExternalLibrary.ExternalClass.CompletedTaskProperty". + /// + public string? Member { get; set; } +} diff --git a/src/Microsoft.VisualStudio.Threading/TplExtensions.cs b/src/Microsoft.VisualStudio.Threading/TplExtensions.cs index 9fdb6aa76..188f689c5 100644 --- a/src/Microsoft.VisualStudio.Threading/TplExtensions.cs +++ b/src/Microsoft.VisualStudio.Threading/TplExtensions.cs @@ -20,22 +20,26 @@ public static partial class TplExtensions /// A singleton completed task. /// [Obsolete("Use Task.CompletedTask instead.")] + [CompletedTask] public static readonly Task CompletedTask = Task.FromResult(default(EmptyStruct)); /// /// A task that is already canceled. /// [Obsolete("Use Task.FromCanceled instead.")] + [CompletedTask] public static readonly Task CanceledTask = Task.FromCanceled(new CancellationToken(canceled: true)); /// /// A completed task with a result. /// + [CompletedTask] public static readonly Task TrueTask = Task.FromResult(true); /// /// A completed task with a result. /// + [CompletedTask] public static readonly Task FalseTask = Task.FromResult(false); /// diff --git a/test/Microsoft.VisualStudio.Threading.Analyzers.Tests/VSTHRD003UseJtfRunAsyncAnalyzerTests.cs b/test/Microsoft.VisualStudio.Threading.Analyzers.Tests/VSTHRD003UseJtfRunAsyncAnalyzerTests.cs index ce64483d5..451e178cb 100644 --- a/test/Microsoft.VisualStudio.Threading.Analyzers.Tests/VSTHRD003UseJtfRunAsyncAnalyzerTests.cs +++ b/test/Microsoft.VisualStudio.Threading.Analyzers.Tests/VSTHRD003UseJtfRunAsyncAnalyzerTests.cs @@ -1453,6 +1453,706 @@ static async Task ListenAndWait() await CSVerify.VerifyAnalyzerAsync(test); } + [Fact] + public async Task DoNotReportWarningWhenAwaitingPropertyWithCompletedTaskAttribute() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [Microsoft.VisualStudio.Threading.CompletedTask] + private static Task MyCompletedTask { get; } = Task.CompletedTask; + + async Task GetTask() + { + await MyCompletedTask; + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task DoNotReportWarningWhenAwaitingFieldWithCompletedTaskAttribute() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [Microsoft.VisualStudio.Threading.CompletedTask] + private static readonly Task MyCompletedTask = Task.CompletedTask; + + async Task GetTask() + { + await MyCompletedTask; + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task DoNotReportWarningWhenAwaitingMethodWithCompletedTaskAttribute() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [Microsoft.VisualStudio.Threading.CompletedTask] + private static Task GetCompletedTask() => Task.CompletedTask; + + async Task TestMethod() + { + await GetCompletedTask(); + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task DoNotReportWarningWhenReturningPropertyWithCompletedTaskAttribute() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [Microsoft.VisualStudio.Threading.CompletedTask] + private static Task MyCompletedTask { get; } = Task.CompletedTask; + + Task GetTask() => MyCompletedTask; +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task ReportWarningWhenAwaitingPropertyWithoutCompletedTaskAttribute() + { + var test = @" +using System.Threading.Tasks; + +class Tests +{ + private static Task MyTask { get; } = Task.Run(() => {}); + + async Task GetTask() + { + await [|MyTask|]; + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task DoNotReportWarningWhenAwaitingTaskGenericPropertyWithCompletedTaskAttribute() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [Microsoft.VisualStudio.Threading.CompletedTask] + private static Task MyCompletedTask { get; } = Task.FromResult(42); + + async Task GetResult() + { + return await MyCompletedTask; + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task DoNotReportWarningWhenAwaitingPropertyWithCompletedTaskAttributeInJtfRun() + { + var test = @" +using System.Threading.Tasks; +using Microsoft.VisualStudio.Threading; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [Microsoft.VisualStudio.Threading.CompletedTask] + private static Task MyCompletedTask { get; } = Task.CompletedTask; + + void TestMethod() + { + JoinableTaskFactory jtf = null; + jtf.Run(async delegate + { + await MyCompletedTask; + }); + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task DoNotReportWarningWhenAwaitingPropertyMarkedByAssemblyLevelAttribute() + { + var test = @" +using System.Threading.Tasks; + +[assembly: Microsoft.VisualStudio.Threading.CompletedTask(Member = ""ExternalLibrary.ExternalClass.CompletedTaskProperty"")] + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field | System.AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + public CompletedTaskAttribute() { } + public string? Member { get; set; } + } +} + +namespace ExternalLibrary +{ + public static class ExternalClass + { + public static Task CompletedTaskProperty { get; } = Task.CompletedTask; + } +} + +class Tests +{ + async Task TestMethod() + { + await ExternalLibrary.ExternalClass.CompletedTaskProperty; + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task DoNotReportWarningWhenAwaitingFieldMarkedByAssemblyLevelAttribute() + { + var test = @" +using System.Threading.Tasks; + +[assembly: Microsoft.VisualStudio.Threading.CompletedTask(Member = ""ExternalLibrary.ExternalClass.CompletedTaskField"")] + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field | System.AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + public CompletedTaskAttribute() { } + public string? Member { get; set; } + } +} + +namespace ExternalLibrary +{ + public static class ExternalClass + { + public static readonly Task CompletedTaskField = Task.FromResult(true); + } +} + +class Tests +{ + async Task TestMethod() + { + await ExternalLibrary.ExternalClass.CompletedTaskField; + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task DoNotReportWarningWhenAwaitingMethodMarkedByAssemblyLevelAttribute() + { + var test = @" +using System.Threading.Tasks; + +[assembly: Microsoft.VisualStudio.Threading.CompletedTask(Member = ""ExternalLibrary.ExternalClass.GetCompletedTask"")] + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field | System.AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + public CompletedTaskAttribute() { } + public string? Member { get; set; } + } +} + +namespace ExternalLibrary +{ + public static class ExternalClass + { + public static Task GetCompletedTask() => Task.CompletedTask; + } +} + +class Tests +{ + async Task TestMethod() + { + await ExternalLibrary.ExternalClass.GetCompletedTask(); + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task DoNotReportWarningWhenReturningPropertyMarkedByAssemblyLevelAttribute() + { + var test = @" +using System.Threading.Tasks; + +[assembly: Microsoft.VisualStudio.Threading.CompletedTask(Member = ""ExternalLibrary.ExternalClass.CompletedTaskProperty"")] + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field | System.AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + public CompletedTaskAttribute() { } + public string? Member { get; set; } + } +} + +namespace ExternalLibrary +{ + public static class ExternalClass + { + public static Task CompletedTaskProperty { get; } = Task.CompletedTask; + } +} + +class Tests +{ + Task GetTask() => ExternalLibrary.ExternalClass.CompletedTaskProperty; +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task ReportWarningWhenAwaitingPropertyNotMarkedByAssemblyLevelAttribute() + { + var test = @" +using System.Threading.Tasks; + +namespace ExternalLibrary +{ + public static class ExternalClass + { + public static Task SomeTaskProperty { get; } = Task.Run(() => {}); + } +} + +class Tests +{ + async Task TestMethod() + { + await [|ExternalLibrary.ExternalClass.SomeTaskProperty|]; + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task DoNotReportWarningWithMultipleAssemblyLevelAttributes() + { + var test = @" +using System.Threading.Tasks; + +[assembly: Microsoft.VisualStudio.Threading.CompletedTask(Member = ""ExternalLibrary.ExternalClass.Task1"")] +[assembly: Microsoft.VisualStudio.Threading.CompletedTask(Member = ""ExternalLibrary.ExternalClass.Task2"")] + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field | System.AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + public CompletedTaskAttribute() { } + public string? Member { get; set; } + } +} + +namespace ExternalLibrary +{ + public static class ExternalClass + { + public static Task Task1 { get; } = Task.CompletedTask; + public static Task Task2 { get; } = Task.FromResult(true); + } +} + +class Tests +{ + async Task TestMethod() + { + await ExternalLibrary.ExternalClass.Task1; + await ExternalLibrary.ExternalClass.Task2; + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task ReportWarningWhenCompletedTaskAttributeOnNonReadonlyField() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [{|#0:Microsoft.VisualStudio.Threading.CompletedTask|}] + private static Task MyTask = Task.CompletedTask; // Not readonly + + async Task GetTask() + { + await [|MyTask|]; + } +} +"; + DiagnosticResult expected = new DiagnosticResult(Microsoft.VisualStudio.Threading.Analyzers.VSTHRD003UseJtfRunAsyncAnalyzer.InvalidAttributeUseDescriptor) + .WithLocation(0) + .WithArguments("Fields must be readonly."); + await CSVerify.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task ReportWarningWhenCompletedTaskAttributeOnPropertyWithPublicSetter() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [{|#0:Microsoft.VisualStudio.Threading.CompletedTask|}] + public static Task MyTask { get; set; } = Task.CompletedTask; // Public setter + + async Task GetTask() + { + await [|MyTask|]; + } +} +"; + DiagnosticResult expected = new DiagnosticResult(Microsoft.VisualStudio.Threading.Analyzers.VSTHRD003UseJtfRunAsyncAnalyzer.InvalidAttributeUseDescriptor) + .WithLocation(0) + .WithArguments("Properties must not have non-private setters."); + await CSVerify.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task ReportWarningWhenCompletedTaskAttributeOnPropertyWithInternalSetter() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [{|#0:Microsoft.VisualStudio.Threading.CompletedTask|}] + public static Task MyTask { get; internal set; } = Task.CompletedTask; // Internal setter + + async Task GetTask() + { + await [|MyTask|]; + } +} +"; + DiagnosticResult expected = new DiagnosticResult(Microsoft.VisualStudio.Threading.Analyzers.VSTHRD003UseJtfRunAsyncAnalyzer.InvalidAttributeUseDescriptor) + .WithLocation(0) + .WithArguments("Properties must not have non-private setters."); + await CSVerify.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task DoNotReportWarningWhenCompletedTaskAttributeOnPropertyWithPrivateSetter() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [Microsoft.VisualStudio.Threading.CompletedTask] + public static Task MyTask { get; private set; } = Task.CompletedTask; // Private setter is OK + + async Task GetTask() + { + await MyTask; + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task DoNotReportWarningWhenCompletedTaskAttributeOnPropertyWithGetterOnly() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [Microsoft.VisualStudio.Threading.CompletedTask] + public static Task MyTask { get; } = Task.CompletedTask; // Getter-only is OK + + async Task GetTask() + { + await MyTask; + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task ReportDiagnosticWhenCompletedTaskAttributeOnPropertyWithPublicInit() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [{|#0:Microsoft.VisualStudio.Threading.CompletedTask|}] + public static Task MyTask { get; init; } = Task.CompletedTask; // Public init + + async Task GetTask() + { + await [|MyTask|]; + } +} +"; + DiagnosticResult expected = new DiagnosticResult(Microsoft.VisualStudio.Threading.Analyzers.VSTHRD003UseJtfRunAsyncAnalyzer.InvalidAttributeUseDescriptor) + .WithLocation(0) + .WithArguments("Properties with init accessors must be private."); + await CSVerify.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task DoNotReportWarningWhenCompletedTaskAttributeOnPrivatePropertyWithInit() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [Microsoft.VisualStudio.Threading.CompletedTask] + private static Task MyTask { get; init; } = Task.CompletedTask; // Private init is OK + + async Task GetTask() + { + await MyTask; + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task ReportDiagnosticWhenCompletedTaskAttributeOnNonReadonlyFieldWithDiagnosticOnAttribute() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [{|#0:Microsoft.VisualStudio.Threading.CompletedTask|}] + private static Task MyTask = Task.CompletedTask; // Not readonly + + async Task GetTask() + { + await [|MyTask|]; + } +} +"; + DiagnosticResult expected = new DiagnosticResult(Microsoft.VisualStudio.Threading.Analyzers.VSTHRD003UseJtfRunAsyncAnalyzer.InvalidAttributeUseDescriptor) + .WithLocation(0) + .WithArguments("Fields must be readonly."); + await CSVerify.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task ReportDiagnosticWhenCompletedTaskAttributeOnPropertyWithPublicSetterWithDiagnosticOnAttribute() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [{|#0:Microsoft.VisualStudio.Threading.CompletedTask|}] + public static Task MyTask { get; set; } = Task.CompletedTask; // Public setter + + async Task GetTask() + { + await [|MyTask|]; + } +} +"; + DiagnosticResult expected = new DiagnosticResult(Microsoft.VisualStudio.Threading.Analyzers.VSTHRD003UseJtfRunAsyncAnalyzer.InvalidAttributeUseDescriptor) + .WithLocation(0) + .WithArguments("Properties must not have non-private setters."); + await CSVerify.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task ReportDiagnosticWhenCompletedTaskAttributeOnPropertyWithInternalSetterWithDiagnosticOnAttribute() + { + var test = @" +using System.Threading.Tasks; + +namespace Microsoft.VisualStudio.Threading +{ + [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)] + internal sealed class CompletedTaskAttribute : System.Attribute + { + } +} + +class Tests +{ + [{|#0:Microsoft.VisualStudio.Threading.CompletedTask|}] + public static Task MyTask { get; internal set; } = Task.CompletedTask; // Internal setter + + async Task GetTask() + { + await [|MyTask|]; + } +} +"; + DiagnosticResult expected = new DiagnosticResult(Microsoft.VisualStudio.Threading.Analyzers.VSTHRD003UseJtfRunAsyncAnalyzer.InvalidAttributeUseDescriptor) + .WithLocation(0) + .WithArguments("Properties must not have non-private setters."); + await CSVerify.VerifyAnalyzerAsync(test, expected); + } + private DiagnosticResult CreateDiagnostic(int line, int column, int length) => CSVerify.Diagnostic().WithSpan(line, column, line, column + length); }