Skip to content

Commit

Permalink
Clean up CheckCastExpression
Browse files Browse the repository at this point in the history
  • Loading branch information
Tim-Pohlmann committed Feb 15, 2023
1 parent cbf178b commit f02a011
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions analyzers/src/SonarAnalyzer.CSharp/Rules/RedundantCast.cs
Expand Up @@ -65,29 +65,35 @@ private static void CheckCastExpression(SonarSyntaxNodeReportingContext context,
}

var expressionTypeInfo = context.SemanticModel.GetTypeInfo(expression);
var expressionType = expressionTypeInfo.Type;
if (expressionType == null)
if (expressionTypeInfo.Type is not { } expressionType)
{
return;
}

var castTypeInfo = context.SemanticModel.GetTypeInfo(type);
var castType = castTypeInfo.Type;
if (castType == null)
if (castTypeInfo.Type is not { } castType)
{
return;
}

var castToNullable = type is NullableTypeSyntax;
var expressionFlowState = expressionTypeInfo.Nullability().FlowState;
var expressionMaybeNull = expressionFlowState == NullableFlowState.MaybeNull;

if (expressionType.Equals(castType) && (expressionFlowState == NullableFlowState.None || expressionMaybeNull == castToNullable))
if (expressionType.Equals(castType) && FlowStateIsNoneOrMatchesCast(expressionTypeInfo, type))
{
ReportIssue(context, expression, location, castType);
}
}

private static bool FlowStateIsNoneOrMatchesCast(TypeInfo expressionTypeInfo, ExpressionSyntax type)
{
var castingToNullable = type is NullableTypeSyntax;
return expressionTypeInfo.Nullability().FlowState switch
{
NullableFlowState.None => true,
NullableFlowState.MaybeNull => castingToNullable,
NullableFlowState.NotNull => !castingToNullable,
_ => throw new NotSupportedException()
};
}

private static void CheckExtensionMethodInvocation(SonarSyntaxNodeReportingContext context)
{
var invocation = (InvocationExpressionSyntax)context.Node;
Expand Down

0 comments on commit f02a011

Please sign in to comment.