|
| 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 Microsoft.CodeAnalysis; |
| 8 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 9 | +using Microsoft.CodeAnalysis.Operations; |
| 10 | + |
| 11 | +namespace Microsoft.NetCore.Analyzers.Performance |
| 12 | +{ |
| 13 | + using static MicrosoftNetCoreAnalyzersResources; |
| 14 | + |
| 15 | + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] |
| 16 | + public sealed class UseStartsWithInsteadOfIndexOfComparisonWithZero : DiagnosticAnalyzer |
| 17 | + { |
| 18 | + internal const string RuleId = "CA1858"; |
| 19 | + internal const string ShouldNegateKey = "ShouldNegate"; |
| 20 | + internal const string CompilationHasStartsWithCharOverloadKey = "CompilationHasStartsWithCharOverload"; |
| 21 | + |
| 22 | + internal const string ExistingOverloadKey = "ExistingOverload"; |
| 23 | + |
| 24 | + internal const string OverloadString = "String"; |
| 25 | + internal const string OverloadString_StringComparison = "String,StringComparison"; |
| 26 | + internal const string OverloadChar = "Char"; |
| 27 | + internal const string OverloadChar_StringComparison = "Char,StringComparison"; |
| 28 | + |
| 29 | + internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( |
| 30 | + id: RuleId, |
| 31 | + title: CreateLocalizableResourceString(nameof(UseStartsWithInsteadOfIndexOfComparisonWithZeroTitle)), |
| 32 | + messageFormat: CreateLocalizableResourceString(nameof(UseStartsWithInsteadOfIndexOfComparisonWithZeroMessage)), |
| 33 | + category: DiagnosticCategory.Performance, |
| 34 | + ruleLevel: RuleLevel.IdeSuggestion, |
| 35 | + description: CreateLocalizableResourceString(nameof(UseStartsWithInsteadOfIndexOfComparisonWithZeroDescription)), |
| 36 | + isPortedFxCopRule: false, |
| 37 | + isDataflowRule: false |
| 38 | + ); |
| 39 | + |
| 40 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); |
| 41 | + |
| 42 | + public override void Initialize(AnalysisContext context) |
| 43 | + { |
| 44 | + context.EnableConcurrentExecution(); |
| 45 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 46 | + |
| 47 | + context.RegisterCompilationStartAction(context => |
| 48 | + { |
| 49 | + var stringType = context.Compilation.GetSpecialType(SpecialType.System_String); |
| 50 | + var hasAnyStartsWith = false; |
| 51 | + var hasStartsWithCharOverload = false; |
| 52 | + foreach (var startsWithMethod in stringType.GetMembers("StartsWith").OfType<IMethodSymbol>()) |
| 53 | + { |
| 54 | + hasAnyStartsWith = true; |
| 55 | + if (startsWithMethod.Parameters is [{ Type.SpecialType: SpecialType.System_Char }]) |
| 56 | + { |
| 57 | + hasStartsWithCharOverload = true; |
| 58 | + break; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + if (!hasAnyStartsWith) |
| 63 | + { |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + var indexOfMethodsBuilder = ImmutableArray.CreateBuilder<(IMethodSymbol IndexOfSymbol, string OverloadPropertyValue)>(); |
| 68 | + foreach (var indexOfMethod in stringType.GetMembers("IndexOf").OfType<IMethodSymbol>()) |
| 69 | + { |
| 70 | + if (indexOfMethod.Parameters is [{ Type.SpecialType: SpecialType.System_String }]) |
| 71 | + { |
| 72 | + indexOfMethodsBuilder.Add((indexOfMethod, OverloadString)); |
| 73 | + } |
| 74 | + else if (indexOfMethod.Parameters is [{ Type.SpecialType: SpecialType.System_Char }]) |
| 75 | + { |
| 76 | + indexOfMethodsBuilder.Add((indexOfMethod, OverloadChar)); |
| 77 | + } |
| 78 | + else if (indexOfMethod.Parameters is [{ Type.SpecialType: SpecialType.System_String }, { Name: "comparisonType" }]) |
| 79 | + { |
| 80 | + indexOfMethodsBuilder.Add((indexOfMethod, OverloadString_StringComparison)); |
| 81 | + } |
| 82 | + else if (indexOfMethod.Parameters is [{ Type.SpecialType: SpecialType.System_Char }, { Name: "comparisonType" }]) |
| 83 | + { |
| 84 | + indexOfMethodsBuilder.Add((indexOfMethod, OverloadChar_StringComparison)); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + if (indexOfMethodsBuilder.Count == 0) |
| 89 | + { |
| 90 | + return; |
| 91 | + } |
| 92 | + |
| 93 | + var indexOfMethods = indexOfMethodsBuilder.ToImmutable(); |
| 94 | + |
| 95 | + context.RegisterOperationAction(context => |
| 96 | + { |
| 97 | + var binaryOperation = (IBinaryOperation)context.Operation; |
| 98 | + if (binaryOperation.OperatorKind is not (BinaryOperatorKind.Equals or BinaryOperatorKind.NotEquals)) |
| 99 | + { |
| 100 | + return; |
| 101 | + } |
| 102 | + |
| 103 | + if (IsIndexOfComparedWithZero(binaryOperation.LeftOperand, binaryOperation.RightOperand, indexOfMethods, out var additionalLocations, out var properties) || |
| 104 | + IsIndexOfComparedWithZero(binaryOperation.RightOperand, binaryOperation.LeftOperand, indexOfMethods, out additionalLocations, out properties)) |
| 105 | + { |
| 106 | + if (binaryOperation.OperatorKind == BinaryOperatorKind.NotEquals) |
| 107 | + { |
| 108 | + properties = properties.Add(ShouldNegateKey, ""); |
| 109 | + } |
| 110 | + |
| 111 | + if (hasStartsWithCharOverload) |
| 112 | + { |
| 113 | + properties = properties.Add(CompilationHasStartsWithCharOverloadKey, ""); |
| 114 | + } |
| 115 | + |
| 116 | + context.ReportDiagnostic(binaryOperation.CreateDiagnostic(Rule, additionalLocations, properties)); |
| 117 | + } |
| 118 | + }, OperationKind.Binary); |
| 119 | + }); |
| 120 | + } |
| 121 | + |
| 122 | + private static bool IsIndexOfComparedWithZero( |
| 123 | + IOperation left, IOperation right, |
| 124 | + ImmutableArray<(IMethodSymbol Symbol, string OverloadPropertyValue)> indexOfMethods, |
| 125 | + out ImmutableArray<Location> additionalLocations, |
| 126 | + out ImmutableDictionary<string, string?> properties) |
| 127 | + { |
| 128 | + properties = ImmutableDictionary<string, string?>.Empty; |
| 129 | + |
| 130 | + if (right.ConstantValue is { HasValue: true, Value: 0 } && |
| 131 | + left is IInvocationOperation invocation) |
| 132 | + { |
| 133 | + foreach (var (indexOfMethod, overloadPropertyValue) in indexOfMethods) |
| 134 | + { |
| 135 | + if (indexOfMethod.Equals(invocation.TargetMethod, SymbolEqualityComparer.Default)) |
| 136 | + { |
| 137 | + var locationsBuilder = ImmutableArray.CreateBuilder<Location>(); |
| 138 | + locationsBuilder.Add(invocation.Instance.Syntax.GetLocation()); |
| 139 | + locationsBuilder.AddRange(invocation.Arguments.Select(arg => arg.Syntax.GetLocation())); |
| 140 | + additionalLocations = locationsBuilder.ToImmutable(); |
| 141 | + |
| 142 | + properties = properties.Add(ExistingOverloadKey, overloadPropertyValue); |
| 143 | + return true; |
| 144 | + } |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + additionalLocations = ImmutableArray<Location>.Empty; |
| 149 | + return false; |
| 150 | + } |
| 151 | + } |
| 152 | +} |
0 commit comments