Skip to content

Commit 1e86fc9

Browse files
committed
Fix logic in SA1308CodeFixProvider
- Checking token.ValueText.Length <= 2 beforehand implies the text is not null or empty - Do not offer a code fix when a string consists entirely of multiple prefixes
1 parent 841c0ac commit 1e86fc9

1 file changed

Lines changed: 18 additions & 16 deletions

File tree

StyleCop.Analyzers/StyleCop.Analyzers.CodeFixes/NamingRules/SA1308CodeFixProvider.cs

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -42,18 +42,12 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
4242
{
4343
var token = root.FindToken(diagnostic.Location.SourceSpan.Start);
4444

45-
// The variable name is the full suffix. In this case we cannot generate a valid variable name and thus will not offer a code fix.
46-
if (token.ValueText.Length <= 2)
47-
{
48-
continue;
49-
}
50-
51-
var numberOfCharsToRemove = 2;
45+
var numberOfCharsToRemove = 0;
5246

5347
// If a variable contains multiple prefixes that would result in this diagnostic,
5448
// we detect that and remove all of the bad prefixes such that after
5549
// the fix is applied there are no more violations of this rule.
56-
for (int i = 2; i < token.ValueText.Length; i += 2)
50+
for (int i = 0; i < token.ValueText.Length; i += 2)
5751
{
5852
if (string.Compare("m_", 0, token.ValueText, i, 2, StringComparison.Ordinal) == 0
5953
|| string.Compare("s_", 0, token.ValueText, i, 2, StringComparison.Ordinal) == 0
@@ -66,16 +60,24 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
6660
break;
6761
}
6862

69-
if (!string.IsNullOrEmpty(token.ValueText))
63+
if (numberOfCharsToRemove == 0)
64+
{
65+
continue;
66+
}
67+
68+
// The prefix is the full variable name. In this case we cannot generate a valid variable name and thus will not offer a code fix.
69+
if (token.ValueText.Length == numberOfCharsToRemove)
7070
{
71-
var newName = token.ValueText.Substring(numberOfCharsToRemove);
72-
context.RegisterCodeFix(
73-
CodeAction.Create(
74-
string.Format(NamingResources.RenameToCodeFix, newName),
75-
cancellationToken => RenameHelper.RenameSymbolAsync(document, root, token, newName, cancellationToken),
76-
nameof(SA1308CodeFixProvider)),
77-
diagnostic);
71+
continue;
7872
}
73+
74+
var newName = token.ValueText.Substring(numberOfCharsToRemove);
75+
context.RegisterCodeFix(
76+
CodeAction.Create(
77+
string.Format(NamingResources.RenameToCodeFix, newName),
78+
cancellationToken => RenameHelper.RenameSymbolAsync(document, root, token, newName, cancellationToken),
79+
nameof(SA1308CodeFixProvider)),
80+
diagnostic);
7981
}
8082
}
8183
}

0 commit comments

Comments
 (0)