Skip to content

Commit 523db8a

Browse files
Updated SA1309CodeFixProvider to not provide a code fix if the resulting identifier would be illegal.
1 parent 90e043e commit 523db8a

2 files changed

Lines changed: 20 additions & 3 deletions

File tree

StyleCop.Analyzers/StyleCop.Analyzers.CodeFixes/NamingRules/SA1309CodeFixProvider.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ namespace StyleCop.Analyzers.NamingRules
1010
using Microsoft.CodeAnalysis;
1111
using Microsoft.CodeAnalysis.CodeActions;
1212
using Microsoft.CodeAnalysis.CodeFixes;
13+
using Microsoft.CodeAnalysis.CSharp;
1314

1415
/// <summary>
1516
/// Implements a code fix for <see cref="SA1309FieldNamesMustNotBeginWithUnderscore"/>.
@@ -45,10 +46,9 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
4546
{
4647
var newName = token.ValueText.TrimStart(new[] { '_' });
4748

48-
if (string.IsNullOrEmpty(newName))
49+
if (!SyntaxFacts.IsValidIdentifier(newName))
4950
{
50-
// The variable consisted of only underscores. In this case we cannot
51-
// generate a valid variable name and thus will not offer a code fix.
51+
// The proposed name was not legal, so no code fix will be offered.
5252
continue;
5353
}
5454

StyleCop.Analyzers/StyleCop.Analyzers.Test/NamingRules/SA1309UnitTests.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,23 @@ public async Task TestFieldStartingWithMultipleUnderscoresAsync()
132132
await this.VerifyCSharpFixAsync(testCode, fixedCode).ConfigureAwait(false);
133133
}
134134

135+
// This a regression test for issue #2360.
136+
[Fact]
137+
public async Task VerifyThatAFieldStartingWithAnUnderscoreAndADigitIsNotAffectedByCodeFixAsync()
138+
{
139+
var testCode = @"public class Foo
140+
{
141+
private string _1bar = ""baz"";
142+
}";
143+
144+
DiagnosticResult expected = this.CSharpDiagnostic().WithArguments("_1bar").WithLocation(3, 20);
145+
await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
146+
147+
// no changes will be made
148+
var fixedCode = testCode;
149+
await this.VerifyCSharpFixAsync(testCode, fixedCode).ConfigureAwait(false);
150+
}
151+
135152
protected override IEnumerable<DiagnosticAnalyzer> GetCSharpDiagnosticAnalyzers()
136153
{
137154
yield return new SA1309FieldNamesMustNotBeginWithUnderscore();

0 commit comments

Comments
 (0)