Skip to content

Commit

Permalink
fix and test
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesHargreaves12 committed Aug 6, 2023
1 parent 5ebe544 commit 6987ed8
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Common/CSharp/Analysis/UseConstantInsteadOfFieldAnalysis.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
Expand Down Expand Up @@ -69,7 +70,7 @@ internal static class UseConstantInsteadOfFieldAnalysis

if (!fieldSymbol.Type.SupportsConstantValue())
return false;

foreach (VariableDeclaratorSyntax declarator in declarators)
{
ExpressionSyntax value = declarator.Initializer?.Value;
Expand All @@ -82,6 +83,18 @@ internal static class UseConstantInsteadOfFieldAnalysis

if (!semanticModel.HasConstantValue(value, cancellationToken))
return false;

// Changing a static field to a constant changes the meaning of that symbol in the declerators.
foreach (var identifierName in value.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>())
{
if (identifierName.Identifier.ValueText != fieldSymbol.Name)
continue;

if (identifierName.Parent is MemberAccessExpressionSyntax memberAccessExpression && memberAccessExpression.Name == identifierName)
continue;

return false;
}
}

foreach (IMethodSymbol constructorSymbol in fieldSymbol.ContainingType.StaticConstructors)
Expand Down
13 changes: 13 additions & 0 deletions src/Tests/Analyzers.Tests/RCS1187UseConstantInsteadOfFieldTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,19 @@ static void M(in int value)
{
}
}
");
}

[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseConstantInsteadOfField)]
public async Task TestNoDiagnostic_SelfReference()
{
await VerifyNoDiagnosticAsync(@"
using System;
class C
{
private static readonly Double Double = Double.Epsilon;
}
");
}
}

0 comments on commit 6987ed8

Please sign in to comment.