Ejemplo n.º 1
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));
        }
Ejemplo n.º 2
0
 private static SyntaxList <AttributeSyntax> RemoveAttributeFromAttributeLists(
     SyntaxList <AttributeSyntax> attributeLists,
     SyntaxNode attributeToRemove,
     CodeGenerationOptions options,
     out int positionOfRemovedNode,
     out SyntaxTriviaList triviaOfRemovedNode)
 {
     triviaOfRemovedNode   = new SyntaxTriviaList();
     positionOfRemovedNode = attributeToRemove.SpanStart;
     return(attributeLists.Remove((AttributeSyntax)attributeToRemove));
 }
        private static SyntaxList <MemberDeclarationSyntax> WithMoved(SyntaxList <MemberDeclarationSyntax> members, MemberDeclarationSyntax member)
        {
            members = members.Remove(member);
            for (var i = 0; i < members.Count; i++)
            {
                var current = members[i];
                if (MemberDeclarationComparer.Compare(member, current) < 0)
                {
                    return(RemoveLeadingEndOfLine(members.Insert(i, UpdateLineFeed(member))));
                }
            }

            return(RemoveLeadingEndOfLine(members.Add(UpdateLineFeed(member))));
        }
Ejemplo n.º 4
0
        private static NamespaceDeclarationSyntax AmendUsings(NamespaceDeclarationSyntax nameSpace, SyntaxList <UsingDirectiveSyntax> usings)
        {
            var last = nameSpace.Name.ToString().Right(c => c != '.');

            foreach (var item in usings)
            {
                var name  = item.Name.ToString();
                var first = name.Left(c => c != '.');

                if (first == last)
                {
                    usings = usings.Remove(item);
                    usings = usings.Add(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("global::" + name)));
                }
            }

            return(nameSpace.WithUsings(usings));
        }
Ejemplo n.º 5
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)
                );
        }
Ejemplo n.º 6
0
        public static SyntaxList <AttributeListSyntax> RemoveAttribute(SyntaxList <AttributeListSyntax> attributeLists, string name)
        {
            foreach (var attrList in attributeLists.ToArray())
            {
                foreach (var attr in attrList.Attributes)
                {
                    if (attr.Name.ToString() == name)
                    {
                        attributeLists = attributeLists.Remove(attrList);

                        var newAttrList = attrList.RemoveNode(attr, SyntaxRemoveOptions.KeepNoTrivia);
                        if (newAttrList.Attributes.Count != 0)
                        {
                            attributeLists = attributeLists.Add(newAttrList);
                        }
                    }
                }
            }

            return(attributeLists);
        }
        protected static SyntaxList <XmlNodeSyntax> CommentStartingWith(SyntaxList <XmlNodeSyntax> content, string phrase)
        {
            // when necessary adjust beginning text
            // Note: when on new line, then the text is not the 1st one but the 2nd one
            var index = GetIndex(content);

            if (index < 0)
            {
                return(content.Add(SyntaxFactory.XmlText(phrase)));
            }

            if (content[index] is XmlTextSyntax text)
            {
                // we have to remove the element as otherwise we duplicate the comment
                content = content.Remove(content[index]);

                if (phrase.IsNullOrWhiteSpace())
                {
                    var textTokens = text.TextTokens.Count;
                    if (textTokens > 2)
                    {
                        // TODO: RKN find a better solution this as it is not good code

                        // remove last "\r\n" token and remove '  /// ' trivia of last token
                        if (text.TextTokens[textTokens - 2].IsKind(SyntaxKind.XmlTextLiteralNewLineToken) &&
                            text.TextTokens[textTokens - 1].ValueText.IsNullOrWhiteSpace())
                        {
                            var newTokens = text.TextTokens.Take(textTokens - 2).ToArray();
                            text = SyntaxFactory.XmlText(newTokens);
                        }
                    }
                }

                var newText = text.WithStartText(phrase);

                return(content.Insert(index, newText));
            }

            return(content.Insert(index, SyntaxFactory.XmlText(phrase)));
        }
Ejemplo n.º 8
0
        private static SyntaxList <StatementSyntax> GetSectionStatements(SwitchSectionSyntax switchSection)
        {
            SyntaxList <StatementSyntax> statements = switchSection.Statements;

            if (statements.Count == 1 &&
                statements[0].IsKind(SyntaxKind.Block))
            {
                statements = ((BlockSyntax)statements[0]).Statements;
            }

            if (statements.Any())
            {
                StatementSyntax last = statements.Last();

                if (last.IsKind(SyntaxKind.BreakStatement))
                {
                    return(statements.Remove(last));
                }
            }

            return(statements);
        }
Ejemplo n.º 9
0
        public SyntaxList <AttributeListSyntax> Remove()
        {
            var attributes = _attributeList.First(a =>
                                                  a.Attributes.Any(at =>
                                                                   at.Name.ToString().Equals(_attributeText, StringComparison.OrdinalIgnoreCase)));

            if (attributes.Attributes.Count == 1 && _attributeList.Count == 1)
            {
                return(new SyntaxList <AttributeListSyntax>());
            }

            if (attributes.Attributes.Count == 1)
            {
                return(_attributeList.Remove(attributes));
            }

            var attribute = attributes.Attributes.First(at =>
                                                        at.Name.ToString().Equals(_attributeText, StringComparison.OrdinalIgnoreCase));

            var newAttributes = attributes.WithAttributes(attributes.Attributes.Remove(attribute));

            return(_attributeList.Replace(attributes, newAttributes));
        }
Ejemplo n.º 10
0
        private static async Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            CancellationToken cancellationToken)
        {
            ExpressionSyntax condition = ifStatement.Condition;

            ElseClauseSyntax elseClause = ifStatement.Else;

            if ((ifStatement.Statement as BlockSyntax)?.Statements.Any() == false)
            {
                SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                ExpressionSyntax newCondition = Inverter.LogicallyNegate(condition, semanticModel, cancellationToken);

                StatementSyntax statement = elseClause.Statement;

                if (statement is IfStatementSyntax nestedIf)
                {
                    newCondition = LogicalAndExpression(newCondition.Parenthesize(), nestedIf.Condition.Parenthesize());

                    statement = nestedIf.Statement;
                }

                cancellationToken.ThrowIfCancellationRequested();

                IfStatementSyntax newNode = ifStatement.Update(
                    ifStatement.IfKeyword,
                    ifStatement.OpenParenToken,
                    newCondition,
                    ifStatement.CloseParenToken,
                    statement,
                    default(ElseClauseSyntax));

                newNode = newNode.WithFormatterAnnotation();

                return(await document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken).ConfigureAwait(false));
            }
            else if (elseClause != null)
            {
                WhileStatementSyntax whileStatement;

                if (ifStatement.Parent is BlockSyntax block)
                {
                    whileStatement = (WhileStatementSyntax)block.Parent;
                }
                else
                {
                    block          = Block();
                    whileStatement = (WhileStatementSyntax)ifStatement.Parent;
                }

                cancellationToken.ThrowIfCancellationRequested();

                BlockSyntax newBlock = (ifStatement.Statement is BlockSyntax ifBlock)
                    ? block.WithStatements(ifBlock.Statements)
                    : block.WithStatements(SingletonList(ifStatement.Statement));

                SyntaxNode newNode = whileStatement.Update(
                    whileStatement.WhileKeyword,
                    whileStatement.OpenParenToken,
                    ifStatement.Condition,
                    whileStatement.CloseParenToken,
                    newBlock);

                newNode = newNode.WithFormatterAnnotation();

                return(await document.ReplaceNodeAsync(whileStatement, newNode, cancellationToken).ConfigureAwait(false));
            }
            else
            {
                var block = (BlockSyntax)ifStatement.Parent;

                SyntaxList <StatementSyntax> statements = block.Statements;

                BlockSyntax newBlock = block.WithStatements(statements.Remove(ifStatement));

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

                ExpressionSyntax newCondition = Inverter.LogicallyNegate(condition, semanticModel, cancellationToken);

                SyntaxNode newNode = block.Parent;

                switch (block.Parent)
                {
                case WhileStatementSyntax whileStatement:
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    if (statements.IsFirst(ifStatement))
                    {
                        newNode = whileStatement.Update(
                            whileStatement.WhileKeyword,
                            whileStatement.OpenParenToken,
                            newCondition,
                            whileStatement.CloseParenToken,
                            newBlock);
                    }
                    else
                    {
                        newNode = DoStatement(
                            Token(whileStatement.WhileKeyword.LeadingTrivia, SyntaxKind.DoKeyword, whileStatement.CloseParenToken.TrailingTrivia),
                            newBlock.WithoutTrailingTrivia(),
                            Token(SyntaxKind.WhileKeyword),
                            OpenParenToken(),
                            newCondition,
                            CloseParenToken(),
                            SemicolonToken().WithTrailingTrivia(newBlock.GetTrailingTrivia()));
                    }

                    break;
                }

                case DoStatementSyntax doStatement:
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    if (statements.IsLast(ifStatement))
                    {
                        newNode = doStatement.Update(
                            doStatement.DoKeyword,
                            newBlock,
                            doStatement.WhileKeyword,
                            doStatement.OpenParenToken,
                            newCondition,
                            doStatement.CloseParenToken,
                            doStatement.SemicolonToken);
                    }
                    else
                    {
                        newNode = WhileStatement(
                            Token(doStatement.DoKeyword.LeadingTrivia, SyntaxKind.WhileKeyword, SyntaxTriviaList.Empty),
                            OpenParenToken(),
                            newCondition,
                            Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, doStatement.DoKeyword.TrailingTrivia),
                            newBlock.WithTrailingTrivia(doStatement.GetTrailingTrivia()));
                    }

                    break;
                }

                default:
                {
                    Debug.Fail(block.Parent.Kind().ToString());
                    break;
                }
                }

                newNode = newNode.WithFormatterAnnotation();

                return(await document.ReplaceNodeAsync(block.Parent, newNode, cancellationToken).ConfigureAwait(false));
            }
        }
        public static SyntaxList <XmlNodeSyntax> WithoutFirstAndLastNewlines(this SyntaxList <XmlNodeSyntax> summaryContent)
        {
            if (summaryContent.Count == 0)
            {
                return(summaryContent);
            }

            if (!(summaryContent[0] is XmlTextSyntax firstSyntax))
            {
                return(summaryContent);
            }

            if (!(summaryContent[summaryContent.Count - 1] is XmlTextSyntax lastSyntax))
            {
                return(summaryContent);
            }

            SyntaxTokenList firstSyntaxTokens = firstSyntax.TextTokens;

            int removeFromStart;

            if (IsXmlNewLine(firstSyntaxTokens[0]))
            {
                removeFromStart = 1;
            }
            else
            {
                if (!IsXmlWhitespace(firstSyntaxTokens[0]))
                {
                    return(summaryContent);
                }

                if (!IsXmlNewLine(firstSyntaxTokens[1]))
                {
                    return(summaryContent);
                }

                removeFromStart = 2;
            }

            SyntaxTokenList lastSyntaxTokens = lastSyntax.TextTokens;

            int removeFromEnd;

            if (IsXmlNewLine(lastSyntaxTokens[lastSyntaxTokens.Count - 1]))
            {
                removeFromEnd = 1;
            }
            else
            {
                if (!IsXmlWhitespace(lastSyntaxTokens[lastSyntaxTokens.Count - 1]))
                {
                    return(summaryContent);
                }

                if (!IsXmlNewLine(lastSyntaxTokens[lastSyntaxTokens.Count - 2]))
                {
                    return(summaryContent);
                }

                removeFromEnd = 2;
            }

            for (int i = 0; i < removeFromStart; i++)
            {
                firstSyntaxTokens = firstSyntaxTokens.RemoveAt(0);
            }

            if (firstSyntax == lastSyntax)
            {
                lastSyntaxTokens = firstSyntaxTokens;
            }

            for (int i = 0; i < removeFromEnd; i++)
            {
                if (!lastSyntaxTokens.Any())
                {
                    break;
                }

                lastSyntaxTokens = lastSyntaxTokens.RemoveAt(lastSyntaxTokens.Count - 1);
            }

            summaryContent = summaryContent.RemoveAt(summaryContent.Count - 1);
            if (lastSyntaxTokens.Count != 0)
            {
                summaryContent = summaryContent.Add(lastSyntax.WithTextTokens(lastSyntaxTokens));
            }

            if (firstSyntax != lastSyntax)
            {
                summaryContent = summaryContent.RemoveAt(0);
                if (firstSyntaxTokens.Count != 0)
                {
                    summaryContent = summaryContent.Insert(0, firstSyntax.WithTextTokens(firstSyntaxTokens));
                }
            }

            if (summaryContent.Count > 0)
            {
                // Make sure to remove the leading trivia
                summaryContent = summaryContent.Replace(summaryContent[0], summaryContent[0].WithLeadingTrivia());

                // Remove leading spaces (between the <para> start tag and the start of the paragraph content)
                if (summaryContent[0] is XmlTextSyntax firstTextSyntax && firstTextSyntax.TextTokens.Count > 0)
                {
                    SyntaxToken firstTextToken = firstTextSyntax.TextTokens[0];
                    string      firstTokenText = firstTextToken.Text;
                    string      trimmed        = firstTokenText.TrimStart();
                    if (trimmed != firstTokenText)
                    {
                        if (trimmed.Length == 0)
                        {
                            if (firstTextSyntax.TextTokens.Count == 1)
                            {
                                summaryContent = summaryContent.Remove(firstTextSyntax);
                            }
                            else
                            {
                                summaryContent = summaryContent.Replace(firstTextSyntax, firstTextSyntax.WithTextTokens(firstTextSyntax.TextTokens.RemoveAt(0)));
                            }
                        }
                        else
                        {
                            SyntaxToken newFirstToken = SyntaxFactory.Token(
                                firstTextToken.LeadingTrivia,
                                firstTextToken.Kind(),
                                trimmed,
                                firstTextToken.ValueText.TrimStart(),
                                firstTextToken.TrailingTrivia);

                            summaryContent = summaryContent.Replace(firstTextSyntax, firstTextSyntax.ReplaceToken(firstTextToken, newFirstToken));
                        }
                    }
                }
            }

            return(summaryContent);
        }
Ejemplo n.º 12
0
        private static async Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            ExpressionSyntax condition = ifStatement.Condition;

            ElseClauseSyntax elseClause = ifStatement.Else;

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

            SimplifyCodeBranchingKind kind = SimplifyCodeBranchingAnalyzer.GetKind(ifStatement, semanticModel, cancellationToken).Value;

            if (kind == SimplifyCodeBranchingKind.IfElseWithEmptyIf)
            {
                ExpressionSyntax newCondition = SyntaxInverter.LogicallyInvert(condition, semanticModel, cancellationToken);

                StatementSyntax statement = elseClause.Statement;

                if (statement is IfStatementSyntax nestedIf)
                {
                    newCondition = LogicalAndExpression(newCondition.Parenthesize(), nestedIf.Condition.Parenthesize());

                    statement = nestedIf.Statement;
                }

                IfStatementSyntax newIfStatement = ifStatement.Update(
                    ifStatement.IfKeyword,
                    ifStatement.OpenParenToken,
                    newCondition,
                    ifStatement.CloseParenToken,
                    statement,
                    default(ElseClauseSyntax));

                newIfStatement = newIfStatement.WithFormatterAnnotation();

                return(await document.ReplaceNodeAsync(ifStatement, newIfStatement, cancellationToken).ConfigureAwait(false));
            }
            else if (kind == SimplifyCodeBranchingKind.IfElseInsideWhile)
            {
                bool elseContainsBreak = elseClause.SingleNonBlockStatementOrDefault()?.Kind() == SyntaxKind.BreakStatement;

                SyntaxList <StatementSyntax> statements;

                if (elseContainsBreak)
                {
                    statements = (ifStatement.Statement is BlockSyntax block2)
                        ? block2.Statements
                        : SingletonList(ifStatement.Statement);
                }
                else
                {
                    statements = (elseClause.Statement is BlockSyntax block2)
                        ? block2.Statements
                        : SingletonList(elseClause.Statement);
                }

                WhileStatementSyntax whileStatement;

                if (ifStatement.Parent is BlockSyntax block)
                {
                    whileStatement = (WhileStatementSyntax)block.Parent;

                    block = block.WithStatements(block.Statements.ReplaceRange(ifStatement, statements));
                }
                else
                {
                    whileStatement = (WhileStatementSyntax)ifStatement.Parent;

                    block = Block(statements);
                }

                if (!elseContainsBreak)
                {
                    condition = SyntaxInverter.LogicallyInvert(condition, semanticModel, cancellationToken);
                }

                WhileStatementSyntax newWhileStatement = whileStatement.Update(
                    whileStatement.WhileKeyword,
                    whileStatement.OpenParenToken,
                    condition,
                    whileStatement.CloseParenToken,
                    block);

                newWhileStatement = newWhileStatement.WithFormatterAnnotation();

                return(await document.ReplaceNodeAsync(whileStatement, newWhileStatement, cancellationToken).ConfigureAwait(false));
            }
            else if (kind == SimplifyCodeBranchingKind.SimplifIfInsideWhileOrDo)
            {
                var block = (BlockSyntax)ifStatement.Parent;

                SyntaxList <StatementSyntax> statements = block.Statements;

                BlockSyntax newBlock = block.WithStatements(statements.Remove(ifStatement));

                ExpressionSyntax newCondition = SyntaxInverter.LogicallyInvert(condition, semanticModel, cancellationToken);

                SyntaxNode newNode;

                switch (block.Parent)
                {
                case WhileStatementSyntax whileStatement:
                {
                    if (statements.IsFirst(ifStatement))
                    {
                        newNode = whileStatement.Update(
                            whileStatement.WhileKeyword,
                            whileStatement.OpenParenToken,
                            newCondition,
                            whileStatement.CloseParenToken,
                            newBlock);
                    }
                    else
                    {
                        newNode = DoStatement(
                            Token(whileStatement.WhileKeyword.LeadingTrivia, SyntaxKind.DoKeyword, whileStatement.CloseParenToken.TrailingTrivia),
                            newBlock.WithoutTrailingTrivia(),
                            Token(SyntaxKind.WhileKeyword),
                            OpenParenToken(),
                            newCondition,
                            CloseParenToken(),
                            SemicolonToken().WithTrailingTrivia(newBlock.GetTrailingTrivia()));
                    }

                    break;
                }

                case DoStatementSyntax doStatement:
                {
                    if (statements.IsLast(ifStatement))
                    {
                        newNode = doStatement.Update(
                            doStatement.DoKeyword,
                            newBlock,
                            doStatement.WhileKeyword,
                            doStatement.OpenParenToken,
                            newCondition,
                            doStatement.CloseParenToken,
                            doStatement.SemicolonToken);
                    }
                    else
                    {
                        newNode = WhileStatement(
                            Token(doStatement.DoKeyword.LeadingTrivia, SyntaxKind.WhileKeyword, SyntaxTriviaList.Empty),
                            OpenParenToken(),
                            newCondition,
                            Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, doStatement.DoKeyword.TrailingTrivia),
                            newBlock.WithTrailingTrivia(doStatement.GetTrailingTrivia()));
                    }

                    break;
                }

                default:
                {
                    throw new InvalidOperationException();
                }
                }

                newNode = newNode.WithFormatterAnnotation();

                return(await document.ReplaceNodeAsync(block.Parent, newNode, cancellationToken).ConfigureAwait(false));
            }
            else if (kind == SimplifyCodeBranchingKind.SimpleIfContainingOnlyDo)
            {
                StatementSyntax statement = ifStatement.SingleNonBlockStatementOrDefault();

                var doStatement = (DoStatementSyntax)statement;

                WhileStatementSyntax whileStatement = WhileStatement(
                    Token(ifStatement.GetLeadingTrivia(), SyntaxKind.WhileKeyword, SyntaxTriviaList.Empty),
                    OpenParenToken(),
                    doStatement.Condition,
                    Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, doStatement.DoKeyword.TrailingTrivia),
                    doStatement.Statement.WithTrailingTrivia(ifStatement.GetTrailingTrivia()));

                whileStatement = whileStatement.WithFormatterAnnotation();

                return(await document.ReplaceNodeAsync(ifStatement, whileStatement, cancellationToken).ConfigureAwait(false));
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
Ejemplo n.º 13
0
 public SyntaxList <TItem> Remove(SyntaxList <TItem> list, TItem item)
 {
     return(list.Remove(item));
 }