Esempio n. 1
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));
        }
Esempio n. 3
0
        private static Task <Document> IfReturnToReturnWithBooleanExpressionAsync(
            Document document,
            IfReturnToReturnWithBooleanExpressionAnalysis analysis,
            CancellationToken cancellationToken = default)
        {
            StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(analysis.IfStatement);

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(analysis.IfStatement);

            ExpressionSyntax expression = GetBooleanExpression(
                analysis.IfStatement.Condition,
                analysis.Expression1,
                analysis.Expression2,
                analysis.SemanticModel,
                cancellationToken);

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

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

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
Esempio n. 4
0
        public static Task <Document> RefactorAsync(
            Document document,
            StatementListSelection selectedStatements,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ImmutableArray <IfStatementSyntax> ifStatements = selectedStatements.Cast <IfStatementSyntax>().ToImmutableArray();

            IfStatementSyntax newIfStatement = IfStatement(
                BinaryExpression(SyntaxKind.LogicalOrExpression, ifStatements.Select(f => f.Condition)),
                Block(CreateStatements(ifStatements)));

            SyntaxList <StatementSyntax> statements = selectedStatements.UnderlyingList;

            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.ReplaceStatementsAsync(SyntaxInfo.StatementListInfo(selectedStatements), newStatements, cancellationToken));
        }
Esempio n. 5
0
        public override async Task <Document> RefactorAsync(Document document, CancellationToken cancellationToken)
        {
            IStatementContainer container = StatementContainer.Create(IfStatement);

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(IfStatement);

            ExpressionSyntax left  = Left.WithoutTrivia();
            ExpressionSyntax right = Right.WithoutTrivia();

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

            right = AddCastExpressionIfNecessary(right, semanticModel, IfStatement.SpanStart, cancellationToken);

            StatementSyntax newNode = CreateStatement(
                CoalesceExpression(
                    left.Parenthesize().WithSimplifierAnnotation(),
                    right.Parenthesize().WithSimplifierAnnotation()));

            newNode = newNode
                      .WithLeadingTrivia(IfStatement.GetLeadingTrivia())
                      .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia())
                      .WithFormatterAnnotation();

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

            return(await document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken).ConfigureAwait(false));
        }
        private static async Task <Document> RefactorAsync(
            Document document,
            MemberDeclarationSyntax member,
            AttributeListSyntax[] attributeLists,
            CancellationToken cancellationToken)
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken);

            SyntaxList <AttributeListSyntax> lists = member.GetAttributeLists();

            int index = lists.IndexOf(attributeLists[0]);

            for (int i = attributeLists.Length - 1; i >= 1; i--)
            {
                lists = lists.RemoveAt(index);
            }

            AttributeListSyntax list = AttributeRefactoring.MergeAttributes(attributeLists)
                                       .WithAdditionalAnnotations(Formatter.Annotation);

            lists = lists.Replace(lists[index], list);

            root = root.ReplaceNode(member, member.SetAttributeLists(lists));

            return(document.WithSyntaxRoot(root));
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken)
        {
            var block = (BlockSyntax)localDeclaration.Parent;

            SyntaxList <StatementSyntax> statements = block.Statements;

            int index = statements.IndexOf(localDeclaration);

            var returnStatement = (ReturnStatementSyntax)statements[index + 1];

            ReturnStatementSyntax newReturnStatement = returnStatement
                                                       .WithExpression(localDeclaration.Declaration.Variables[0].Initializer.Value.WithoutTrivia())
                                                       .WithLeadingTrivia(localDeclaration.GetLeadingTrivia())
                                                       .WithTrailingTrivia(returnStatement.GetTrailingTrivia())
                                                       .WithFormatterAnnotation();

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

            BlockSyntax newBlock = block.WithStatements(newStatements);

            return(await document.ReplaceNodeAsync(block, newBlock, cancellationToken).ConfigureAwait(false));
        }
        public static Task <Document> RefactorAsync(
            Document document,
            ObjectCreationExpressionSyntax objectCreation,
            StatementsSelection selectedStatements,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementsInfo statementsInfo = selectedStatements.Info;

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

            StatementSyntax firstStatement = selectedStatements.First();

            SyntaxList <StatementSyntax> newStatements = statementsInfo.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.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            ObjectCreationExpressionSyntax objectCreation,
            SelectedStatementCollection selectedStatements,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementContainer container = selectedStatements.Container;

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

            StatementSyntax firstNode = selectedStatements.First;

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

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

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

            return(await document.ReplaceNodeAsync(
                       container.Node,
                       container.NodeWithStatements(newStatements),
                       cancellationToken).ConfigureAwait(false));
        }
Esempio n. 10
0
        public static async Task <Document> RefactorAsync(
            Document document,
            ExpressionStatementSyntax statement,
            ReturnStatementSyntax returnStatement,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var block = (BlockSyntax)statement.Parent;

            SyntaxList <StatementSyntax> statements = block.Statements;

            int index = statements.IndexOf(statement);

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

            var assignmentExpression = (AssignmentExpressionSyntax)statement.Expression;

            ReturnStatementSyntax newReturnStatement = returnStatement
                                                       .WithExpression(assignmentExpression.Right)
                                                       .WithLeadingTrivia(assignmentExpression.GetLeadingTrivia())
                                                       .WithTrailingTrivia(returnStatement.GetTrailingTrivia())
                                                       .WithFormatterAnnotation();

            newStatements = newStatements.Replace(newStatements[index], newReturnStatement);

            root = root.ReplaceNode(block, block.WithStatements(newStatements));

            return(document.WithSyntaxRoot(root));
        }
Esempio n. 11
0
        public static Task <Document> RefactorAsync(
            Document document,
            AssignmentExpressionSyntax assignmentExpression,
            CancellationToken cancellationToken)
        {
            var statement = (StatementSyntax)assignmentExpression.Parent;

            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(statement);

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(statement);

            statements = statements.RemoveAt(index);

            var returnStatement = (ReturnStatementSyntax)statement.NextStatementOrDefault();

            IEnumerable <SyntaxTrivia> trivia = statementsInfo
                                                .Node
                                                .DescendantTrivia(TextSpan.FromBounds(statement.SpanStart, returnStatement.SpanStart))
                                                .Where(f => !f.IsWhitespaceOrEndOfLineTrivia());

            trivia = statement
                     .GetLeadingTrivia()
                     .Concat(trivia);

            returnStatement = returnStatement
                              .WithExpression(assignmentExpression.Right.WithTriviaFrom(returnStatement.Expression))
                              .WithLeadingTrivia(trivia);

            statements = statements.ReplaceAt(index, returnStatement);

            return(document.ReplaceStatementsAsync(statementsInfo, statements, cancellationToken));
        }
        private static Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            StatementListSelection selectedStatements,
            CancellationToken cancellationToken)
        {
            StatementSyntax newStatement = null;

            if (selectedStatements.Count == 1 &&
                !ifStatement.AsCascade().Any(f => f.Statement?.Kind() == SyntaxKind.Block))
            {
                newStatement = selectedStatements.First();
            }
            else
            {
                newStatement = SyntaxFactory.Block(selectedStatements);
            }

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

            IfStatementSyntax lastIfStatement = ifStatement.AsCascade().Last();

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

            SyntaxList <StatementSyntax> newStatements = selectedStatements.UnderlyingList.Replace(ifStatement, newIfStatement);

            for (int i = newStatements.Count - 1; i >= selectedStatements.FirstIndex; i--)
            {
                newStatements = newStatements.RemoveAt(i);
            }

            return(document.ReplaceStatementsAsync(SyntaxInfo.StatementListInfo(selectedStatements), newStatements, cancellationToken));
        }
        private static async Task <Document> UseExceptionFilterAsync(
            Document document,
            IfStatementSyntax ifStatement,
            CancellationToken cancellationToken)
        {
            ElseClauseSyntax elseClause = ifStatement.Else;

            var catchClause = (CatchClauseSyntax)ifStatement.Parent.Parent;

            SyntaxList <StatementSyntax> statements = catchClause.Block.Statements;

            ExpressionSyntax filterExpression = ifStatement.Condition;

            SyntaxList <StatementSyntax> newStatements;

            if (ifStatement.Statement.SingleNonBlockStatementOrDefault() is ThrowStatementSyntax throwStatement &&
                throwStatement.Expression == null)
            {
                if (elseClause != null)
                {
                    newStatements = ReplaceStatement(elseClause.Statement);
                }
                else
                {
                    newStatements = statements.RemoveAt(0);
                }

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

                filterExpression = SyntaxInverter.LogicallyInvert(filterExpression, semanticModel, cancellationToken);
            }
Esempio n. 14
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));
        }
        private static Task <Document> RefactorAsync(
            Document document,
            StatementsInfo statementsInfo,
            LocalDeclarationStatementSyntax[] localDeclarations,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            LocalDeclarationStatementSyntax localDeclaration = localDeclarations[0];

            SyntaxList <StatementSyntax> statements = statementsInfo.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);
            }

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
Esempio n. 16
0
        private static Task <Document> IfReturnToReturnWithConditionalExpressionAsync(
            Document document,
            IfReturnToReturnWithConditionalExpressionAnalysis analysis,
            CancellationToken cancellationToken = default)
        {
            IfStatementSyntax ifStatement = analysis.IfStatement;

            StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(ifStatement);

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(ifStatement);

            ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(ifStatement.Condition, analysis.Expression1, analysis.Expression2);

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

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

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
        public static Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            CancellationToken cancellationToken)
        {
            ReturnStatementSyntax newReturnStatement = CreateReturnStatement(ifStatement);

            if (ifStatement.Else != null)
            {
                newReturnStatement = newReturnStatement.WithTriviaFrom(ifStatement);

                return(document.ReplaceNodeAsync(ifStatement, newReturnStatement, cancellationToken));
            }
            else
            {
                var block = (BlockSyntax)ifStatement.Parent;
                SyntaxList <StatementSyntax> statements = block.Statements;

                int index = statements.IndexOf(ifStatement);

                var returnStatement = (ReturnStatementSyntax)statements[index + 1];

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

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

                return(document.ReplaceNodeAsync(block, block.WithStatements(newStatements), cancellationToken));
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Move the item at oldIndex to newIndex.
        /// </summary>
        /// <typeparam name="T">The type of items in <paramref name="list"/>.</typeparam>
        /// <param name="list">The <see cref="SyntaxList{T}"/>.</param>
        /// <param name="oldIndex">The old index.</param>
        /// <param name="newIndex">The new index.</param>
        /// <returns>A <see cref="SyntaxList{T}"/> with the item moved.</returns>
        public static SyntaxList <T> Move <T>(this SyntaxList <T> list, int oldIndex, int newIndex)
            where T : SyntaxNode
        {
            var item = list[oldIndex];

            return(list.RemoveAt(oldIndex)
                   .Insert(Math.Min(newIndex, list.Count - 1), item));
        }
Esempio n. 19
0
        private static SyntaxList <StatementSyntax> RemoveBreakStatement(SyntaxList <StatementSyntax> statements)
        {
            int index = statements.IndexOf(SyntaxKind.BreakStatement);

            if (index != -1)
            {
                return(statements.RemoveAt(index));
            }

            return(statements);
        }
Esempio n. 20
0
        private static Task <Document> IfToReturnWithExpressionAsync(
            Document document,
            IfToReturnWithExpressionAnalysis analysis,
            CancellationToken cancellationToken = default)
        {
            ExpressionSyntax expression = analysis.Expression;

            if (analysis.Invert)
            {
                expression = SyntaxInverter.LogicallyInvert(expression, analysis.SemanticModel, cancellationToken);
            }

            StatementSyntax statement;

            if (analysis.IsYield)
            {
                statement = YieldReturnStatement(expression);
            }
            else
            {
                statement = ReturnStatement(expression);
            }

            IfStatementSyntax ifStatement = analysis.IfStatement;

            if (ifStatement.IsSimpleIf())
            {
                StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(ifStatement);

                SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

                int index = statements.IndexOf(ifStatement);

                StatementSyntax newNode = statement
                                          .WithLeadingTrivia(ifStatement.GetLeadingTrivia())
                                          .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia())
                                          .WithFormatterAnnotation();

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

                return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
            }
            else
            {
                StatementSyntax newNode = statement
                                          .WithTriviaFrom(ifStatement)
                                          .WithFormatterAnnotation();

                return(document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken));
            }
        }
        private static SyntaxList <UsingDirectiveSyntax> FilterOutUsings(SyntaxList <UsingDirectiveSyntax> usings,
                                                                         string[] usingsToFilterOut)
        {
            for (;;)
            {
                var index = usings.IndexOf(usingDirectiveSyntax => usingDirectiveSyntax.Alias == null && Array.IndexOf(usingsToFilterOut, usingDirectiveSyntax.Name.ToString()) >= 0);
                if (index < 0)
                {
                    return(usings);
                }

                usings = usings.RemoveAt(index);
            }
        }
Esempio n. 22
0
        private ClassDeclarationSyntax WrapMembersWithComment(ClassDeclarationSyntax node, SyntaxList <MemberDeclarationSyntax> members)
        {
            if (members.Count == 0)
            {
                node = node.WithOpenBraceToken(GetOpenBraceTokenWithEmptyCustomCode())
                       .WithMembers(SyntaxFactory.List <MemberDeclarationSyntax>());
            }
            else if (members.Count == 1)
            {
                var newMember = AddLeadingTriviaComment(AddTrailingTriviaComment(members.Single()));
                node = node.WithMembers(members.RemoveAt(0).Add(newMember));
            }
            else
            {
                var firstMember = AddLeadingTriviaComment(members.First());

                var lastMember    = AddTrailingTriviaComment(members.Last());
                var lastMemberIdx = members.Count - 1;

                node = node.WithMembers(members.RemoveAt(lastMemberIdx).RemoveAt(0).Insert(0, firstMember).Add(lastMember));
            }

            return(node);
        }
Esempio n. 23
0
        private static DocumentationCommentTriviaSyntax RemoveFilterPriorityElement(DocumentationCommentTriviaSyntax commentTrivia)
        {
            SyntaxList <XmlNodeSyntax> content = commentTrivia.Content;

            for (int i = content.Count - 1; i >= 0; i--)
            {
                XmlNodeSyntax xmlNode = content[i];

                if (xmlNode is XmlElementSyntax xmlElement &&
                    xmlElement.IsLocalName("filterpriority", StringComparison.OrdinalIgnoreCase))
                {
                    content = content.RemoveAt(i);
                }
            }

            return(commentTrivia.WithContent(content));
        }
        public override async Task <Document> RefactorAsync(Document document, CancellationToken cancellationToken = default(CancellationToken))
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            int position = IfStatement.SpanStart;

            ITypeSymbol targetType = GetTargetType(position, semanticModel, cancellationToken);

            BinaryExpressionSyntax coalesceExpression = RefactoringHelper.CreateCoalesceExpression(
                targetType,
                Left.WithoutTrivia(),
                Right.WithoutTrivia(),
                position,
                semanticModel);

            StatementSyntax statement = CreateStatement(coalesceExpression);

            if (IfStatement.IsSimpleIf())
            {
                StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(IfStatement);

                SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

                int index = statements.IndexOf(IfStatement);

                StatementSyntax newNode = statement
                                          .WithLeadingTrivia(IfStatement.GetLeadingTrivia())
                                          .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia())
                                          .WithFormatterAnnotation();

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

                return(await document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken).ConfigureAwait(false));
            }
            else
            {
                StatementSyntax newNode = statement
                                          .WithTriviaFrom(IfStatement)
                                          .WithFormatterAnnotation();

                return(await document.ReplaceNodeAsync(IfStatement, newNode, cancellationToken).ConfigureAwait(false));
            }
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            CancellationToken cancellationToken)
        {
            ExpressionSyntax returnExpression = ifStatement.Condition;

            if (GetBooleanLiteral(ifStatement.Statement).Kind() == SyntaxKind.FalseLiteralExpression)
            {
                SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                returnExpression = CSharpUtility.LogicallyNegate(returnExpression, semanticModel, cancellationToken);
            }

            ReturnStatementSyntax newReturnStatement = ReturnStatement(
                ReturnKeyword().WithTrailingTrivia(Space),
                returnExpression,
                SemicolonToken());

            if (ifStatement.Else != null)
            {
                newReturnStatement = newReturnStatement.WithTriviaFrom(ifStatement);

                return(await document.ReplaceNodeAsync(ifStatement, newReturnStatement, cancellationToken).ConfigureAwait(false));
            }

            StatementContainer container = StatementContainer.Create(ifStatement);

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(ifStatement);

            var returnStatement = (ReturnStatementSyntax)statements[index + 1];

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

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

            //TODO: ReplaceStatementsAsync
            return(await document.ReplaceNodeAsync(container.Node, container.WithStatements(newStatements).Node, cancellationToken).ConfigureAwait(false));
        }
        public override Task <Document> RefactorAsync(
            Document document,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            IStatementContainer 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));
        }
Esempio n. 27
0
        public override Task <Document> RefactorAsync(
            Document document,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(IfStatement);

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(IfStatement);

            TStatement newStatement = CreateNewStatement();

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

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
Esempio n. 28
0
        private static Task <Document> ToAssignmentWithConditionalExpressionAsync(
            Document document,
            ToAssignmentWithConditionalExpressionAnalysis analysis,
            StatementSyntax newStatement,
            CancellationToken cancellationToken = default)
        {
            StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(analysis.IfStatement);

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(analysis.IfStatement);

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

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
Esempio n. 29
0
        private void DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxList <SyntaxNode> list)
        {
            Assert.Equal(0, list.Count);

            SyntaxNode nodeD = SyntaxFactory.ParseExpression("D ");
            SyntaxNode nodeE = SyntaxFactory.ParseExpression("E ");

            var newList = list.Add(nodeD);

            Assert.Equal(1, newList.Count);
            Assert.Equal("D ", newList.ToFullString());

            newList = list.AddRange(new[] { nodeD, nodeE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("D E ", newList.ToFullString());

            newList = list.Insert(0, nodeD);
            Assert.Equal(1, newList.Count);
            Assert.Equal("D ", newList.ToFullString());

            newList = list.InsertRange(0, new[] { nodeD, nodeE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("D E ", newList.ToFullString());

            newList = list.Remove(nodeD);
            Assert.Equal(0, newList.Count);

            Assert.Equal(-1, list.IndexOf(nodeD));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.RemoveAt(0));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.Insert(1, nodeD));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.Insert(-1, nodeD));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { nodeD }));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { nodeD }));
            Assert.Throws <ArgumentException>(() => list.Replace(nodeD, nodeE));
            Assert.Throws <ArgumentException>(() => list.ReplaceRange(nodeD, new[] { nodeE }));
            Assert.Throws <ArgumentNullException>(() => list.Add(null));
            Assert.Throws <ArgumentNullException>(
                () => list.AddRange((IEnumerable <SyntaxNode>)null)
                );
            Assert.Throws <ArgumentNullException>(() => list.Insert(0, null));
            Assert.Throws <ArgumentNullException>(
                () => list.InsertRange(0, (IEnumerable <SyntaxNode>)null)
                );
        }
            private SyntaxNode Rewrite(StatementsInfo statementsInfo, IfStatementSyntax ifStatement)
            {
                SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

                int index = statements.IndexOf(ifStatement);

                ExpressionSyntax newCondition = LogicalNegationHelper.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(statementsInfo.WithStatements(newStatements).Node);
            }