|
| 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 Analyzer.Utilities; |
| 5 | +using Analyzer.Utilities.Extensions; |
| 6 | +using Analyzer.Utilities.Lightup; |
| 7 | +using Microsoft.CodeAnalysis; |
| 8 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 9 | +using Microsoft.CodeAnalysis.Operations; |
| 10 | +using static Microsoft.NetCore.Analyzers.MicrosoftNetCoreAnalyzersResources; |
| 11 | + |
| 12 | +namespace Microsoft.NetCore.Analyzers.Tasks |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// CA2027: <inheritdoc cref="DoNotUseNonCancelableTaskDelayWithWhenAnyTitle"/> |
| 16 | + /// </summary> |
| 17 | + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] |
| 18 | + public sealed class DoNotUseNonCancelableTaskDelayWithWhenAny : DiagnosticAnalyzer |
| 19 | + { |
| 20 | + internal const string RuleId = "CA2027"; |
| 21 | + |
| 22 | + internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( |
| 23 | + RuleId, |
| 24 | + CreateLocalizableResourceString(nameof(DoNotUseNonCancelableTaskDelayWithWhenAnyTitle)), |
| 25 | + CreateLocalizableResourceString(nameof(DoNotUseNonCancelableTaskDelayWithWhenAnyMessage)), |
| 26 | + DiagnosticCategory.Reliability, |
| 27 | + RuleLevel.IdeSuggestion, |
| 28 | + CreateLocalizableResourceString(nameof(DoNotUseNonCancelableTaskDelayWithWhenAnyDescription)), |
| 29 | + isPortedFxCopRule: false, |
| 30 | + isDataflowRule: false); |
| 31 | + |
| 32 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); |
| 33 | + |
| 34 | + public override void Initialize(AnalysisContext context) |
| 35 | + { |
| 36 | + context.EnableConcurrentExecution(); |
| 37 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 38 | + |
| 39 | + context.RegisterCompilationStartAction(context => |
| 40 | + { |
| 41 | + var compilation = context.Compilation; |
| 42 | + |
| 43 | + if (!compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask, out var taskType) || |
| 44 | + !compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingCancellationToken, out var cancellationTokenType)) |
| 45 | + { |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + context.RegisterOperationAction(context => |
| 50 | + { |
| 51 | + var invocation = (IInvocationOperation)context.Operation; |
| 52 | + |
| 53 | + // Check if this is a call to Task.WhenAny |
| 54 | + var method = invocation.TargetMethod; |
| 55 | + if (!SymbolEqualityComparer.Default.Equals(method.ContainingType, taskType) || |
| 56 | + !method.IsStatic || |
| 57 | + method.Name != nameof(Task.WhenAny)) |
| 58 | + { |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + // Count the total number of tasks passed to WhenAny |
| 63 | + int taskCount = 0; |
| 64 | + List<IOperation>? taskDelayOperations = null; |
| 65 | + |
| 66 | + // Task.WhenAny has params parameters, so arguments are often implicitly wrapped in an array |
| 67 | + // We need to check inside the array initializer or collection expression |
| 68 | + for (int i = 0; i < invocation.Arguments.Length; i++) |
| 69 | + { |
| 70 | + var argument = invocation.Arguments[i].Value.WalkDownConversion(); |
| 71 | + |
| 72 | + // Check if this is an array creation |
| 73 | + if (argument is IArrayCreationOperation { Initializer: not null } arrayCreation) |
| 74 | + { |
| 75 | + // Check each element in the array |
| 76 | + foreach (var element in arrayCreation.Initializer.ElementValues) |
| 77 | + { |
| 78 | + taskCount++; |
| 79 | + if (IsNonCancelableTaskDelay(element, taskType, cancellationTokenType)) |
| 80 | + { |
| 81 | + (taskDelayOperations ??= []).Add(element); |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + else if (ICollectionExpressionOperationWrapper.IsInstance(argument)) |
| 86 | + { |
| 87 | + // Check each element in the collection expression |
| 88 | + var collectionExpression = ICollectionExpressionOperationWrapper.FromOperation(argument); |
| 89 | + foreach (var element in collectionExpression.Elements) |
| 90 | + { |
| 91 | + taskCount++; |
| 92 | + if (IsNonCancelableTaskDelay(element, taskType, cancellationTokenType)) |
| 93 | + { |
| 94 | + (taskDelayOperations ??= []).Add(element); |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + else |
| 99 | + { |
| 100 | + // Direct argument (not params or array) |
| 101 | + taskCount++; |
| 102 | + if (IsNonCancelableTaskDelay(argument, taskType, cancellationTokenType)) |
| 103 | + { |
| 104 | + (taskDelayOperations ??= []).Add(argument); |
| 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 IsNonCancelableTaskDelay(IOperation operation, INamedTypeSymbol taskType, INamedTypeSymbol cancellationTokenType) |
| 123 | + { |
| 124 | + operation = operation.WalkDownConversion(); |
| 125 | + |
| 126 | + if (operation is not IInvocationOperation invocation) |
| 127 | + { |
| 128 | + return false; |
| 129 | + } |
| 130 | + |
| 131 | + // Check if this is Task.Delay |
| 132 | + var method = invocation.TargetMethod; |
| 133 | + if (!SymbolEqualityComparer.Default.Equals(method.ContainingType, taskType) || |
| 134 | + !method.IsStatic || |
| 135 | + method.Name != nameof(Task.Delay)) |
| 136 | + { |
| 137 | + return false; |
| 138 | + } |
| 139 | + |
| 140 | + // Check if any parameter is a CancellationToken, in which case we consider it cancelable |
| 141 | + foreach (var parameter in method.Parameters) |
| 142 | + { |
| 143 | + if (SymbolEqualityComparer.Default.Equals(parameter.Type, cancellationTokenType)) |
| 144 | + { |
| 145 | + return false; |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + return true; // Task.Delay without CancellationToken |
| 150 | + } |
| 151 | + } |
| 152 | +} |
0 commit comments