Skip to content

Commit

Permalink
Fix SA1131 to not treat "complex" expressions as a literal
Browse files Browse the repository at this point in the history
  • Loading branch information
bjornhellander committed Dec 20, 2023
1 parent 36cc2cc commit 32646fb
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -584,5 +584,29 @@ private void Method2()
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
}

[Theory]
[InlineData("==")]
[InlineData("!=")]
[InlineData(">=")]
[InlineData("<=")]
[InlineData(">")]
[InlineData("<")]
[WorkItem(3759, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3759")]
public async Task TestComplexLeftHandSideExpressionAsync(string @operator)
{
var testCode = $@"
using System;
public class TypeName
{{
public void Test(int x, int y, Func<int> a)
{{
var r1 = x + 1 {@operator} y;
var r2 = -x {@operator} y;
var r3 = a() {@operator} y;
}}
}}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,11 @@ private static bool IsLiteral(ExpressionSyntax expression, SemanticModel semanti
switch (symbol)
{
case IFieldSymbol fieldSymbol when fieldSymbol.IsStatic && fieldSymbol.IsReadOnly:
case IMethodSymbol:
return true;

// NOTE: Without the when clause, this would also treat e.g unary or binary expressions as literals,
// since GetSymbolInfo returns the operator method in those cases.
case IMethodSymbol when expression is IdentifierNameSyntax:
return true;

default:
Expand Down

0 comments on commit 32646fb

Please sign in to comment.