Skip to content

Commit 77c2d72

Browse files
committed
Improved index initializer detection
1 parent 967a6cd commit 77c2d72

2 files changed

Lines changed: 38 additions & 12 deletions

File tree

StyleCop.Analyzers/StyleCop.Analyzers.Test/SpacingRules/SA1010UnitTests.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,42 @@ public void TestMethod(IDictionary<ulong, string> items)
183183
await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
184184
}
185185

186+
/// <summary>
187+
/// Verify that index initializer scope determination is working as intended.
188+
/// </summary>
189+
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
190+
[Fact]
191+
public async Task VerifyThatIndexInitializerScopeIsDeterminedProperlyAsync()
192+
{
193+
var testCode = @"using System.Collections.Generic;
194+
195+
public class TestClass
196+
{
197+
public void TestMethod(IDictionary<ulong, string> items)
198+
{
199+
int[] indexes = { 0 };
200+
var dictionary = new Dictionary<int, int> { [indexes [0]] = 0 };
201+
}
202+
}
203+
";
204+
205+
var fixedTestCode = @"using System.Collections.Generic;
206+
207+
public class TestClass
208+
{
209+
public void TestMethod(IDictionary<ulong, string> items)
210+
{
211+
int[] indexes = { 0 };
212+
var dictionary = new Dictionary<int, int> { [indexes[0]] = 0 };
213+
}
214+
}
215+
";
216+
var expected = this.CSharpDiagnostic().WithLocation(8, 62).WithArguments("not be preceded");
217+
await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
218+
await this.VerifyCSharpDiagnosticAsync(fixedTestCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
219+
await this.VerifyCSharpFixAsync(testCode, fixedTestCode).ConfigureAwait(false);
220+
}
221+
186222
/// <inheritdoc/>
187223
protected override IEnumerable<DiagnosticAnalyzer> GetCSharpDiagnosticAnalyzers()
188224
{

StyleCop.Analyzers/StyleCop.Analyzers/SpacingRules/SA1010OpeningSquareBracketsMustBeSpacedCorrectly.cs

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -107,18 +107,8 @@ private static void HandleOpenBracketToken(SyntaxTreeAnalysisContext context, Sy
107107

108108
private static bool IsPartOfIndexInitializer(SyntaxToken token)
109109
{
110-
var currentParent = token.Parent;
111-
while (currentParent != null)
112-
{
113-
if (currentParent.IsKind(SyntaxKind.ImplicitElementAccess))
114-
{
115-
return true;
116-
}
117-
118-
currentParent = currentParent.Parent;
119-
}
120-
121-
return false;
110+
return token.Parent.IsKind(SyntaxKind.BracketedArgumentList)
111+
&& token.Parent.Parent.IsKind(SyntaxKind.ImplicitElementAccess);
122112
}
123113
}
124114
}

0 commit comments

Comments
 (0)