private static SyntaxNode GetContainingBlock(SyntaxNode node)
 {
     if (node.IsKind(SyntaxKind.ElseClause))
     {
         return(IfElseChainAnalysis.GetTopmostIf((ElseClauseSyntax)node)?.Parent);
     }
     else
     {
         return(node.Parent);
     }
 }
        private static SyntaxNode GetNewRoot(StatementSyntax statement, SyntaxNode oldRoot, IEnumerable <StatementSyntax> newNodes)
        {
            if (statement.Parent.IsKind(SyntaxKind.ElseClause))
            {
                IfStatementSyntax ifStatement = IfElseChainAnalysis.GetTopmostIf((ElseClauseSyntax)statement.Parent);
                var block = (BlockSyntax)ifStatement.Parent;
                int index = block.Statements.IndexOf(ifStatement);

                BlockSyntax newBlock = block.RemoveNode(statement.Parent, SyntaxRemoveOptions.KeepNoTrivia);

                newBlock = newBlock.WithStatements(newBlock.Statements.InsertRange(index + 1, newNodes));

                return(oldRoot.ReplaceNode(block, newBlock));
            }
            else
            {
                return(oldRoot.ReplaceNode(statement.Parent, newNodes));
            }
        }
Exemple #3
0
        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;
            }

            ifStatement = IfElseChainAnalysis.GetTopmostIf(ifStatement);

            CodeAction codeAction = CodeAction.Create(
                "Add braces to if-else chain",
                cancellationToken => AddBracesToIfElseChainRefactoring.RefactorAsync(context.Document, ifStatement, cancellationToken),
                DiagnosticIdentifiers.AddBracesToIfElseChain + EquivalenceKeySuffix);

            context.RegisterCodeFix(codeAction, context.Diagnostics);
        }