public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); IfStatementSyntax ifStatement = root .FindNode(context.Span, getInnermostNodeForTie: true)? .FirstAncestorOrSelf <IfStatementSyntax>(); if (ifStatement == null) { return; } foreach (Diagnostic diagnostic in context.Diagnostics) { switch (diagnostic.Id) { case DiagnosticIdentifiers.MergeIfStatementWithNestedIfStatement: { CodeAction codeAction = CodeAction.Create( "Merge if with nested if", cancellationToken => { return(MergeIfStatementWithNestedIfStatementAsync( context.Document, ifStatement, cancellationToken)); }, diagnostic.Id + EquivalenceKeySuffix); context.RegisterCodeFix(codeAction, diagnostic); break; } case DiagnosticIdentifiers.SimplifyIfElseStatement: { CodeAction codeAction = CodeAction.Create( "Simplify if-else", cancellationToken => { return(SimplifyIfElseStatementRefactoring.RefactorAsync( context.Document, ifStatement, cancellationToken)); }, diagnostic.Id + EquivalenceKeySuffix); context.RegisterCodeFix(codeAction, diagnostic); break; } } } }
private void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) { if (GeneratedCodeAnalyzer?.IsGeneratedCode(context) == true) { return; } if (context.Node.Parent?.IsKind(SyntaxKind.ElseClause) == true) { return; } var ifStatement = (IfStatementSyntax)context.Node; if (ifStatement.Else != null) { var result = new IfElseAnalysisResult(ifStatement); if (result.AddBraces) { context.ReportDiagnostic( DiagnosticDescriptors.AddBracesToIfElse, ifStatement.GetLocation()); } if (result.RemoveBraces) { context.ReportDiagnostic( DiagnosticDescriptors.RemoveBracesFromIfElse, ifStatement.GetLocation()); RemoveBracesFromIfElseFadeOut(context, ifStatement); } } MergeIfStatementWithNestedIfStatementAnalyzer.Analyze(context, ifStatement); SimplifyIfStatementToReturnStatementAnalyzer.Analyze(context); if (SimplifyIfElseStatementRefactoring.CanRefactor(ifStatement, context.SemanticModel, context.CancellationToken) && !ifStatement.SpanContainsDirectives()) { context.ReportDiagnostic( DiagnosticDescriptors.SimplifyIfElseStatement, ifStatement.GetLocation()); } }