-
Notifications
You must be signed in to change notification settings - Fork 222
/
RedundantCast.cs
174 lines (153 loc) · 7.39 KB
/
RedundantCast.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
/*
* SonarAnalyzer for .NET
* Copyright (C) 2015-2023 SonarSource SA
* mailto: contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
namespace SonarAnalyzer.Rules.CSharp;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class RedundantCast : SonarDiagnosticAnalyzer
{
internal const string DiagnosticId = "S1905";
private const string MessageFormat = "Remove this unnecessary cast to '{0}'.";
private static readonly DiagnosticDescriptor Rule =
DescriptorFactory.Create(DiagnosticId, MessageFormat);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule);
private static readonly ISet<string> CastIEnumerableMethods = new HashSet<string> { "Cast", "OfType" };
protected override void Initialize(SonarAnalysisContext context)
{
context.RegisterNodeAction(
c =>
{
var castExpression = (CastExpressionSyntax)c.Node;
CheckCastExpression(c, castExpression.Expression, castExpression.Type, castExpression.Type.GetLocation());
},
SyntaxKind.CastExpression);
context.RegisterNodeAction(
c =>
{
var castExpression = (BinaryExpressionSyntax)c.Node;
CheckCastExpression(c, castExpression.Left, castExpression.Right,
castExpression.OperatorToken.CreateLocation(castExpression.Right));
},
SyntaxKind.AsExpression);
context.RegisterNodeAction(
CheckExtensionMethodInvocation,
SyntaxKind.InvocationExpression);
}
private static void CheckCastExpression(SonarSyntaxNodeReportingContext context, ExpressionSyntax expression, ExpressionSyntax type, Location location)
{
if (expression.IsKind(SyntaxKindEx.DefaultLiteralExpression))
{
return;
}
var expressionTypeInfo = context.SemanticModel.GetTypeInfo(expression);
var expressionType = expressionTypeInfo.Type;
if (expressionType == null)
{
return;
}
var castTypeInfo = context.SemanticModel.GetTypeInfo(type);
var castType = castTypeInfo.Type;
if (castType == null)
{
return;
}
if (expressionType.Equals(castType) && expressionTypeInfo.Nullability() == castTypeInfo.Nullability())
{
ReportIssue(context, expression, location, castType);
}
}
private static void CheckExtensionMethodInvocation(SonarSyntaxNodeReportingContext context)
{
var invocation = (InvocationExpressionSyntax)context.Node;
if (GetEnumerableExtensionSymbol(invocation, context.SemanticModel) is { } methodSymbol)
{
var returnType = methodSymbol.ReturnType;
if (GetGenericTypeArgument(returnType) is { } castType)
{
if (methodSymbol.Name == "OfType" && CanHaveNullValue(castType))
{
// OfType() filters 'null' values from enumerables
return;
}
var elementType = GetElementType(invocation, methodSymbol, context.SemanticModel);
// Generic types {T} and {T?} are equal and there is no way to access NullableAnnotation field right now
// See https://github.com/SonarSource/sonar-dotnet/issues/3273
if (elementType != null && elementType.Equals(castType) && string.Equals(elementType.ToString(), castType.ToString(), StringComparison.Ordinal))
{
var methodCalledAsStatic = methodSymbol.MethodKind == MethodKind.Ordinary;
ReportIssue(context, invocation, GetReportLocation(invocation, methodCalledAsStatic), returnType);
}
}
}
}
private static void ReportIssue(SonarSyntaxNodeReportingContext context,
ExpressionSyntax expression,
Location location,
ITypeSymbol castType) =>
context.ReportIssue(Diagnostic.Create(Rule, location, castType.ToMinimalDisplayString(context.SemanticModel, expression.SpanStart)));
/// If the invocation one of the <see cref="CastIEnumerableMethods"/> extensions, returns the method symbol.
private static IMethodSymbol GetEnumerableExtensionSymbol(InvocationExpressionSyntax invocation, SemanticModel semanticModel) =>
invocation.GetMethodCallIdentifier() is { } methodName
&& CastIEnumerableMethods.Contains(methodName.ValueText)
&& semanticModel.GetSymbolInfo(invocation).Symbol is IMethodSymbol methodSymbol
&& methodSymbol.IsExtensionOn(KnownType.System_Collections_IEnumerable)
? methodSymbol
: null;
private static ITypeSymbol GetGenericTypeArgument(ITypeSymbol type) =>
type is INamedTypeSymbol returnType && returnType.Is(KnownType.System_Collections_Generic_IEnumerable_T)
? returnType.TypeArguments.Single()
: null;
private static bool CanHaveNullValue(ITypeSymbol type) => type.IsReferenceType || type.Name == "Nullable";
private static Location GetReportLocation(InvocationExpressionSyntax invocation, bool methodCalledAsStatic) =>
invocation.Expression switch
{
MemberAccessExpressionSyntax memberAccess => methodCalledAsStatic
? memberAccess.GetLocation()
: memberAccess.OperatorToken.CreateLocation(invocation),
_ => invocation.Expression.GetLocation()
};
private static ITypeSymbol GetElementType(InvocationExpressionSyntax invocation,
IMethodSymbol methodSymbol,
SemanticModel semanticModel)
{
ExpressionSyntax collection;
if (methodSymbol.MethodKind == MethodKind.Ordinary)
{
var firstArgument = invocation.ArgumentList.Arguments.FirstOrDefault();
if (firstArgument == default)
{
return null;
}
collection = firstArgument.Expression;
}
else
{
if (invocation.Expression is not MemberAccessExpressionSyntax memberAccess)
{
return null;
}
collection = memberAccess.Expression;
}
return semanticModel.GetTypeInfo(collection).Type switch
{
INamedTypeSymbol { TypeArguments: { Length: 1 } typeArguments } => typeArguments.First(),
IArrayTypeSymbol { Rank: 1 } arrayType => arrayType.ElementType, // casting is necessary for multidimensional arrays
_ => null
};
}
}