|
| 1 | +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. |
| 2 | + |
| 3 | +using System.Collections.Immutable; |
| 4 | +using System.Linq; |
| 5 | +using Analyzer.Utilities; |
| 6 | +using Analyzer.Utilities.Extensions; |
| 7 | +using Analyzer.Utilities.Lightup; |
| 8 | +using Microsoft.CodeAnalysis; |
| 9 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 10 | +using Microsoft.CodeAnalysis.Operations; |
| 11 | + |
| 12 | +namespace Microsoft.NetCore.Analyzers.Tasks |
| 13 | +{ |
| 14 | + using static MicrosoftNetCoreAnalyzersResources; |
| 15 | + |
| 16 | + /// <summary> |
| 17 | + /// CA2027: <inheritdoc cref="DoNotUseNonCancelableTaskDelayWithWhenAnyTitle"/> |
| 18 | + /// </summary> |
| 19 | + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] |
| 20 | + public sealed class DoNotUseNonCancelableTaskDelayWithWhenAny : DiagnosticAnalyzer |
| 21 | + { |
| 22 | + internal const string RuleId = "CA2027"; |
| 23 | + |
| 24 | + internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( |
| 25 | + RuleId, |
| 26 | + CreateLocalizableResourceString(nameof(DoNotUseNonCancelableTaskDelayWithWhenAnyTitle)), |
| 27 | + CreateLocalizableResourceString(nameof(DoNotUseNonCancelableTaskDelayWithWhenAnyMessage)), |
| 28 | + DiagnosticCategory.Reliability, |
| 29 | + RuleLevel.IdeSuggestion, |
| 30 | + CreateLocalizableResourceString(nameof(DoNotUseNonCancelableTaskDelayWithWhenAnyDescription)), |
| 31 | + isPortedFxCopRule: false, |
| 32 | + isDataflowRule: false); |
| 33 | + |
| 34 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); |
| 35 | + |
| 36 | + public override void Initialize(AnalysisContext context) |
| 37 | + { |
| 38 | + context.EnableConcurrentExecution(); |
| 39 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 40 | + |
| 41 | + context.RegisterCompilationStartAction(context => |
| 42 | + { |
| 43 | + var compilation = context.Compilation; |
| 44 | + |
| 45 | + if (!compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask, out var taskType) || |
| 46 | + !compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingCancellationToken, out var cancellationTokenType)) |
| 47 | + { |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + context.RegisterOperationAction(context => |
| 52 | + { |
| 53 | + var invocation = (IInvocationOperation)context.Operation; |
| 54 | + |
| 55 | + // Check if this is a call to Task.WhenAny |
| 56 | + if (!IsTaskWhenAny(invocation.TargetMethod, taskType)) |
| 57 | + { |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + // Count the total number of tasks passed to WhenAny |
| 62 | + int taskCount = 0; |
| 63 | + System.Collections.Generic.List<IOperation>? taskDelayOperations = null; |
| 64 | + |
| 65 | + // Task.WhenAny has params parameters, so arguments are often implicitly wrapped in an array |
| 66 | + // We need to check inside the array initializer or collection expression |
| 67 | + foreach (var argument in invocation.Arguments) |
| 68 | + { |
| 69 | + // Check if this is an array creation (implicit params expansion, explicit array, or collection expression) |
| 70 | + if (argument.Value is IArrayCreationOperation { Initializer: not null } arrayCreation) |
| 71 | + { |
| 72 | + // Check each element in the array |
| 73 | + foreach (var element in arrayCreation.Initializer.ElementValues) |
| 74 | + { |
| 75 | + taskCount++; |
| 76 | + if (IsNonCancelableTaskDelay(element, taskType, cancellationTokenType)) |
| 77 | + { |
| 78 | + taskDelayOperations ??= new System.Collections.Generic.List<IOperation>(); |
| 79 | + taskDelayOperations.Add(element); |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + else if (ICollectionExpressionOperationWrapper.IsInstance(argument.Value)) |
| 84 | + { |
| 85 | + // Check each element in the collection expression |
| 86 | + var collectionExpression = ICollectionExpressionOperationWrapper.FromOperation(argument.Value); |
| 87 | + foreach (var element in collectionExpression.Elements) |
| 88 | + { |
| 89 | + taskCount++; |
| 90 | + if (IsNonCancelableTaskDelay(element, taskType, cancellationTokenType)) |
| 91 | + { |
| 92 | + taskDelayOperations ??= new System.Collections.Generic.List<IOperation>(); |
| 93 | + taskDelayOperations.Add(element); |
| 94 | + } |
| 95 | + } |
| 96 | + } |
| 97 | + else |
| 98 | + { |
| 99 | + // Direct argument (not params or array) |
| 100 | + taskCount++; |
| 101 | + if (IsNonCancelableTaskDelay(argument.Value, taskType, cancellationTokenType)) |
| 102 | + { |
| 103 | + taskDelayOperations ??= new System.Collections.Generic.List<IOperation>(); |
| 104 | + taskDelayOperations.Add(argument.Value); |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + // Only report diagnostics if there are at least 2 tasks total |
| 110 | + // (avoid flagging Task.WhenAny(Task.Delay(...)) which may be used to avoid exceptions) |
| 111 | + if (taskCount >= 2 && taskDelayOperations is not null) |
| 112 | + { |
| 113 | + foreach (var operation in taskDelayOperations) |
| 114 | + { |
| 115 | + context.ReportDiagnostic(operation.CreateDiagnostic(Rule)); |
| 116 | + } |
| 117 | + } |
| 118 | + }, OperationKind.Invocation); |
| 119 | + }); |
| 120 | + } |
| 121 | + |
| 122 | + private static bool IsTaskWhenAny(IMethodSymbol method, INamedTypeSymbol taskType) |
| 123 | + { |
| 124 | + return SymbolEqualityComparer.Default.Equals(method.ContainingType, taskType) && |
| 125 | + method.IsStatic && |
| 126 | + method.Name == nameof(System.Threading.Tasks.Task.WhenAny); |
| 127 | + } |
| 128 | + |
| 129 | + private static bool IsNonCancelableTaskDelay(IOperation operation, INamedTypeSymbol taskType, INamedTypeSymbol cancellationTokenType) |
| 130 | + { |
| 131 | + // Unwrap conversions to get to the actual invocation |
| 132 | + if (operation is IConversionOperation conversion) |
| 133 | + { |
| 134 | + operation = conversion.Operand; |
| 135 | + } |
| 136 | + |
| 137 | + if (operation is not IInvocationOperation invocation) |
| 138 | + { |
| 139 | + return false; |
| 140 | + } |
| 141 | + |
| 142 | + var method = invocation.TargetMethod; |
| 143 | + |
| 144 | + // Check if this is Task.Delay |
| 145 | + if (!SymbolEqualityComparer.Default.Equals(method.ContainingType, taskType) || |
| 146 | + !method.IsStatic || |
| 147 | + method.Name != nameof(System.Threading.Tasks.Task.Delay)) |
| 148 | + { |
| 149 | + return false; |
| 150 | + } |
| 151 | + |
| 152 | + // Check if any parameter is a CancellationToken |
| 153 | + foreach (var parameter in method.Parameters) |
| 154 | + { |
| 155 | + if (SymbolEqualityComparer.Default.Equals(parameter.Type, cancellationTokenType)) |
| 156 | + { |
| 157 | + return false; // Has a CancellationToken parameter, so it's cancelable |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + return true; // Task.Delay without CancellationToken |
| 162 | + } |
| 163 | + } |
| 164 | +} |
0 commit comments