Skip to content

Commit

Permalink
Fix S3247 FN: When cast expression contains parentheses (#9492)
Browse files Browse the repository at this point in the history
Co-authored-by: mary-georgiou-sonarsource <[email protected]>
  • Loading branch information
1 parent db48fa2 commit 09a749a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,8 @@ private static void ReportPatternAtCastLocation(SonarSyntaxNodeReportingContext

private static bool IsEquivalentVariable(ExpressionSyntax expression, SyntaxNode typedVariable)
{
var left = RemoveThisExpression(typedVariable).WithoutTrivia();
var right = RemoveThisExpression(expression).WithoutTrivia();
var left = CleanupExpression(typedVariable).WithoutTrivia();
var right = CleanupExpression(expression).WithoutTrivia();

return left.IsEquivalentTo(right)
|| (StandaloneIdentifier(left) is { } leftIdentifier && leftIdentifier == StandaloneIdentifier(right));
Expand All @@ -245,8 +245,14 @@ static string StandaloneIdentifier(SyntaxNode node) =>
_ when node.IsKind(SyntaxKindEx.SingleVariableDesignation) => ((SingleVariableDesignationSyntaxWrapper)node).Identifier.ValueText,
_ => null
};
}

static SyntaxNode RemoveThisExpression(SyntaxNode node) =>
node is MemberAccessExpressionSyntax { Expression: ThisExpressionSyntax } memberAccess ? memberAccess.Name : node;
private static SyntaxNode CleanupExpression(SyntaxNode node)
{
while (node is ParenthesizedExpressionSyntax parenthesized)
{
node = parenthesized.Expression;
}
return node is MemberAccessExpressionSyntax { Expression: ThisExpressionSyntax } memberAccess ? memberAccess.Name : node;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,22 @@ public void IgnoreMemberAccess(Fruit arg)
_ = (Fruit)differentInstance.Property;
}

// https://github.com/SonarSource/sonar-dotnet/issues/9491
if (arg.Property is Fruit) // Noncompliant
{
_ = ((Fruit)(arg.Property)).Property; // Secondary
}

if (arg.Property is Fruit) // Noncompliant
{
_ = ((Fruit)((arg.Property))).Property; // Secondary
}

if (arg.Property is Fruit) // Noncompliant
{
_ = ((Fruit)arg.Property).Property; // Secondary
}

if (f.Property is Fruit) // Compliant, the cast is on a different instance
{
_ = (Fruit)differentInstance.Property;
Expand Down Expand Up @@ -128,6 +144,12 @@ public void TakeIdentifierIntoAccount(object x)
var fruit = (Fruit)this.someField;
// ^^^^^^^^^^^^^^^^^^^^^ Secondary
}

if (someField is Fruit) // Noncompliant
{
var fruit = ((Fruit)(this.someField));
// ^^^^^^^^^^^^^^^^^^^^^^^ Secondary
}
}

public void UnknownFoo(object x)
Expand Down

0 comments on commit 09a749a

Please sign in to comment.