|
| 1 | +using System.Collections.Immutable; |
| 2 | +using System.Composition; |
| 3 | +using System.Linq; |
| 4 | +using System.Threading.Tasks; |
| 5 | +using Microsoft.CodeAnalysis; |
| 6 | +using Microsoft.CodeAnalysis.CodeActions; |
| 7 | +using Microsoft.CodeAnalysis.CodeFixes; |
| 8 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 9 | + |
| 10 | +namespace ProgressOnderwijsUtils.Analyzers; |
| 11 | + |
| 12 | +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(RedundantAssertNotNullCodeFix))] |
| 13 | +[Shared] |
| 14 | +public sealed class IfNotFalseCodeFix : CodeFixProvider |
| 15 | +{ |
| 16 | + public override ImmutableArray<string> FixableDiagnosticIds |
| 17 | + => [IfNotFalseAnalyzer.Rule.Id,]; |
| 18 | + |
| 19 | + public override FixAllProvider GetFixAllProvider() |
| 20 | + => WellKnownFixAllProviders.BatchFixer; |
| 21 | + |
| 22 | + public override async Task RegisterCodeFixesAsync(CodeFixContext context) |
| 23 | + { |
| 24 | + const string title = "Remove redundant if statement"; |
| 25 | + var diagnostic = context.Diagnostics.First(); |
| 26 | + var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); |
| 27 | + if (root is null) { |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + var ifStatement = root.FindNode(diagnostic.Location.SourceSpan).FirstAncestorOrSelf<IfStatementSyntax>(); |
| 32 | + if (ifStatement is null) { |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + var newRoot = ifStatement.Statement is BlockSyntax { Statements.Count: > 0, } block |
| 37 | + ? ReplaceWithBlockStatements(root, ifStatement, block) |
| 38 | + : root.RemoveNode(ifStatement, SyntaxRemoveOptions.KeepNoTrivia); |
| 39 | + |
| 40 | + if (newRoot is null) { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + context.RegisterCodeFix( |
| 45 | + CodeAction.Create( |
| 46 | + title, |
| 47 | + _ => Task.FromResult(context.Document.WithSyntaxRoot(newRoot)), |
| 48 | + title |
| 49 | + ), |
| 50 | + diagnostic |
| 51 | + ); |
| 52 | + } |
| 53 | + |
| 54 | + private static SyntaxNode ReplaceWithBlockStatements(SyntaxNode root, IfStatementSyntax ifStatement, BlockSyntax block) |
| 55 | + { |
| 56 | + var statements = block.Statements; |
| 57 | + var firstStatement = statements[0] |
| 58 | + .WithLeadingTrivia(ifStatement.GetLeadingTrivia()) |
| 59 | + .WithTrailingTrivia(block.GetTrailingTrivia()); |
| 60 | + |
| 61 | + var newStatements = statements.Replace(statements[0], firstStatement); |
| 62 | + |
| 63 | + return root.ReplaceNode(ifStatement, newStatements); |
| 64 | + } |
| 65 | +} |
0 commit comments