Ejemplo n.º 1
0
        public static Task <Document> RefactorAsync(
            Document document,
            SwitchSectionSyntax switchSection,
            int numberOfAdditionalSectionsToMerge,
            CancellationToken cancellationToken)
        {
            var switchStatement = (SwitchStatementSyntax)switchSection.Parent;

            SyntaxList <SwitchSectionSyntax> sections = switchStatement.Sections;

            int index = sections.IndexOf(switchSection);

            IEnumerable <SwitchSectionSyntax> sectionsWithoutStatements = sections
                                                                          .Skip(index)
                                                                          .Take(numberOfAdditionalSectionsToMerge + 1)
                                                                          .Select(section => CreateSectionWithoutStatements(section));

            SyntaxList <SwitchSectionSyntax> newSections = sections.Take(index)
                                                           .Concat(sectionsWithoutStatements)
                                                           .Concat(sections.Skip(index + numberOfAdditionalSectionsToMerge + 1))
                                                           .ToSyntaxList();

            SwitchStatementSyntax newSwitchStatement = switchStatement.WithSections(newSections);

            return(document.ReplaceNodeAsync(switchStatement, newSwitchStatement, cancellationToken));
        }
Ejemplo n.º 2
0
        private static SyntaxList <XmlNodeSyntax> RemoveTrailingEmptyLines(SyntaxList <XmlNodeSyntax> content)
        {
            if (!(content[content.Count - 1] is XmlTextSyntax xmlText))
            {
                return(content);
            }

            // skip the last token, as it contains the documentation comment for the closing tag, which needs to remain.
            var firstEmptyToken = -1;

            for (var j = xmlText.TextTokens.Count - 2; j >= 0; j--)
            {
                var textToken = xmlText.TextTokens[j];

                if (textToken.IsXmlWhitespace())
                {
                    firstEmptyToken = j;
                }
                else if (textToken.IsKind(SyntaxKind.XmlTextLiteralToken) && !string.IsNullOrWhiteSpace(textToken.Text))
                {
                    break;
                }
            }

            if (firstEmptyToken > -1)
            {
                var newContent = SyntaxFactory.List(content.Take(firstEmptyToken));
                newContent.Add(newContent.Last());
                return(newContent);
            }

            return(content);
        }
Ejemplo n.º 3
0
        private static ForStatementSyntax CreateForStatement(
            WhileStatementSyntax whileStatement,
            VariableDeclarationSyntax declaration,
            SeparatedSyntaxList <ExpressionSyntax> initializers,
            SeparatedSyntaxList <ExpressionSyntax> incrementors)
        {
            StatementSyntax statement = whileStatement.Statement;

            if (statement?.IsKind(SyntaxKind.Block) == true)
            {
                var block = (BlockSyntax)statement;

                incrementors = SeparatedList(GetIncrementors(block));

                if (incrementors.Any())
                {
                    SyntaxList <StatementSyntax> statements = block.Statements;

                    statement = block.WithStatements(List(statements.Take(statements.Count - incrementors.Count)));
                }
            }

            return(ForStatement(
                       declaration,
                       initializers,
                       whileStatement.Condition,
                       incrementors,
                       statement));
        }
Ejemplo n.º 4
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));
        }
        private static ForStatementSyntax ConvertWhileToFor(
            WhileStatementSyntax whileStatement,
            VariableDeclarationSyntax declaration = default(VariableDeclarationSyntax),
            SeparatedSyntaxList <ExpressionSyntax> initializers = default(SeparatedSyntaxList <ExpressionSyntax>))
        {
            var incrementors = default(SeparatedSyntaxList <ExpressionSyntax>);

            StatementSyntax statement = whileStatement.Statement;

            if (statement is BlockSyntax block)
            {
                incrementors = SeparatedList(GetIncrementors(block));

                if (incrementors.Any())
                {
                    SyntaxList <StatementSyntax> statements = block.Statements;

                    statement = block.WithStatements(List(statements.Take(statements.Count - incrementors.Count)));
                }
            }

            return(ForStatement(
                       declaration,
                       initializers,
                       whileStatement.Condition,
                       incrementors,
                       statement));
        }
        public static void ComputeRefactoring(RefactoringContext context, MemberDeclarationSyntax member)
        {
            MemberDeclarationListInfo info = SyntaxInfo.MemberDeclarationListInfo(member.Parent);

            if (!info.Success)
            {
                return;
            }

            SyntaxList <MemberDeclarationSyntax> members = info.Members;

            if (members.Count <= 1)
            {
                return;
            }

            int index = IndexOfMemberToSwap(member, members, context.Span);

            if (index == -1)
            {
                return;
            }

            SyntaxTree tree = member.SyntaxTree;

            FileLinePositionSpan fileLinePositionSpan = tree.GetLineSpan(context.Span, context.CancellationToken);

            int startLine = fileLinePositionSpan.StartLine();
            int endLine   = fileLinePositionSpan.EndLine();

            if (startLine <= tree.GetEndLine(members[index].TrimmedSpan(), context.CancellationToken))
            {
                return;
            }

            if (endLine >= tree.GetStartLine(members[index + 1].TrimmedSpan(), context.CancellationToken))
            {
                return;
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveMemberDeclarations))
            {
                context.RegisterRefactoring(
                    "Remove members above",
                    ct => ReplaceMembersAsync(context.Document, info, members.Skip(index + 1), ct));

                context.RegisterRefactoring(
                    "Remove members below",
                    ct => ReplaceMembersAsync(context.Document, info, members.Take(index + 1), ct));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.SwapMemberDeclarations))
            {
                context.RegisterRefactoring(
                    "Swap members",
                    ct => SwapMembersAsync(context.Document, info, index, ct));
            }
        }
 private IEnumerable <Diagnostic> AnalyzeUsingDirectiveOrder(
     SyntaxList <UsingDirectiveSyntax> usingDirectives,
     DiagnosticDescriptor rule)
 {
     return(usingDirectives
            .Where((u, i) => usingDirectives.Take(i).Any(n => u.Name.ToString().CompareTo(n.Name.ToString()) == -1))
            .Select(u => Diagnostic.Create(rule, u.GetLocation()))
            .ToList());
 }
Ejemplo n.º 8
0
        private static async Task <Document> RefactorAsync(
            Document document,
            List <LocalDeclarationStatementSyntax> localDeclarations,
            List <ExpressionSyntax> expressions,
            WhileStatementSyntax whileStatement,
            CancellationToken cancellationToken)
        {
            var declaration  = default(VariableDeclarationSyntax);
            var initializers = default(SeparatedSyntaxList <ExpressionSyntax>);
            var incrementors = default(SeparatedSyntaxList <ExpressionSyntax>);

            if (localDeclarations != null)
            {
                IEnumerable <VariableDeclarationSyntax> declarations = localDeclarations
                                                                       .Select(f => f.Declaration)
                                                                       .Where(f => f != null);

                TypeSyntax type = declarations.First().Type.TrimTrivia();

                IEnumerable <VariableDeclaratorSyntax> variables = declarations
                                                                   .SelectMany(f => f.Variables)
                                                                   .Select(f => f.TrimTrivia());

                declaration = VariableDeclaration(type, SeparatedList(variables));

                StatementContainer container;
                if (StatementContainer.TryCreate(whileStatement, out container))
                {
                    SyntaxList <StatementSyntax> statements = container.Statements;

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

                    ForStatementSyntax forStatement = CreateForStatement(whileStatement, declaration, initializers, incrementors);

                    forStatement = forStatement
                                   .TrimLeadingTrivia()
                                   .PrependToLeadingTrivia(localDeclarations[0].GetLeadingTrivia());

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

                    return(await document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken).ConfigureAwait(false));
                }
            }
            else if (expressions != null)
            {
                initializers = SeparatedList(expressions);
            }

            return(await document.ReplaceNodeAsync(
                       whileStatement,
                       CreateForStatement(whileStatement, declaration, initializers, incrementors),
                       cancellationToken).ConfigureAwait(false));
        }
 private static SyntaxList <StatementSyntax> CreateNewStatementList(
     SyntaxList <StatementSyntax> oldStatements,
     LocalDeclarationStatementSyntax localDeclaration,
     StatementSyntax newStatement,
     int statementIndex)
 {
     return(oldStatements.Take(statementIndex)
            .Concat(localDeclaration.WithLeadingTrivia(oldStatements.Skip(statementIndex).First().GetLeadingTrivia()))
            .Concat(newStatement.WithoutLeadingTrivia())
            .Concat(oldStatements.Skip(statementIndex + 1))
            .ToSyntaxList());
 }
Ejemplo n.º 10
0
        private static Task <Document> RefactorAsync(
            Document document,
            MemberDeclarationSelection selectedMembers,
            MemberDeclarationSortMode sortMode,
            CancellationToken cancellationToken)
        {
            MemberDeclarationComparer comparer = MemberDeclarationComparer.GetInstance(sortMode);

            MemberDeclarationSyntax containingMember = selectedMembers.ContainingMember;

            SyntaxList <MemberDeclarationSyntax> members = containingMember.GetMembers();

            SyntaxList <MemberDeclarationSyntax> newMembers = members
                                                              .Take(selectedMembers.StartIndex)
                                                              .Concat(selectedMembers.OrderBy(f => f, comparer))
                                                              .Concat(members.Skip(selectedMembers.EndIndex + 1))
                                                              .ToSyntaxList();

            MemberDeclarationSyntax newNode = containingMember.WithMembers(newMembers);

            return(document.ReplaceNodeAsync(containingMember, newNode, cancellationToken));
        }
Ejemplo n.º 11
0
        private static async Task <Document> RefactorAsync(
            Document document,
            SelectedMemberDeclarationCollection selectedMembers,
            MemberDeclarationSortMode sortMode,
            CancellationToken cancellationToken)
        {
            var comparer = new MemberDeclarationComparer(sortMode);

            MemberDeclarationSyntax containingMember = selectedMembers.ContainingMember;

            SyntaxList <MemberDeclarationSyntax> members = containingMember.GetMembers();

            SyntaxList <MemberDeclarationSyntax> newMembers = members
                                                              .Take(selectedMembers.FirstIndex)
                                                              .Concat(selectedMembers.OrderBy(f => f, comparer))
                                                              .Concat(members.Skip(selectedMembers.LastIndex + 1))
                                                              .ToSyntaxList();

            MemberDeclarationSyntax newNode = containingMember.SetMembers(newMembers);

            return(await document.ReplaceNodeAsync(containingMember, newNode, cancellationToken).ConfigureAwait(false));
        }
        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));
        }
        private static Task <Document> RefactorAsync(
            Document document,
            SwitchSectionSyntax switchSection,
            SwitchLabelSyntax[] selectedLabels,
            CancellationToken cancellationToken)
        {
            SyntaxList <SwitchLabelSyntax> labels = switchSection.Labels;

            int lastIndex = labels.IndexOf(selectedLabels.Last());

            var switchStatement = (SwitchStatementSyntax)switchSection.Parent;

            SwitchStatementSyntax newSwitchStatement = switchStatement
                                                       .RemoveNodes(labels.Take(lastIndex + 1), SyntaxRemoveOptions.KeepNoTrivia);

            SyntaxList <SwitchSectionSyntax> newSections = newSwitchStatement
                                                           .Sections
                                                           .InsertRange(0, CreateSwitchSections(switchSection, selectedLabels));

            newSwitchStatement = newSwitchStatement.WithSections(newSections);

            return(document.ReplaceNodeAsync(switchStatement, newSwitchStatement, cancellationToken));
        }
Ejemplo n.º 14
0
        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());

            StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(whileStatement);

            SyntaxList <StatementSyntax> statements = statementsInfo.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.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
        public static Task <Document> RefactorAsync(
            Document document,
            SwitchSectionSyntax switchSection,
            CancellationToken cancellationToken)
        {
            var switchStatement = (SwitchStatementSyntax)switchSection.Parent;

            SyntaxList <SwitchSectionSyntax> sections = switchStatement.Sections;

            SyntaxList <StatementSyntax> statements = GetStatementsOrDefault(switchSection);

            int index = sections.IndexOf(switchSection);

            int i = index + 1;

            while (i < sections.Count - 1 &&
                   !sections[i].SpanOrLeadingTriviaContainsDirectives() &&
                   AreEquivalent(statements, GetStatementsOrDefault(sections[i + 1])))
            {
                i++;
            }

            IEnumerable <SwitchSectionSyntax> sectionsWithoutStatements = sections
                                                                          .Skip(index)
                                                                          .Take(i - index)
                                                                          .Select(CreateSectionWithoutStatements);

            SyntaxList <SwitchSectionSyntax> newSections = sections
                                                           .Take(index)
                                                           .Concat(sectionsWithoutStatements)
                                                           .Concat(sections.Skip(i))
                                                           .ToSyntaxList();

            SwitchStatementSyntax newSwitchStatement = switchStatement.WithSections(newSections);

            return(document.ReplaceNodeAsync(switchStatement, newSwitchStatement, cancellationToken));
        }
        private static IEnumerable <SwitchSectionSyntax> CreateSwitchSections(SwitchSectionSyntax switchSection, SwitchLabelSyntax[] selectedLabels)
        {
            SyntaxList <SwitchLabelSyntax> labels = switchSection.Labels;

            int firstIndex = labels.IndexOf(selectedLabels[0]);

            if (firstIndex > 0)
            {
                yield return(SwitchSection(labels.Take(firstIndex + 1).ToSyntaxList(), SingletonList <StatementSyntax>(BreakStatement()))
                             .WithFormatterAnnotation());

                foreach (SwitchLabelSyntax label in selectedLabels.Skip(1))
                {
                    yield return(CreateSection(label));
                }
            }
            else
            {
                foreach (SwitchLabelSyntax label in selectedLabels)
                {
                    yield return(CreateSection(label));
                }
            }
        }
        public static void ComputeRefactoring(RefactoringContext context, MemberDeclarationSyntax member)
        {
            SyntaxNode parent = member.Parent;

            if (parent?.IsKind(
                SyntaxKind.NamespaceDeclaration,
                SyntaxKind.ClassDeclaration,
                SyntaxKind.StructDeclaration,
                SyntaxKind.InterfaceDeclaration) == true)
            {
                var parentMember = (MemberDeclarationSyntax)parent;

                SyntaxList<MemberDeclarationSyntax> members = parentMember.GetMembers();

                if (members.Count > 1)
                {
                    int index = IndexOfMemberToSwap(member, members, context.Span);

                    if (index != -1)
                    {
                        SyntaxTree tree = member.SyntaxTree;

                        FileLinePositionSpan fileLinePositionSpan = tree.GetLineSpan(context.Span, context.CancellationToken);

                        int startLine = fileLinePositionSpan.StartLine();
                        int endLine = fileLinePositionSpan.EndLine();

                        if (startLine > tree.GetEndLine(members[index].TrimmedSpan(), context.CancellationToken)
                            && endLine < tree.GetStartLine(members[index + 1].TrimmedSpan(), context.CancellationToken))
                        {
                            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveMemberDeclarations))
                            {
                                context.RegisterRefactoring(
                                    "Remove members above",
                                    cancellationToken =>
                                    {
                                        return ReplaceMembersAsync(
                                            context.Document,
                                            parentMember,
                                            List(members.Skip(index + 1)),
                                            cancellationToken);
                                    });

                                context.RegisterRefactoring(
                                    "Remove members below",
                                    cancellationToken =>
                                    {
                                        return ReplaceMembersAsync(
                                            context.Document,
                                            parentMember,
                                            List(members.Take(index + 1)),
                                            cancellationToken);
                                    });
                            }

                            if (context.IsRefactoringEnabled(RefactoringIdentifiers.SwapMemberDeclarations))
                            {
                                context.RegisterRefactoring(
                                    "Swap members",
                                    cancellationToken =>
                                    {
                                        return RefactorAsync(
                                            context.Document,
                                            parentMember,
                                            members,
                                            index,
                                            cancellationToken);
                                    });
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 18
0
 public static SyntaxList <T> Insert <T>(this SyntaxList <T> list, int index, T item) where T : SyntaxNode
 {
     return(list.Take(index).Concat(item).Concat(list.Skip(index)).ToSyntaxList());
 }
        public static void ComputeRefactoring(RefactoringContext context, MemberDeclarationSyntax member)
        {
            var parent = member.Parent as MemberDeclarationSyntax;

            if (parent != null)
            {
                SyntaxList <MemberDeclarationSyntax> members = parent.GetMembers();

                if (members.Count > 1)
                {
                    int index = IndexOfMemberToSwap(member, members, context.Span);

                    if (index != -1)
                    {
                        FileLinePositionSpan fileSpan = member.SyntaxTree.GetLineSpan(context.Span, context.CancellationToken);
                        if (fileSpan.StartLine() > members[index].SyntaxTree.GetLineSpan(members[index].TrimmedSpan(), context.CancellationToken).EndLine() &&
                            fileSpan.EndLine() < members[index + 1].SyntaxTree.GetLineSpan(members[index + 1].TrimmedSpan(), context.CancellationToken).StartLine())
                        {
                            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveMemberDeclarations))
                            {
                                context.RegisterRefactoring(
                                    "Remove members above",
                                    cancellationToken =>
                                {
                                    return(ReplaceMembersAsync(
                                               context.Document,
                                               parent,
                                               members,
                                               List(members.Skip(index + 1)),
                                               cancellationToken));
                                });

                                context.RegisterRefactoring(
                                    "Remove members below",
                                    cancellationToken =>
                                {
                                    return(ReplaceMembersAsync(
                                               context.Document,
                                               parent,
                                               members,
                                               List(members.Take(index + 1)),
                                               cancellationToken));
                                });
                            }

                            if (context.IsRefactoringEnabled(RefactoringIdentifiers.SwapMemberDeclarations))
                            {
                                context.RegisterRefactoring(
                                    "Swap members",
                                    cancellationToken =>
                                {
                                    return(RefactorAsync(
                                               context.Document,
                                               parent,
                                               members,
                                               index,
                                               cancellationToken));
                                });
                            }
                        }
                    }
                }
            }
        }
        private static Task <Document> RefactorAsync(
            Document document,
            SwitchSectionSyntax section,
            SyntaxListSelection <SwitchLabelSyntax> selectedLabels,
            CancellationToken cancellationToken)
        {
            SyntaxList <SwitchLabelSyntax> labels = section.Labels;

            int lastIndex = selectedLabels.EndIndex;

            if (selectedLabels.Last() == labels.Last())
            {
                lastIndex--;
            }

            var switchStatement = (SwitchStatementSyntax)section.Parent;

            SyntaxList <SwitchSectionSyntax> sections = switchStatement.Sections;

            int index = sections.IndexOf(section);

            SyntaxList <SwitchSectionSyntax> newSections = sections
                                                           .ReplaceAt(index, section.RemoveNodes(labels.Take(lastIndex + 1), SyntaxRemoveOptions.KeepNoTrivia))
                                                           .InsertRange(index, CreateSwitchSections(section, selectedLabels, lastIndex));

            SwitchStatementSyntax newSwitchStatement = switchStatement.WithSections(newSections);

            return(document.ReplaceNodeAsync(switchStatement, newSwitchStatement, cancellationToken));
        }
        private SyntaxList <StatementSyntax> RefactorIfStatements(SyntaxList <StatementSyntax> statements, int ifCounter)
        {
            var newStatements = new SyntaxList <StatementSyntax>();

            int position = 0;

            while (position < statements.Count)
            {
                var statement = statements[position];
                if (statement.IsKind(SyntaxKind.IfStatement))
                {
                    newStatements = newStatements.AddRange(ConvertIfStatement(statement as IfStatementSyntax, new SyntaxList <StatementSyntax>(statements.Skip(position + 1)), new SyntaxList <StatementSyntax>(statements.Take(position)), ++ifCounter));
                    break;
                }
                else
                {
                    newStatements = newStatements.Add(statement);
                    position++;
                }
            }
            return(newStatements);
        }