|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.Diagnostics.CodeAnalysis; |
| 7 | +using System.Linq; |
| 8 | +using System.Threading; |
| 9 | +using Microsoft.CodeAnalysis.CodeStyle; |
| 10 | +using Microsoft.CodeAnalysis.CSharp.Extensions; |
| 11 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 12 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 13 | + |
| 14 | +namespace Microsoft.CodeAnalysis.CSharp.SimplifyLinqExpression; |
| 15 | + |
| 16 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 17 | +internal sealed class CSharpSimplifyLinqTypeCheckAndCastDiagnosticAnalyzer() |
| 18 | + : AbstractBuiltInCodeStyleDiagnosticAnalyzer( |
| 19 | + IDEDiagnosticIds.SimplifyLinqTypeCheckAndCastDiagnosticId, |
| 20 | + EnforceOnBuildValues.SimplifyLinqExpression, |
| 21 | + option: null, |
| 22 | + title: new LocalizableResourceString(nameof(AnalyzersResources.Simplify_LINQ_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) |
| 23 | +{ |
| 24 | + public override DiagnosticAnalyzerCategory GetAnalyzerCategory() |
| 25 | + => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; |
| 26 | + |
| 27 | + protected override void InitializeWorker(AnalysisContext context) |
| 28 | + { |
| 29 | + context.RegisterCompilationStartAction(context => |
| 30 | + { |
| 31 | + var enumerableType = context.Compilation.GetTypeByMetadataName(typeof(Enumerable).FullName!); |
| 32 | + if (enumerableType is null) |
| 33 | + return; |
| 34 | + |
| 35 | + context.RegisterSyntaxNodeAction(context => AnalyzeInvocationExpression(context, enumerableType), SyntaxKind.InvocationExpression); |
| 36 | + }); |
| 37 | + } |
| 38 | + |
| 39 | + private static bool TryGetSingleLambdaParameter( |
| 40 | + LambdaExpressionSyntax lambda, |
| 41 | + [NotNullWhen(true)] out ParameterSyntax? lambdaParameter) |
| 42 | + { |
| 43 | + lambdaParameter = null; |
| 44 | + var whereParameters = lambda switch |
| 45 | + { |
| 46 | + ParenthesizedLambdaExpressionSyntax parenthesizedLambda => parenthesizedLambda.ParameterList.Parameters, |
| 47 | + SimpleLambdaExpressionSyntax simpleLambda => [simpleLambda.Parameter], |
| 48 | + _ => [], |
| 49 | + }; |
| 50 | + |
| 51 | + if (whereParameters is not [var parameter]) |
| 52 | + return false; |
| 53 | + |
| 54 | + lambdaParameter = parameter; |
| 55 | + return true; |
| 56 | + } |
| 57 | + |
| 58 | + private static bool AnalyzeWhereMethod( |
| 59 | + SemanticModel semanticModel, |
| 60 | + LambdaExpressionSyntax whereLambda, |
| 61 | + CancellationToken cancellationToken, |
| 62 | + [NotNullWhen(true)] out ITypeSymbol? whereType) |
| 63 | + { |
| 64 | + whereType = null; |
| 65 | + |
| 66 | + // has to look like `a => a is ...` or `(T a) => a is ...` |
| 67 | + if (!TryGetSingleLambdaParameter(whereLambda, out var parameter)) |
| 68 | + return false; |
| 69 | + |
| 70 | + // Body needs to be `a is SomeType` |
| 71 | + var parameterName = parameter.Identifier.ValueText; |
| 72 | + if (whereLambda.Body is not BinaryExpressionSyntax(kind: SyntaxKind.IsExpression) |
| 73 | + { |
| 74 | + Left: IdentifierNameSyntax leftIdentifier, |
| 75 | + Right: TypeSyntax whereTypeSyntax |
| 76 | + }) |
| 77 | + { |
| 78 | + return false; |
| 79 | + } |
| 80 | + |
| 81 | + // Value being checked needs to be the parameter passed in. |
| 82 | + if (leftIdentifier.Identifier.ValueText != parameterName) |
| 83 | + return false; |
| 84 | + |
| 85 | + whereType = semanticModel.GetTypeInfo(whereTypeSyntax, cancellationToken).Type; |
| 86 | + return whereType != null; |
| 87 | + } |
| 88 | + |
| 89 | + private bool AnalyzeInvocationExpression( |
| 90 | + InvocationExpressionSyntax invocationExpression, |
| 91 | + [NotNullWhen(true)] out LambdaExpressionSyntax? whereLambda, |
| 92 | + [NotNullWhen(true)] out InvocationExpressionSyntax? whereInvocation, |
| 93 | + [NotNullWhen(true)] out SimpleNameSyntax? caseOrSelectName, |
| 94 | + [NotNullWhen(true)] out TypeSyntax? caseOrSelectType) |
| 95 | + { |
| 96 | + whereLambda = null; |
| 97 | + whereInvocation = null; |
| 98 | + caseOrSelectName = null; |
| 99 | + caseOrSelectType = null; |
| 100 | + |
| 101 | + // Both forms need to be accessed off of `.Where(... => ...)` |
| 102 | + // Needs to look like `.Where(...).Cast<...>()` |
| 103 | + if (invocationExpression is not |
| 104 | + { |
| 105 | + Expression: MemberAccessExpressionSyntax |
| 106 | + { |
| 107 | + Expression: InvocationExpressionSyntax |
| 108 | + { |
| 109 | + // Needs to be `.Where(... => ...)` |
| 110 | + ArgumentList.Arguments: [{ Expression: LambdaExpressionSyntax whereLambda1 }], |
| 111 | + Expression: MemberAccessExpressionSyntax |
| 112 | + { |
| 113 | + Name: IdentifierNameSyntax { Identifier.ValueText: nameof(Enumerable.Where) }, |
| 114 | + }, |
| 115 | + } whereInvocation1, |
| 116 | + }, |
| 117 | + }) |
| 118 | + { |
| 119 | + return false; |
| 120 | + } |
| 121 | + |
| 122 | + whereLambda = whereLambda1; |
| 123 | + whereInvocation = whereInvocation1; |
| 124 | + |
| 125 | + if (invocationExpression is |
| 126 | + { |
| 127 | + // Needs to be `.Cast<T>()` |
| 128 | + ArgumentList.Arguments: [], |
| 129 | + Expression: MemberAccessExpressionSyntax |
| 130 | + { |
| 131 | + Name: GenericNameSyntax |
| 132 | + { |
| 133 | + Identifier.ValueText: nameof(Enumerable.Cast), |
| 134 | + TypeArgumentList.Arguments: [var castTypeArgument] |
| 135 | + } castName, |
| 136 | + }, |
| 137 | + }) |
| 138 | + { |
| 139 | + caseOrSelectName = castName; |
| 140 | + caseOrSelectType = castTypeArgument; |
| 141 | + return true; |
| 142 | + } |
| 143 | + |
| 144 | + // Needs to be `.Select(a => (T)a)` |
| 145 | + if (invocationExpression is |
| 146 | + { |
| 147 | + ArgumentList.Arguments: [ |
| 148 | + { |
| 149 | + // a => (T)a |
| 150 | + Expression: LambdaExpressionSyntax |
| 151 | + { |
| 152 | + ExpressionBody: CastExpressionSyntax |
| 153 | + { |
| 154 | + Type: var lambdaCastType, |
| 155 | + Expression: IdentifierNameSyntax castIdentifier, |
| 156 | + } lambdaCast, |
| 157 | + } selectLambda |
| 158 | + }], |
| 159 | + Expression: MemberAccessExpressionSyntax |
| 160 | + { |
| 161 | + Name: IdentifierNameSyntax |
| 162 | + { |
| 163 | + Identifier.ValueText: nameof(Enumerable.Select), |
| 164 | + } selectName, |
| 165 | + }, |
| 166 | + } && TryGetSingleLambdaParameter(selectLambda, out var selectLambdaParameter) && |
| 167 | + selectLambdaParameter.Identifier.ValueText == castIdentifier.Identifier.ValueText) |
| 168 | + { |
| 169 | + caseOrSelectName = selectName; |
| 170 | + caseOrSelectType = lambdaCastType; |
| 171 | + return true; |
| 172 | + } |
| 173 | + |
| 174 | + return false; |
| 175 | + } |
| 176 | + |
| 177 | + private void AnalyzeInvocationExpression( |
| 178 | + SyntaxNodeAnalysisContext context, INamedTypeSymbol enumerableType) |
| 179 | + { |
| 180 | + var cancellationToken = context.CancellationToken; |
| 181 | + var semanticModel = context.SemanticModel; |
| 182 | + |
| 183 | + if (ShouldSkipAnalysis(context, notification: null)) |
| 184 | + return; |
| 185 | + |
| 186 | + var invocationExpression = (InvocationExpressionSyntax)context.Node; |
| 187 | + |
| 188 | + if (!AnalyzeInvocationExpression(invocationExpression, |
| 189 | + out var whereLambda, |
| 190 | + out var whereInvocation, |
| 191 | + out var castOrSelectName, |
| 192 | + out var castTypeArgument)) |
| 193 | + { |
| 194 | + return; |
| 195 | + } |
| 196 | + |
| 197 | + if (!AnalyzeWhereMethod(semanticModel, whereLambda, cancellationToken, out var whereType)) |
| 198 | + return; |
| 199 | + |
| 200 | + // Ensure the `is SomeType` and `Cast<SomeType>` are the same type. |
| 201 | + var castType = semanticModel.GetTypeInfo(castTypeArgument, cancellationToken).Type; |
| 202 | + if (castType is null) |
| 203 | + return; |
| 204 | + |
| 205 | + if (!whereType.Equals(castType)) |
| 206 | + return; |
| 207 | + |
| 208 | + var castOrSelectSymbol = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken).Symbol; |
| 209 | + var whereSymbol = semanticModel.GetSymbolInfo(whereInvocation, cancellationToken).Symbol; |
| 210 | + |
| 211 | + if (!enumerableType.Equals(castOrSelectSymbol?.OriginalDefinition.ContainingType) || |
| 212 | + !enumerableType.Equals(whereSymbol?.OriginalDefinition.ContainingType)) |
| 213 | + { |
| 214 | + return; |
| 215 | + } |
| 216 | + |
| 217 | + context.ReportDiagnostic(Diagnostic.Create( |
| 218 | + Descriptor, |
| 219 | + castOrSelectName.Identifier.GetLocation(), |
| 220 | + additionalLocations: [invocationExpression.GetLocation(), castTypeArgument.GetLocation()])); |
| 221 | + } |
| 222 | +} |
0 commit comments