Skip to content

Commit

Permalink
Minor refactor in ThreadAbortCodeFixProvider (#6673)
Browse files Browse the repository at this point in the history
## Summary of changes

Don't re-do work in code fix

## Reason for change

Was looking at something else, and noticed that this was doing more work
than necessary

## Implementation details

The diagnostic is already located at the "problematic" catch, so we
don't need to try finding it _again_ in the code fix

## Test coverage

There are existing unit tests for this, and they all pass, so :shipit:
  • Loading branch information
andrewlock authored Feb 17, 2025
1 parent 7d24b3d commit d2ae16e
Showing 1 changed file with 4 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,26 +45,22 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
var diagnosticSpan = diagnostic.Location.SourceSpan;

// Find the while block catch declaration identified by the diagnostic.
var whileStatement = root.FindToken(diagnosticSpan.Start)
var catchClause = root.FindToken(diagnosticSpan.Start)
.Parent
.AncestorsAndSelf()
.OfType<WhileStatementSyntax>().First();
.OfType<CatchClauseSyntax>().First();

// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title: "Rethrow exception",
createChangedDocument: c => AddThrowStatement(context.Document, whileStatement, c),
createChangedDocument: c => AddThrowStatement(context.Document, catchClause, c),
equivalenceKey: nameof(ThreadAbortCodeFixProvider)),
diagnostic);
}

private async Task<Document> AddThrowStatement(Document document, WhileStatementSyntax whileStatement, CancellationToken cancellationToken)
private static async Task<Document> AddThrowStatement(Document document, CatchClauseSyntax catchBlock, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

var catchBlock = ThreadAbortSyntaxHelper.FindProblematicCatchClause(whileStatement, semanticModel);

// This messes with the whitespace, but it's a PITA to get that right
var throwStatement = SyntaxFactory.ThrowStatement();
var statements = catchBlock.Block.Statements.Add(throwStatement);
Expand Down

0 comments on commit d2ae16e

Please sign in to comment.