Skip to content

Commit

Permalink
Merge pull request #3710 from bjornhellander/feature/sa1131-methods-a…
Browse files Browse the repository at this point in the history
…s-constants

Update SA1131 to treat methods as constants
  • Loading branch information
sharwell authored Oct 17, 2023
2 parents 61aea88 + dfd5ed2 commit 3411684
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -508,5 +508,81 @@ public void Test()
};
await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false);
}

[Theory]
[InlineData("Method1", "arg", true)]
[InlineData("Method2", "arg", true)]
[InlineData("Method1", "field1", true)]
[InlineData("Method2", "field1", true)]
[InlineData("Method1", "field2", true)]
[InlineData("Method2", "field2", true)]
[InlineData("Const1", "Method1", false)]
[InlineData("Const1", "Method2", false)]
[InlineData("Method1", "Const1", false)]
[InlineData("Method2", "Const1", false)]
[WorkItem(3677, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3677")]
public async Task TestMethodsAsync(string expr1, string expr2, bool shouldTrigger)
{
var testExpr = $"{expr1} == {expr2}";
var testCode = $@"
using System;
public class TestClass
{{
private static readonly Action Const1 = Method1;
private Action field1 = Method1;
private readonly Action field2 = Method1;
public bool TestMethod(Action arg)
{{
return {(shouldTrigger ? $"[|{testExpr}|]" : testExpr)};
}}
private static void Method1()
{{
}}
private void Method2()
{{
}}
}}
";

var fixedExpr = $"{expr2} == {expr1}";
var fixedCode = $@"
using System;
public class TestClass
{{
private static readonly Action Const1 = Method1;
private Action field1 = Method1;
private readonly Action field2 = Method1;
public bool TestMethod(Action arg)
{{
return {fixedExpr};
}}
private static void Method1()
{{
}}
private void Method2()
{{
}}
}}
";

if (shouldTrigger)
{
await VerifyCSharpFixAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, fixedCode, CancellationToken.None).ConfigureAwait(false);
}
else
{
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,16 @@ private static bool IsLiteral(ExpressionSyntax expression, SemanticModel semanti
return true;
}

if (semanticModel.GetSymbolInfo(expression).Symbol is IFieldSymbol fieldSymbol)
var symbol = semanticModel.GetSymbolInfo(expression).Symbol;
switch (symbol)
{
return fieldSymbol.IsStatic && fieldSymbol.IsReadOnly;
}
case IFieldSymbol fieldSymbol when fieldSymbol.IsStatic && fieldSymbol.IsReadOnly:
case IMethodSymbol:
return true;

return false;
default:
return false;
}
}
}
}

0 comments on commit 3411684

Please sign in to comment.