Skip to content

Commit 3332660

Browse files
committed
Fix #1878 (SA1133CodeFixProvider crash with System.InvalidCastException)
1 parent f25bde0 commit 3332660

2 files changed

Lines changed: 15 additions & 4 deletions

File tree

StyleCop.Analyzers/StyleCop.Analyzers.CodeFixes/ReadabilityRules/SA1133CodeFixProvider.cs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,18 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context)
5151
private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
5252
{
5353
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
54-
var violatingAttribute = (AttributeSyntax)syntaxRoot.FindNode(diagnostic.Location.SourceSpan).Parent;
55-
var attributeList = (AttributeListSyntax)violatingAttribute.Parent;
54+
var nodeInSourceSpan = syntaxRoot.FindNode(diagnostic.Location.SourceSpan);
55+
AttributeListSyntax attributeList;
56+
if (nodeInSourceSpan.Parent is AttributeListSyntax)
57+
{
58+
attributeList = (AttributeListSyntax)nodeInSourceSpan.Parent;
59+
}
60+
else
61+
{
62+
var violatingAttribute = (AttributeSyntax)nodeInSourceSpan.Parent;
63+
attributeList = (AttributeListSyntax)violatingAttribute.Parent;
64+
}
65+
5666
var newAttributeLists = new List<AttributeListSyntax>();
5767

5868
var indentationOptions = IndentationOptions.FromDocument(document);

StyleCop.Analyzers/StyleCop.Analyzers.Test/ReadabilityRules/SA1133UnitTests.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -166,11 +166,12 @@ public void TestMethod()
166166
}
167167

168168
/// <summary>
169-
/// Repro test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1878.
169+
/// Regression test for issue 1878 (SA1133CodeFixProvider crash), https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1878
170+
/// Fixing exception "Unable to cast object of type 'Microsoft.CodeAnalysis.CSharp.Syntax.AttributeListSyntax' to type 'Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax'."
170171
/// </summary>
171172
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
172173
[Fact]
173-
public async Task ReproFor1878Async()
174+
public async Task TestRegressionIssue1878Async()
174175
{
175176
var testCode = @"namespace Stylecop_rc1_bug_repro
176177
{

0 commit comments

Comments
 (0)