Skip to content

Commit

Permalink
Fix CA1862 false positive with same variable on both sides of comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
louis-z committed Dec 23, 2024
1 parent 5ed3367 commit fa98aa7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,15 @@ private static void AnalyzeBinaryOperation(OperationAnalysisContext context, IBi
return;
}

// If using the same parameter on both sides of the binary operation, don't emit a diagnostic.
var lParam = GetParameter(binaryOperation.LeftOperand);
var rParam = GetParameter(binaryOperation.RightOperand);

if (lParam is not null && lParam == rParam)
{
return;
}

ImmutableDictionary<string, string?> dict = new Dictionary<string, string?>()
{
{ LeftOffendingMethodName, leftOffendingMethodName },
Expand Down Expand Up @@ -380,5 +389,15 @@ private static bool IsOffendingMethod(IInvocationOperation invocation, ITypeSymb
offendingMethodName = invocation.TargetMethod.Name;
return true;
}

private static IParameterSymbol? GetParameter(IOperation op)
{
return op switch
{
IParameterReferenceOperation paramRefOp => paramRefOp.Parameter,
IInvocationOperation invocationOp => GetParameter(invocationOp.Children.FirstOrDefault()),
_ => null,
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,30 @@ void M(string s)
}.RunAsync();
}

[Theory]
[InlineData("s != s.ToLowerInvariant()")]
[InlineData("s.ToLower() == s")]
[InlineData("s.ToUpperInvariant() == s.ToUpper()")]
[InlineData("s.ToLower().ToUpper() != s")]
[WorkItem(7074, "https://github.com/dotnet/roslyn-analyzers/issues/7074")]
public async Task NoDiagnostic_SameParameterOnBothSidesOfComparison(string expression)
{
var originalCode = $$"""
using System;
class C
{
void M(string s)
{
if ({{expression}})
Console.WriteLine("string comparison was true");
}
}
""";

await VerifyNoDiagnosticCSharpAsync(originalCode);
}

private async Task VerifyNoDiagnosticCSharpAsync(string originalSource)
{
VerifyCS.Test test = new()
Expand Down

0 comments on commit fa98aa7

Please sign in to comment.