Given the following piece of code as an example:
public class Thing
{
public int Item { get; }
public Thing(int item)
{
Item = Item; // note incorrect assignment: rhs should be item, the passed-in arg, hence analyzer should warn
}
public Thing(Thing other)
{
Item = other.Item; // correct assignment, should NOT trigger analyzer
}
}
I'm writing a Roslyn analyzer to detect and report these cases of possible mistaken self-assignment, pertinent portions below:
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(MistakenSelfAssignment, SyntaxKind.SimpleAssignmentExpression);
}
private static void MistakenSelfAssignment(SyntaxNodeAnalysisContext context)
{
var assignment = context.Node as AssignmentExpressionSyntax;
if (assignment == null)
{
return;
}
var leftToken = GetIdentifierToken(assignment.Left);
var rightToken = GetIdentifierToken(assignment.Right);
if (leftToken != null && leftToken.IsEquivalentTo(rightToken)) // this never works
{
var diagnostic = Diagnostic.Create(Rule, assignment.GetLocation());
context.ReportDiagnostic(diagnostic);
}
}
private static SyntaxToken GetIdentifierToken(ExpressionSyntax syntax)
{
var identifierName = syntax as IdentifierNameSyntax;
if (identifierName != null)
{
return identifierName.Identifier;
}
var identifierAccess = syntax as MemberAccessExpressionSyntax;
if (identifierAccess != null)
{
return identifierAccess.Name.Identifier;
}
return default(SyntaxToken);
}
But I can't figure out how to determine if the LHS and RHS of the assignment are the same token - SyntaxToken.IsEquivalentTo
appears to be the method I want, but it always returns false, as do SyntaxToken.Equals
and ==
.
What's the correct way to determine if a token is referring to itself?