-
Notifications
You must be signed in to change notification settings - Fork 470
/
Copy pathPreferStringContainsOverIndexOfAnalyzer.cs
214 lines (188 loc) · 12.2 KB
/
PreferStringContainsOverIndexOfAnalyzer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Collections.Immutable;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Analyzer.Utilities.PooledObjects;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.NetCore.Analyzers.Runtime
{
using static MicrosoftNetCoreAnalyzersResources;
/// <summary>
/// CA2249: <inheritdoc cref="PreferStringContainsOverIndexOfTitle"/>
/// Prefer string.Contains over string.IndexOf when the result is used to check for the presence/absence of a substring
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class PreferStringContainsOverIndexOfAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA2249";
internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(
RuleId,
CreateLocalizableResourceString(nameof(PreferStringContainsOverIndexOfTitle)),
CreateLocalizableResourceString(nameof(PreferStringContainsOverIndexOfMessage)),
DiagnosticCategory.Usage,
RuleLevel.IdeSuggestion,
CreateLocalizableResourceString(nameof(PreferStringContainsOverIndexOfDescription)),
isPortedFxCopRule: false,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(context =>
{
if (context.Compilation.GetSpecialType(SpecialType.System_String) is not INamedTypeSymbol stringType ||
context.Compilation.GetSpecialType(SpecialType.System_Char) is not INamedTypeSymbol charType ||
!context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemStringComparison, out INamedTypeSymbol? stringComparisonType))
{
return;
}
// First get all the string.IndexOf methods that we are interested in tagging
var stringIndexOfMethods = stringType
.GetMembers("IndexOf")
.OfType<IMethodSymbol>()
.WhereAsArray(s =>
s.Parameters.Length <= 2);
var stringArgumentIndexOfMethod = stringIndexOfMethods.GetFirstOrDefaultMemberWithParameterInfos(
ParameterInfo.GetParameterInfo(stringType));
var charArgumentIndexOfMethod = stringIndexOfMethods.GetFirstOrDefaultMemberWithParameterInfos(
ParameterInfo.GetParameterInfo(charType));
var stringAndComparisonTypeArgumentIndexOfMethod = stringIndexOfMethods.GetFirstOrDefaultMemberWithParameterInfos(
ParameterInfo.GetParameterInfo(stringType),
ParameterInfo.GetParameterInfo(stringComparisonType));
var charAndComparisonTypeArgumentIndexOfMethod = stringIndexOfMethods.GetFirstOrDefaultMemberWithParameterInfos(
ParameterInfo.GetParameterInfo(charType),
ParameterInfo.GetParameterInfo(stringComparisonType));
// Check that the contains methods that take 2 parameters exist
// string.Contains(char) is also .NETStandard2.1+
var stringContainsMethods = stringType
.GetMembers("Contains")
.OfType<IMethodSymbol>()
.WhereAsArray(s =>
s.Parameters.Length <= 2);
var stringAndComparisonTypeArgumentContainsMethod = stringContainsMethods.GetFirstOrDefaultMemberWithParameterInfos(
ParameterInfo.GetParameterInfo(stringType),
ParameterInfo.GetParameterInfo(stringComparisonType));
var charAndComparisonTypeArgumentContainsMethod = stringContainsMethods.GetFirstOrDefaultMemberWithParameterInfos(
ParameterInfo.GetParameterInfo(charType),
ParameterInfo.GetParameterInfo(stringComparisonType));
var charArgumentContainsMethod = stringContainsMethods.GetFirstOrDefaultMemberWithParameterInfos(
ParameterInfo.GetParameterInfo(charType));
if (stringAndComparisonTypeArgumentContainsMethod == null ||
charAndComparisonTypeArgumentContainsMethod == null ||
charArgumentContainsMethod == null)
{
return;
}
// Roslyn doesn't yet support "FindAllReferences" at a file/block level. So instead, find references to local int variables in this block.
context.RegisterOperationBlockStartAction(OnOperationBlockStart);
return;
void OnOperationBlockStart(OperationBlockStartAnalysisContext context)
{
if (context.OwningSymbol is not IMethodSymbol method)
{
return;
}
// Algorithm:
// We aim to change string.IndexOf -> string.Contains
// 1. We register 1 callback for invocations of IndexOf.
// 1a. Check if invocation.Parent is a binary operation we care about (string.IndexOf >= 0 OR string.IndexOf == -1). If so, report a diagnostic and return from the callback.
// 1b. Otherwise, check if invocation.Parent is a variable declarator. If so, add the invocation as a potential violation to track into variableNameToOperationsMap.
// 2. We register another callback for local references
// 2a. If the local reference is not a type int, bail out.
// 2b. If the local reference operation's parent is not a binary operation, add it to "localsToBailOut".
// 3. In an operation block end, we check if entries in "variableNameToOperationsMap" exist in "localToBailOut". If an entry is NOT present, we report a diagnostic at that invocation.
TemporarySet<ILocalSymbol> localsToBailOut = TemporarySet<ILocalSymbol>.Empty;
TemporaryDictionary<ILocalSymbol, IInvocationOperation> variableNameToOperationsMap = TemporaryDictionary<ILocalSymbol, IInvocationOperation>.Empty;
context.RegisterOperationAction(PopulateLocalReferencesSet, OperationKind.LocalReference);
context.RegisterOperationAction(AnalyzeInvocationOperation, OperationKind.Invocation);
context.RegisterOperationBlockEndAction(OnOperationBlockEnd);
return;
// Local Functions
void PopulateLocalReferencesSet(OperationAnalysisContext context)
{
ILocalReferenceOperation localReference = (ILocalReferenceOperation)context.Operation;
if (localReference.Local.Type.SpecialType != SpecialType.System_Int32)
{
return;
}
var parent = localReference.Parent;
if (parent is IBinaryOperation binaryOperation)
{
var otherOperand = binaryOperation.LeftOperand is ILocalReferenceOperation ? binaryOperation.RightOperand : binaryOperation.LeftOperand;
if (CheckOperatorKindAndOperand(binaryOperation, otherOperand))
{
// Do nothing. This is a valid case to the tagged in the analyzer
return;
}
}
localsToBailOut.Add(localReference.Local, context.CancellationToken);
}
void AnalyzeInvocationOperation(OperationAnalysisContext context)
{
var invocationOperation = (IInvocationOperation)context.Operation;
if (!IsDesiredTargetMethod(invocationOperation.TargetMethod))
{
return;
}
var parent = invocationOperation.Parent;
if (parent is IBinaryOperation binaryOperation)
{
var otherOperand = binaryOperation.LeftOperand is IInvocationOperation ? binaryOperation.RightOperand : binaryOperation.LeftOperand;
if (CheckOperatorKindAndOperand(binaryOperation, otherOperand))
{
context.ReportDiagnostic(binaryOperation.CreateDiagnostic(Rule));
}
}
else if (parent is IVariableInitializerOperation variableInitializer)
{
if (variableInitializer.Parent is IVariableDeclaratorOperation variableDeclaratorOperation)
{
variableNameToOperationsMap.Add(variableDeclaratorOperation.Symbol, invocationOperation, context.CancellationToken);
}
else if (variableInitializer.Parent is IVariableDeclarationOperation variableDeclarationOperation && variableDeclarationOperation.Declarators.Length == 1)
{
variableNameToOperationsMap.Add(variableDeclarationOperation.Declarators[0].Symbol, invocationOperation, context.CancellationToken);
}
}
}
static bool CheckOperatorKindAndOperand(IBinaryOperation binaryOperation, IOperation otherOperand)
{
var operatorKind = binaryOperation.OperatorKind;
if (otherOperand.ConstantValue.HasValue && otherOperand.ConstantValue.Value is int intValue)
{
if ((operatorKind == BinaryOperatorKind.Equals && intValue < 0) ||
(operatorKind == BinaryOperatorKind.GreaterThanOrEqual && intValue == 0) ||
(operatorKind == BinaryOperatorKind.NotEquals && intValue < 0))
{
// This is the only case we are targeting in this analyzer
return true;
}
}
return false;
}
void OnOperationBlockEnd(OperationBlockAnalysisContext context)
{
foreach (var variableNameAndLocation in variableNameToOperationsMap.NonConcurrentEnumerable)
{
ILocalSymbol variable = variableNameAndLocation.Key;
if (!localsToBailOut.Contains(variable))
{
context.ReportDiagnostic(variableNameAndLocation.Value.CreateDiagnostic(Rule));
}
}
variableNameToOperationsMap.Free(context.CancellationToken);
localsToBailOut.Free(context.CancellationToken);
}
bool IsDesiredTargetMethod(IMethodSymbol targetMethod) =>
targetMethod.Equals(stringArgumentIndexOfMethod)
|| targetMethod.Equals(charArgumentIndexOfMethod)
|| targetMethod.Equals(stringAndComparisonTypeArgumentIndexOfMethod)
|| targetMethod.Equals(charAndComparisonTypeArgumentIndexOfMethod);
}
});
}
}
}