/
CompareSymbolsCorrectlyAnalyzer.cs
201 lines (168 loc) · 7.98 KB
/
CompareSymbolsCorrectlyAnalyzer.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
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using System.Collections.Immutable;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class CompareSymbolsCorrectlyAnalyzer : DiagnosticAnalyzer
{
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(CodeAnalysisDiagnosticsResources.CompareSymbolsCorrectlyTitle), CodeAnalysisDiagnosticsResources.ResourceManager, typeof(CodeAnalysisDiagnosticsResources));
private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(CodeAnalysisDiagnosticsResources.CompareSymbolsCorrectlyMessage), CodeAnalysisDiagnosticsResources.ResourceManager, typeof(CodeAnalysisDiagnosticsResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(CodeAnalysisDiagnosticsResources.CompareSymbolsCorrectlyDescription), CodeAnalysisDiagnosticsResources.ResourceManager, typeof(CodeAnalysisDiagnosticsResources));
private static readonly string s_symbolTypeFullName = typeof(ISymbol).FullName;
private const string s_symbolEqualsName = nameof(ISymbol.Equals);
public const string SymbolEqualityComparerName = "Microsoft.CodeAnalysis.Shared.Utilities.SymbolEquivalenceComparer";
public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticIds.CompareSymbolsCorrectlyRuleId,
s_localizableTitle,
s_localizableMessage,
DiagnosticCategory.MicrosoftCodeAnalysisCorrectness,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_localizableDescription,
customTags: WellKnownDiagnosticTags.Telemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.RegisterCompilationStartAction(context =>
{
var compilation = context.Compilation;
var symbolType = compilation.GetTypeByMetadataName(s_symbolTypeFullName);
if (symbolType is null)
{
return;
}
// Check that the s_symbolEqualityComparerName exists and can be used, otherwise the Roslyn version
// being used it too low to need the change for method references
var symbolEqualityComparerType = context.Compilation.GetTypeByMetadataName(SymbolEqualityComparerName);
var operatorsToHandle = symbolEqualityComparerType is null ?
new[] { OperationKind.BinaryOperator } :
new[] { OperationKind.BinaryOperator, OperationKind.MethodReference };
context.RegisterOperationAction(context => HandleOperation(in context, symbolType), operatorsToHandle);
});
}
private void HandleOperation(in OperationAnalysisContext context, INamedTypeSymbol symbolType)
{
if (context.Operation is IBinaryOperation)
{
HandleBinaryOperator(context, symbolType);
}
if (context.Operation is IMethodReferenceOperation)
{
HandleMethodReferenceOperation(context, symbolType);
}
}
private static void HandleBinaryOperator(in OperationAnalysisContext context, INamedTypeSymbol symbolType)
{
var binary = (IBinaryOperation)context.Operation;
if (binary.OperatorKind != BinaryOperatorKind.Equals && binary.OperatorKind != BinaryOperatorKind.NotEquals)
{
return;
}
// Allow user-defined operators
if (binary.OperatorMethod?.ContainingSymbol is INamedTypeSymbol containingType
&& containingType.SpecialType != SpecialType.System_Object)
{
return;
}
// If either operand is 'null' or 'default', do not analyze
if (binary.LeftOperand.HasNullConstantValue() || binary.RightOperand.HasNullConstantValue())
{
return;
}
if (!IsSymbolType(binary.LeftOperand, symbolType)
&& !IsSymbolType(binary.RightOperand, symbolType))
{
return;
}
if (binary.Language == LanguageNames.VisualBasic)
{
if (IsSymbolClassType(binary.LeftOperand) || IsSymbolClassType(binary.RightOperand))
{
return;
}
}
if (IsExplicitCastToObject(binary.LeftOperand) || IsExplicitCastToObject(binary.RightOperand))
{
return;
}
context.ReportDiagnostic(binary.Syntax.GetLocation().CreateDiagnostic(Rule));
}
private static void HandleMethodReferenceOperation(OperationAnalysisContext context, INamedTypeSymbol symbolType)
{
var methodReference = (IMethodReferenceOperation)context.Operation;
if (methodReference.Instance != null && !IsSymbolType(methodReference.Instance, symbolType))
{
return;
}
var parameters = methodReference.Method.Parameters;
if (methodReference.Method.Name == s_symbolEqualsName && parameters.All(p => IsSymbolType(p.Type, symbolType)))
{
context.ReportDiagnostic(methodReference.Syntax.GetLocation().CreateDiagnostic(Rule));
}
}
private static bool IsSymbolType(IOperation operation, INamedTypeSymbol symbolType)
{
if (operation.Type is object && IsSymbolType(operation.Type, symbolType))
{
return true;
}
if (operation is IConversionOperation conversion)
{
return IsSymbolType(conversion.Operand, symbolType);
}
return false;
}
private static bool IsSymbolType(ITypeSymbol typeSymbol, INamedTypeSymbol symbolType)
{
if (typeSymbol == null)
{
return false;
}
if (typeSymbol.Equals(symbolType))
{
return true;
}
if (typeSymbol.AllInterfaces.Contains(symbolType))
{
return true;
}
return false;
}
private static bool IsSymbolClassType(IOperation operation)
{
if (operation.Type is object)
{
if (operation.Type.TypeKind == TypeKind.Class
&& operation.Type.SpecialType != SpecialType.System_Object)
{
return true;
}
}
if (operation is IConversionOperation conversion)
{
return IsSymbolClassType(conversion.Operand);
}
return false;
}
private static bool IsExplicitCastToObject(IOperation operation)
{
if (!(operation is IConversionOperation conversion))
{
return false;
}
if (conversion.IsImplicit)
{
return false;
}
return conversion.Type?.SpecialType == SpecialType.System_Object;
}
}
}