Skip to content

Commit

Permalink
Merge pull request #2896 from vweijsters/fix-2894
Browse files Browse the repository at this point in the history
Fixed crash in SA1134 code fix
  • Loading branch information
sharwell authored Feb 19, 2019
2 parents a0971c9 + 1148a55 commit 38872b5
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,23 @@ public override FixAllProvider GetFixAllProvider()
}

/// <inheritdoc/>
public override Task RegisterCodeFixesAsync(CodeFixContext context)
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var syntaxRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(
CodeAction.Create(
ReadabilityResources.SA1134CodeFix,
cancellationToken => GetTransformedDocumentAsync(context.Document, diagnostic, cancellationToken),
nameof(SA1134CodeFixProvider)),
diagnostic);
// Do not offer the code fix if the error is found at an invalid node (like IncompleteMemberSyntax)
if (syntaxRoot.FindNode(diagnostic.Location.SourceSpan) is AttributeListSyntax)
{
context.RegisterCodeFix(
CodeAction.Create(
ReadabilityResources.SA1134CodeFix,
cancellationToken => GetTransformedDocumentAsync(context.Document, diagnostic, cancellationToken),
nameof(SA1134CodeFixProvider)),
diagnostic);
}
}

return SpecializedTasks.CompletedTask;
}

private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -409,5 +409,35 @@ public class TestClass<[Test(""Test1"")][Test(""Test2"")]T>

await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}

/// <summary>
/// Verifies that passing an invalid member syntax into the codefix will not change the code.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(2894, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2894")]
public async Task VerifyInvalidMemberSyntaxInCodeFixAsync()
{
string testCode = @"class Program
{
static void Main(string[] args)
{
{
}[;]
}
}
";

DiagnosticResult[] expected =
{
DiagnosticResult.CompilerError("CS1513").WithLocation(6, 10),
Diagnostic().WithLocation(6, 10),
DiagnosticResult.CompilerError("CS1001").WithLocation(6, 11),
DiagnosticResult.CompilerError("CS1001").WithLocation(6, 11),
DiagnosticResult.CompilerError("CS1022").WithLocation(8, 1),
};

await VerifyCSharpFixAsync(testCode, expected, testCode, CancellationToken.None).ConfigureAwait(false);
}
}
}

0 comments on commit 38872b5

Please sign in to comment.