예제 #1
0
        private static Task <Document> RefactorAsync(
            Document document,
            ExpressionSyntax expression,
            SyntaxList <StatementSyntax> statements,
            StatementContainer container,
            int statementIndex,
            int lastStatementIndex,
            CancellationToken cancellationToken)
        {
            IEnumerable <StatementSyntax> blockStatements = statements
                                                            .Skip(statementIndex + 1)
                                                            .Take(lastStatementIndex - statementIndex);

            IfStatementSyntax ifStatement = CreateNullCheck(expression, List(blockStatements));

            if (lastStatementIndex < statements.Count - 1)
            {
                ifStatement = ifStatement.AppendToTrailingTrivia(NewLine());
            }

            IEnumerable <StatementSyntax> newStatements = statements.Take(statementIndex + 1)
                                                          .Concat(new IfStatementSyntax[] { ifStatement })
                                                          .Concat(statements.Skip(lastStatementIndex + 1));

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
예제 #2
0
        public override async Task <Document> RefactorAsync(Document document, CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementContainer container = StatementContainer.Create(IfStatement);

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(IfStatement);

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            ExpressionSyntax expression = IfRefactoringHelper.GetBooleanExpression(
                IfStatement.Condition,
                Expression1,
                Expression2,
                semanticModel,
                cancellationToken);

            StatementSyntax newStatement = CreateStatement(expression)
                                           .WithLeadingTrivia(IfStatement.GetLeadingTrivia())
                                           .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia())
                                           .WithFormatterAnnotation();

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .RemoveAt(index)
                                                         .ReplaceAt(index, newStatement);

            return(await document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken).ConfigureAwait(false));
        }
        public static Task <Document> RefactorAsync(
            Document document,
            StatementContainer container,
            ImmutableArray <IfStatementSyntax> ifStatements,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            IfStatementSyntax newIfStatement = IfStatement(
                CreateCondition(ifStatements),
                Block(CreateStatements(ifStatements)));

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(ifStatements[0]);

            SyntaxList <StatementSyntax> newStatements = statements.Replace(
                ifStatements[0],
                newIfStatement
                .WithLeadingTrivia(ifStatements[0].GetLeadingTrivia())
                .WithTrailingTrivia(ifStatements[ifStatements.Length - 1].GetTrailingTrivia()));

            for (int i = 1; i < ifStatements.Length; i++)
            {
                newStatements = newStatements.RemoveAt(index + 1);
            }

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
예제 #4
0
        public static Task <Document> RefactorAsync(
            Document document,
            ObjectCreationExpressionSyntax objectCreation,
            StatementContainerSelection selectedStatements,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementContainer container = selectedStatements.Container;

            ExpressionStatementSyntax[] expressionStatements = selectedStatements
                                                               .Skip(1)
                                                               .Cast <ExpressionStatementSyntax>()
                                                               .ToArray();

            StatementSyntax firstStatement = selectedStatements.First();

            SyntaxList <StatementSyntax> newStatements = container.Statements.Replace(
                firstStatement,
                firstStatement.ReplaceNode(
                    objectCreation,
                    objectCreation.WithInitializer(CreateInitializer(objectCreation, expressionStatements))));

            int count = expressionStatements.Length;
            int index = selectedStatements.StartIndex + 1;

            while (count > 0)
            {
                newStatements = newStatements.RemoveAt(index);
                count--;
            }

            return(document.ReplaceNodeAsync(
                       container.Node,
                       container.NodeWithStatements(newStatements),
                       cancellationToken));
        }
예제 #5
0
        public static async Task <Document> RefactorAsync(
            Document document,
            StatementContainer container,
            IfStatementSyntax ifStatement,
            ReturnStatementSyntax returnStatement,
            CancellationToken cancellationToken)
        {
            ExpressionSyntax expression = ReplaceIfWithStatementRefactoring.GetExpression(
                ifStatement.Condition,
                ReplaceIfWithStatementRefactoring.GetReturnExpression(ifStatement),
                returnStatement.Expression);

            ReturnStatementSyntax newReturnStatement = ReturnStatement(expression);

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(ifStatement);

            newReturnStatement = newReturnStatement
                                 .WithLeadingTrivia(ifStatement.GetLeadingTrivia())
                                 .WithTrailingTrivia(returnStatement.GetTrailingTrivia())
                                 .WithFormatterAnnotation();

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .RemoveAt(index)
                                                         .ReplaceAt(index, newReturnStatement);

            return(await document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken).ConfigureAwait(false));
        }
예제 #6
0
        private static async Task <Document> RefactorAsync(
            Document document,
            StatementContainer container,
            IfStatementSyntax ifStatement,
            ReturnStatementSyntax returnStatement,
            ExpressionSyntax whenTrue,
            ExpressionSyntax whenFalse,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(ifStatement);

            ConditionalExpressionSyntax conditionalExpression = ReplaceIfWithStatementRefactoring.CreateConditionalExpression(ifStatement.Condition, whenTrue, whenFalse);

            ReturnStatementSyntax newReturnStatement = ReturnStatement(conditionalExpression)
                                                       .WithLeadingTrivia(ifStatement.GetLeadingTrivia())
                                                       .WithTrailingTrivia(returnStatement.GetTrailingTrivia())
                                                       .WithFormatterAnnotation();

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Remove(returnStatement)
                                                         .ReplaceAt(index, newReturnStatement);

            return(await document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken).ConfigureAwait(false));
        }
예제 #7
0
        private static Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            ReturnStatementSyntax returnStatement,
            StatementContainer container,
            CancellationToken cancellationToken)
        {
            SyntaxList <StatementSyntax> statements = container.Statements;

            IfStatement ifElse = IfStatement.Create(ifStatement);

            StatementSyntax statement = returnStatement;

            if (ifElse.Nodes.Any(f => f.Statement?.IsKind(SyntaxKind.Block) == true))
            {
                statement = SyntaxFactory.Block(statement);
            }

            ElseClauseSyntax elseClause = SyntaxFactory.ElseClause(statement).WithFormatterAnnotation();

            IfStatementSyntax lastIfStatement = ifElse.Nodes.Last();

            IfStatementSyntax newIfStatement = ifStatement.ReplaceNode(
                lastIfStatement,
                lastIfStatement.WithElse(elseClause));

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Replace(ifStatement, newIfStatement)
                                                         .RemoveAt(statements.IndexOf(returnStatement));

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
        private static Task <Document> RefactorAsync(
            Document document,
            StatementContainer statementContainer,
            StatementSyntax statement,
            InitializerExpressionSyntax initializer,
            ExpressionSyntax initializedExpression,
            CancellationToken cancellationToken)
        {
            ExpressionStatementSyntax[] expressions = CreateExpressionStatements(initializer, initializedExpression).ToArray();

            expressions[expressions.Length - 1] = expressions[expressions.Length - 1]
                                                  .WithTrailingTrivia(statement.GetTrailingTrivia());

            var objectCreationExpression = (ObjectCreationExpressionSyntax)initializer.Parent;

            ObjectCreationExpressionSyntax newObjectCreationExpression = objectCreationExpression.WithInitializer(null);

            if (newObjectCreationExpression.ArgumentList == null)
            {
                TypeSyntax type = newObjectCreationExpression.Type;

                newObjectCreationExpression = newObjectCreationExpression
                                              .WithArgumentList(ArgumentList().WithTrailingTrivia(type.GetTrailingTrivia()))
                                              .WithType(type.WithoutTrailingTrivia());
            }

            SyntaxList <StatementSyntax> statements = statementContainer.Statements;

            int index = statements.IndexOf(statement);

            StatementSyntax newStatement = statement.ReplaceNode(objectCreationExpression, newObjectCreationExpression);

            SyntaxKind statementKind = statement.Kind();

            if (statementKind == SyntaxKind.ExpressionStatement)
            {
                var expressionStatement = (ExpressionStatementSyntax)newStatement;

                newStatement = expressionStatement
                               .WithExpression(expressionStatement.Expression.WithoutTrailingTrivia());
            }
            else if (statementKind == SyntaxKind.LocalDeclarationStatement)
            {
                var localDeclaration = (LocalDeclarationStatementSyntax)newStatement;

                newStatement = localDeclaration
                               .WithDeclaration(localDeclaration.Declaration.WithoutTrailingTrivia());
            }

            SyntaxList <StatementSyntax> newStatements = statements.Replace(statement, newStatement);

            SyntaxNode newNode = statementContainer
                                 .NodeWithStatements(newStatements.InsertRange(index + 1, expressions))
                                 .WithFormatterAnnotation();

            return(document.ReplaceNodeAsync(statementContainer.Node, newNode, cancellationToken));
        }
예제 #9
0
        public static Task <Document> RefactorAsync(
            Document document,
            VariableDeclaratorSyntax declarator,
            CancellationToken cancellationToken)
        {
            var declaration = (VariableDeclarationSyntax)declarator.Parent;

            var localDeclaration = (LocalDeclarationStatementSyntax)declaration.Parent;

            StatementContainer container = StatementContainer.Create(localDeclaration);

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(localDeclaration);

            StatementSyntax nextStatement = statements[index + 1];

            var expressionStatement = (ExpressionStatementSyntax)nextStatement;

            var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;

            ExpressionSyntax right = assignment.Right;

            EqualsValueClauseSyntax initializer = declarator.Initializer;

            ExpressionSyntax value = initializer?.Value;

            VariableDeclaratorSyntax newDeclarator = (value != null)
                ? declarator.ReplaceNode(value, right)
                : declarator.WithInitializer(EqualsValueClause(right));

            LocalDeclarationStatementSyntax newLocalDeclaration = localDeclaration.ReplaceNode(declarator, newDeclarator);

            SyntaxTriviaList trailingTrivia = localDeclaration.GetTrailingTrivia();

            if (!trailingTrivia.IsEmptyOrWhitespace())
            {
                newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(trailingTrivia.Concat(nextStatement.GetTrailingTrivia()));
            }
            else
            {
                newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(nextStatement.GetTrailingTrivia());
            }

            SyntaxTriviaList leadingTrivia = nextStatement.GetLeadingTrivia();

            if (!leadingTrivia.IsEmptyOrWhitespace())
            {
                newLocalDeclaration = newLocalDeclaration.WithLeadingTrivia(newLocalDeclaration.GetLeadingTrivia().Concat(leadingTrivia));
            }

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Replace(localDeclaration, newLocalDeclaration)
                                                         .RemoveAt(index + 1);

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
예제 #10
0
        public override Task <Document> RefactorAsync(
            Document document,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementContainer container = StatementContainer.Create(IfStatement);

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(IfStatement);

            TStatement newStatement = CreateNewStatement();

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .RemoveAt(index)
                                                         .ReplaceAt(index - 1, newStatement);

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
        private static async Task <Document> RefactorAsync(
            Document document,
            StatementContainer statementContainer,
            StatementSyntax statement,
            InitializerExpressionSyntax initializer,
            ExpressionSyntax expression,
            CancellationToken cancellationToken)
        {
            ExpressionStatementSyntax[] expressions = Refactor(initializer, expression).ToArray();

            expressions[expressions.Length - 1] = expressions[expressions.Length - 1]
                                                  .WithTrailingTrivia(statement.GetTrailingTrivia());

            SyntaxList <StatementSyntax> statements = statementContainer.Statements;

            int index = statements.IndexOf(statement);

            StatementSyntax newStatement = statement.RemoveNode(initializer, SyntaxRemoveOptions.KeepNoTrivia);

            SyntaxKind statementKind = statement.Kind();

            if (statementKind == SyntaxKind.ExpressionStatement)
            {
                var expressionStatement = (ExpressionStatementSyntax)newStatement;

                newStatement = expressionStatement
                               .WithExpression(expressionStatement.Expression.WithoutTrailingTrivia());
            }
            else if (statementKind == SyntaxKind.LocalDeclarationStatement)
            {
                var localDeclaration = (LocalDeclarationStatementSyntax)newStatement;

                newStatement = localDeclaration
                               .WithDeclaration(localDeclaration.Declaration.WithoutTrailingTrivia());
            }

            SyntaxList <StatementSyntax> newStatements = statements.Replace(statement, newStatement);

            SyntaxNode newNode = statementContainer
                                 .NodeWithStatements(newStatements.InsertRange(index + 1, expressions))
                                 .WithFormatterAnnotation();

            return(await document.ReplaceNodeAsync(statementContainer.Node, newNode, cancellationToken).ConfigureAwait(false));
        }
예제 #12
0
            private SyntaxNode Rewrite(StatementContainer container, IfStatementSyntax ifStatement)
            {
                SyntaxList <StatementSyntax> statements = container.Statements;

                int index = statements.IndexOf(ifStatement);

                ExpressionSyntax newCondition = CSharpUtility.LogicallyNegate(ifStatement.Condition, _semanticModel, _cancellationToken);

                if (_recursive)
                {
                    ifStatement = (IfStatementSyntax)VisitIfStatement(ifStatement);
                }

                var block = (BlockSyntax)ifStatement.Statement;

                BlockSyntax newBlock = block.WithStatements(SingletonList(_jumpStatement));

                if (!block
                    .Statements
                    .First()
                    .GetLeadingTrivia()
                    .Any(f => f.IsEndOfLineTrivia()))
                {
                    newBlock = newBlock.WithCloseBraceToken(newBlock.CloseBraceToken.AppendToTrailingTrivia(NewLine()));
                }

                IfStatementSyntax newIfStatement = ifStatement
                                                   .WithCondition(newCondition)
                                                   .WithStatement(newBlock)
                                                   .WithFormatterAnnotation();

                if (statements.Last().Kind().IsJumpStatementOrYieldBreakStatement() &&
                    block.Statements.Last().Kind().IsJumpStatementOrYieldBreakStatement())
                {
                    statements = statements.RemoveAt(statements.Count - 1);
                }

                SyntaxList <StatementSyntax> newStatements = statements
                                                             .ReplaceAt(index, newIfStatement)
                                                             .InsertRange(index + 1, block.Statements.Select(f => f.WithFormatterAnnotation()));

                return(container.NodeWithStatements(newStatements));
            }
        private static SyntaxNode AddNextIf(
            StatementContainer container,
            IfStatementSyntax ifStatement,
            IfStatementSyntax newIfStatement,
            ExpressionSyntax expression)
        {
            IfStatementSyntax nextIfStatement = ifStatement.WithCondition(expression)
                                                .WithFormatterAnnotation();

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(ifStatement);

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Replace(ifStatement, newIfStatement)
                                                         .Insert(index + 1, nextIfStatement);

            return(container.NodeWithStatements(newStatements));
        }
예제 #14
0
        public async Task <Document> RefactorAsync(
            Document document,
            SelectedStatementsInfo info,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            StatementContainer container = info.Container;

            StatementSyntax[] statements = info.SelectedNodes().ToArray();

            int index = info.FirstSelectedNodeIndex;

            SyntaxTriviaList leadingTrivia  = statements[0].GetLeadingTrivia();
            SyntaxTriviaList trailingTrivia = statements[statements.Length - 1].GetTrailingTrivia();

            statements[0] = statements[0].WithLeadingTrivia();
            statements[statements.Length - 1] = statements[statements.Length - 1].WithTrailingTrivia();

            SyntaxList <StatementSyntax> newStatements = container.Statements;

            int cnt = statements.Length;

            while (cnt > 0)
            {
                newStatements = newStatements.RemoveAt(index);
                cnt--;
            }

            TStatement statement = CreateStatement(statements.ToImmutableArray());

            statement = statement
                        .WithLeadingTrivia(leadingTrivia)
                        .WithTrailingTrivia(trailingTrivia)
                        .WithFormatterAnnotation();

            newStatements = newStatements.Insert(index, statement);

            root = root.ReplaceNode(container.Node, container.NodeWithStatements(newStatements));

            return(document.WithSyntaxRoot(root));
        }
예제 #15
0
        private static Task <Document> RefactorAsync(
            Document document,
            StatementSyntax statement,
            IfStatementSyntax ifStatement,
            int statementIndex,
            StatementContainer container,
            ExpressionSyntax expression,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            var expressionStatement = (ExpressionStatementSyntax)ifStatement.GetSingleStatementOrDefault();

            var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;

            BinaryExpressionSyntax newNode = RefactoringHelper.CreateCoalesceExpression(
                semanticModel.GetTypeSymbol(assignment.Left, cancellationToken),
                expression.WithoutTrailingTrivia(),
                assignment.Right.WithTrailingTrivia(expression.GetTrailingTrivia()),
                statement.SpanStart,
                semanticModel);

            StatementSyntax newStatement = statement.ReplaceNode(expression, newNode);

            IEnumerable <SyntaxTrivia> trivia = container.Node.DescendantTrivia(TextSpan.FromBounds(statement.Span.End, ifStatement.Span.End));

            if (!trivia.All(f => f.IsWhitespaceOrEndOfLineTrivia()))
            {
                newStatement = newStatement.WithTrailingTrivia(trivia);
                newStatement = newStatement.AppendToTrailingTrivia(ifStatement.GetTrailingTrivia());
            }
            else
            {
                newStatement = newStatement.WithTrailingTrivia(ifStatement.GetTrailingTrivia());
            }

            SyntaxList <StatementSyntax> newStatements = container.Statements
                                                         .Remove(ifStatement)
                                                         .ReplaceAt(statementIndex, newStatement);

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
예제 #16
0
        public override Task <Document> RefactorAsync(Document document, CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementContainer container = StatementContainer.Create(IfStatement);

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(IfStatement);

            ConditionalExpressionSyntax conditionalExpression = IfRefactoringHelper.CreateConditionalExpression(IfStatement.Condition, Expression1, Expression2);

            StatementSyntax newStatement = CreateStatement(conditionalExpression)
                                           .WithLeadingTrivia(IfStatement.GetLeadingTrivia())
                                           .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia())
                                           .WithFormatterAnnotation();

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .RemoveAt(index)
                                                         .ReplaceAt(index, newStatement);

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
        private static async Task <Document> RefactorAsync(
            Document document,
            StatementSyntax statement,
            IfStatementSyntax ifStatement,
            int statementIndex,
            StatementContainer container,
            ExpressionSyntax expression,
            CancellationToken cancellationToken)
        {
            var expressionStatement = (ExpressionStatementSyntax)GetSingleStatementOrDefault(ifStatement.Statement);

            var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;

            ExpressionSyntax right = assignment.Right;

            BinaryExpressionSyntax newNode = CoalesceExpression(
                expression.WithoutTrailingTrivia(),
                right.WithTrailingTrivia(expression.GetTrailingTrivia()));

            StatementSyntax newStatement = statement.ReplaceNode(expression, newNode);

            IEnumerable <SyntaxTrivia> trivia = container.Node.DescendantTrivia(TextSpan.FromBounds(statement.Span.End, ifStatement.Span.End));

            if (!trivia.All(f => f.IsWhitespaceOrEndOfLineTrivia()))
            {
                newStatement = newStatement.WithTrailingTrivia(trivia);
                newStatement = newStatement.AppendToTrailingTrivia(ifStatement.GetTrailingTrivia());
            }
            else
            {
                newStatement = newStatement.WithTrailingTrivia(ifStatement.GetTrailingTrivia());
            }

            SyntaxList <StatementSyntax> newStatements = container.Statements
                                                         .Remove(ifStatement)
                                                         .ReplaceAt(statementIndex, newStatement);

            return(await document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken).ConfigureAwait(false));
        }
        private static Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            ConditionalExpressionSyntax conditionalExpression,
            SemanticModel semanticModel,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            VariableDeclaratorSyntax variableDeclarator = localDeclaration.Declaration.Variables[0];

            LocalDeclarationStatementSyntax newLocalDeclaration = localDeclaration.RemoveNode(variableDeclarator.Initializer, SyntaxRemoveOptions.KeepExteriorTrivia);

            TypeSyntax type = newLocalDeclaration.Declaration.Type;

            if (type.IsVar)
            {
                newLocalDeclaration = newLocalDeclaration.ReplaceNode(
                    type,
                    semanticModel.GetTypeSymbol(conditionalExpression)
                    .ToMinimalTypeSyntax(semanticModel, type.SpanStart)
                    .WithTriviaFrom(type));
            }

            IdentifierNameSyntax left = IdentifierName(variableDeclarator.Identifier.ValueText);

            IfStatementSyntax ifStatement = IfElseStatement(
                conditionalExpression.Condition.WalkDownParentheses().WithoutTrivia(),
                SimpleAssignmentStatement(left, conditionalExpression.WhenTrue.WithoutTrivia()),
                SimpleAssignmentStatement(left, conditionalExpression.WhenFalse.WithoutTrivia()));

            StatementContainer container = StatementContainer.Create(localDeclaration);

            SyntaxList <StatementSyntax> statements = container.Statements;

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Replace(localDeclaration, newLocalDeclaration.WithFormatterAnnotation())
                                                         .Insert(statements.IndexOf(localDeclaration) + 1, ifStatement.WithFormatterAnnotation());

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            ObjectCreationExpressionSyntax objectCreation,
            SelectedStatementsInfo info,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            StatementContainer container = info.Container;

            ExpressionStatementSyntax[] expressionStatements = info
                                                               .SelectedNodes()
                                                               .Skip(1)
                                                               .Cast <ExpressionStatementSyntax>()
                                                               .ToArray();

            StatementSyntax firstNode = info.FirstSelectedNode;

            SyntaxList <StatementSyntax> newStatements = container.Statements.Replace(
                firstNode,
                firstNode.ReplaceNode(
                    objectCreation,
                    objectCreation.WithInitializer(CreateInitializer(objectCreation, expressionStatements))));

            int count = expressionStatements.Length;
            int index = info.FirstSelectedNodeIndex + 1;

            while (count > 0)
            {
                newStatements = newStatements.RemoveAt(index);
                count--;
            }

            SyntaxNode newRoot = root.ReplaceNode(
                container.Node,
                container.NodeWithStatements(newStatements));

            return(document.WithSyntaxRoot(newRoot));
        }
예제 #20
0
        public static Task <Document> InlineLazyInitializationAsync(
            Document document,
            IfStatementSyntax ifStatement,
            CancellationToken cancellationToken)
        {
            StatementContainer container = StatementContainer.Create(ifStatement);

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(ifStatement);

            StatementSyntax expressionStatement = (ExpressionStatementSyntax)statements[index + 1];

            MemberInvocationStatement invocation = MemberInvocationStatement.Create((ExpressionStatementSyntax)expressionStatement);

            ExpressionSyntax expression = invocation.Expression;

            SimpleAssignmentStatement assignment = SimpleAssignmentStatement.Create((ExpressionStatementSyntax)ifStatement.GetSingleStatementOrDefault());

            BinaryExpressionSyntax coalesceExpression = CSharpFactory.CoalesceExpression(expression.WithoutTrivia(), ParenthesizedExpression(assignment.AssignmentExpression));

            ParenthesizedExpressionSyntax newExpression = ParenthesizedExpression(coalesceExpression)
                                                          .WithTriviaFrom(expression);

            StatementSyntax newExpressionStatement = expressionStatement.ReplaceNode(expression, newExpression);

            IEnumerable <SyntaxTrivia> trivia = container.Node.DescendantTrivia(TextSpan.FromBounds(ifStatement.FullSpan.Start, expressionStatement.FullSpan.Start));

            if (trivia.Any(f => !f.IsWhitespaceOrEndOfLineTrivia()))
            {
                newExpressionStatement = newExpressionStatement.PrependToLeadingTrivia(trivia);
            }

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Replace(expressionStatement, newExpressionStatement)
                                                         .RemoveAt(index);

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken)
        {
            StatementContainer container = StatementContainer.Create(localDeclaration);

            int index = container.Statements.IndexOf(localDeclaration);

            StatementSyntax nextStatement = container.Statements[index + 1];

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            ExpressionSyntax value = GetExpressionToInline(localDeclaration, semanticModel, cancellationToken);

            StatementSyntax newStatement = GetStatementWithInlinedExpression(nextStatement, value);

            SyntaxTriviaList leadingTrivia = localDeclaration.GetLeadingTrivia();

            IEnumerable <SyntaxTrivia> trivia = container
                                                .Node
                                                .DescendantTrivia(TextSpan.FromBounds(localDeclaration.SpanStart, nextStatement.Span.Start));

            if (!trivia.All(f => f.IsWhitespaceOrEndOfLineTrivia()))
            {
                newStatement = newStatement.WithLeadingTrivia(leadingTrivia.Concat(trivia));
            }
            else
            {
                newStatement = newStatement.WithLeadingTrivia(leadingTrivia);
            }

            SyntaxList <StatementSyntax> newStatements = container.Statements
                                                         .Replace(nextStatement, newStatement)
                                                         .RemoveAt(index);

            return(await document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken).ConfigureAwait(false));
        }
        public Task <Document> RefactorAsync(
            Document document,
            StatementContainerSelection selectedStatements,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementContainer container = selectedStatements.Container;

            StatementSyntax[] statements = selectedStatements.ToArray();

            int index = selectedStatements.StartIndex;

            SyntaxTriviaList leadingTrivia  = statements[0].GetLeadingTrivia();
            SyntaxTriviaList trailingTrivia = statements[statements.Length - 1].GetTrailingTrivia();

            statements[0] = statements[0].WithLeadingTrivia();
            statements[statements.Length - 1] = statements[statements.Length - 1].WithTrailingTrivia();

            SyntaxList <StatementSyntax> newStatements = container.Statements;

            int cnt = statements.Length;

            while (cnt > 0)
            {
                newStatements = newStatements.RemoveAt(index);
                cnt--;
            }

            TStatement statement = CreateStatement(statements.ToImmutableArray());

            statement = statement
                        .WithLeadingTrivia(leadingTrivia)
                        .WithTrailingTrivia(trailingTrivia)
                        .WithFormatterAnnotation();

            newStatements = newStatements.Insert(index, statement);

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
예제 #23
0
        private static async Task <Document> RefactorAsync(
            Document document,
            StatementContainer container,
            LocalDeclarationStatementSyntax[] localDeclarations,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            LocalDeclarationStatementSyntax localDeclaration = localDeclarations[0];

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(localDeclaration);

            VariableDeclaratorSyntax[] variables = localDeclarations
                                                   .Skip(1)
                                                   .Select(f => f.Declaration)
                                                   .SelectMany(f => f.Variables)
                                                   .ToArray();

            LocalDeclarationStatementSyntax newLocalDeclaration = localDeclaration
                                                                  .AddDeclarationVariables(variables)
                                                                  .WithTrailingTrivia(localDeclarations[localDeclarations.Length - 1].GetTrailingTrivia())
                                                                  .WithFormatterAnnotation();

            SyntaxList <StatementSyntax> newStatements = statements.Replace(
                localDeclaration,
                newLocalDeclaration);

            for (int i = 1; i < localDeclarations.Length; i++)
            {
                newStatements = newStatements.RemoveAt(index + 1);
            }

            SyntaxNode newRoot = root.ReplaceNode(container.Node, container.NodeWithStatements(newStatements));

            return(document.WithSyntaxRoot(newRoot));
        }
        private static Task <Document> RefactorAsync <TNode>(
            Document document,
            WhileStatementSyntax whileStatement,
            ForStatementSyntax forStatement,
            List <TNode> list,
            CancellationToken cancellationToken) where TNode : StatementSyntax
        {
            forStatement = forStatement
                           .TrimLeadingTrivia()
                           .PrependToLeadingTrivia(list[0].GetLeadingTrivia());

            StatementContainer container = StatementContainer.Create(whileStatement);

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(list[0]);

            IEnumerable <StatementSyntax> newStatements = statements.Take(index)
                                                          .Concat(new ForStatementSyntax[] { forStatement })
                                                          .Concat(statements.Skip(index + list.Count + 1));

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            ExpressionStatementSyntax expressionStatement,
            CancellationToken cancellationToken)
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            INamedTypeSymbol symbol = semanticModel.GetTypeByMetadataName(MetadataNames.System_Text_StringBuilder);

            var invocationExpression = (InvocationExpressionSyntax)expressionStatement.Expression;

            MemberInvocationExpression memberInvocation = MemberInvocationExpression.Create(invocationExpression);

            ExpressionSyntax expression = GetFirstInvocationInMethodChain(memberInvocation, symbol, semanticModel, cancellationToken).Expression;

            StatementContainer statementContainer = StatementContainer.Create(expressionStatement);

            SyntaxList <StatementSyntax> statements = statementContainer.Statements;

            int index = statements.IndexOf(expressionStatement);

            string indentation = CSharpFormatter.GetIncreasedIndentation(expressionStatement, cancellationToken).ToString();

            var sb = new StringBuilder(invocationExpression.ToString());

            int j = index;

            while (j < statements.Count - 1)
            {
                StatementSyntax statement = statements[j + 1];

                if (!IsFixable(statement, expression, symbol, semanticModel, cancellationToken))
                {
                    break;
                }

                sb.AppendLine();
                sb.Append(indentation);
                sb.Append(GetTextToAppend((ExpressionStatementSyntax)statement, symbol, semanticModel, cancellationToken));

                j++;
            }

            StatementSyntax lastStatement = statements[j];

            SyntaxList <StatementSyntax> newStatements = statements;

            while (j > index)
            {
                newStatements = newStatements.RemoveAt(j);
                j--;
            }

            ExpressionSyntax newInvocationExpression = SyntaxFactory.ParseExpression(sb.ToString());

            SyntaxTriviaList trailingTrivia = statementContainer
                                              .Node
                                              .DescendantTrivia(TextSpan.FromBounds(invocationExpression.Span.End, lastStatement.Span.End))
                                              .ToSyntaxTriviaList()
                                              .EmptyIfWhitespace()
                                              .AddRange(lastStatement.GetTrailingTrivia());

            ExpressionStatementSyntax newExpressionStatement = expressionStatement
                                                               .WithExpression(newInvocationExpression)
                                                               .WithLeadingTrivia(expressionStatement.GetLeadingTrivia())
                                                               .WithTrailingTrivia(trailingTrivia)
                                                               .WithFormatterAndSimplifierAnnotations();

            newStatements = newStatements.ReplaceAt(index, newExpressionStatement);

            return(await document.ReplaceNodeAsync(statementContainer.Node, statementContainer.NodeWithStatements(newStatements), cancellationToken).ConfigureAwait(false));
        }