Skip to content

Commit

Permalink
Fix varaible designation
Browse files Browse the repository at this point in the history
  • Loading branch information
pavel-mikula-sonarsource committed Jun 28, 2024
1 parent dce3c8e commit e2340ef
Showing 1 changed file with 23 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

using System.Linq.Expressions;

namespace SonarAnalyzer.Rules.CSharp;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
Expand Down Expand Up @@ -107,11 +109,8 @@ bool IsDuplicatedCastOnSameSymbol(ExpressionSyntax expression, SyntaxNode type)
&& !CSharpFacade.Instance.Syntax.IsInExpressionTree(context.SemanticModel, expression); // see https://github.com/SonarSource/sonar-dotnet/issues/8735#issuecomment-1943419398

bool IsCastOnSameSymbol(ExpressionSyntax expression) =>
RemoveThisExpression(typedVariable).WithoutTrivia().IsEquivalentTo(RemoveThisExpression(expression).WithoutTrivia())
IsEquivalentVariable(expression, typedVariable)
&& Equals(context.SemanticModel.GetSymbolInfo(expression).Symbol, typeExpressionSymbol);

static SyntaxNode RemoveThisExpression(SyntaxNode node) =>
node is MemberAccessExpressionSyntax { Expression: ThisExpressionSyntax } memberAccess ? memberAccess.Name : node;
}

private static void ProcessPatternExpression(SonarSyntaxNodeReportingContext analysisContext, SyntaxNode isPattern, SyntaxNode mainVariableExpression, SyntaxNode parentStatement)
Expand Down Expand Up @@ -232,4 +231,24 @@ private static void ReportPatternAtCastLocation(SonarSyntaxNodeReportingContext
context.ReportIssue(Rule, castLocation, [patternLocation.ToSecondary()], message);
}
}

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

return left.IsEquivalentTo(right)
|| (StandaloneIdentifier(left) is { } leftIdentifier && leftIdentifier == StandaloneIdentifier(right));

static string StandaloneIdentifier(SyntaxNode node) =>
node switch
{
IdentifierNameSyntax name => name.Identifier.ValueText,
_ when node.IsKind(SyntaxKindEx.SingleVariableDesignation) => ((SingleVariableDesignationSyntaxWrapper)node).Identifier.ValueText,
_ => null
};

static SyntaxNode RemoveThisExpression(SyntaxNode node) =>
node is MemberAccessExpressionSyntax { Expression: ThisExpressionSyntax } memberAccess ? memberAccess.Name : node;
}
}

0 comments on commit e2340ef

Please sign in to comment.