Skip to content

Commit 967a6cd

Browse files
committed
SA1010 now properly supports index initializers
1 parent bbd6bba commit 967a6cd

2 files changed

Lines changed: 39 additions & 1 deletion

File tree

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,28 @@ public int this [ [CLSCompliant(true)]int index]
161161
await this.VerifyCSharpFixAsync(testCode, ExpectedCode).ConfigureAwait(false);
162162
}
163163

164+
/// <summary>
165+
/// Verify that index initializers are properly handled.
166+
/// Regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1617
167+
/// </summary>
168+
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
169+
[Fact]
170+
public async Task VerifyIndexInitializerAsync()
171+
{
172+
var testCode = @"using System.Collections.Generic;
173+
174+
public class TestClass
175+
{
176+
public void TestMethod(IDictionary<ulong, string> items)
177+
{
178+
var test = new Dictionary<ulong, string>(items) { [100] = ""100"" };
179+
}
180+
}
181+
";
182+
183+
await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
184+
}
185+
164186
/// <inheritdoc/>
165187
protected override IEnumerable<DiagnosticAnalyzer> GetCSharpDiagnosticAnalyzers()
166188
{

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

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ private static void HandleOpenBracketToken(SyntaxTreeAnalysisContext context, Sy
9292
bool followedBySpace = token.IsFollowedByWhitespace();
9393
bool lastInLine = token.IsLastInLine();
9494

95-
if (!firstInLine && precededBySpace && !ignorePrecedingSpaceProblem)
95+
if (!firstInLine && precededBySpace && !ignorePrecedingSpaceProblem && !IsPartOfIndexInitializer(token))
9696
{
9797
// Opening square bracket must {not be preceded} by a space.
9898
context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), TokenSpacingCodeFixProvider.RemovePreceding, "not be preceded"));
@@ -104,5 +104,21 @@ private static void HandleOpenBracketToken(SyntaxTreeAnalysisContext context, Sy
104104
context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), TokenSpacingCodeFixProvider.RemoveFollowing, "not be followed"));
105105
}
106106
}
107+
108+
private static bool IsPartOfIndexInitializer(SyntaxToken token)
109+
{
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;
122+
}
107123
}
108124
}

0 commit comments

Comments
 (0)