private async Task <Document> GetTransformedDocumentAsync(Document document, XmlElementSyntax elementSyntax, CancellationToken cancellationToken)
        {
            SyntaxList <XmlNodeSyntax> content = elementSyntax.Content;

            if (content.Count == 0)
            {
                return(document);
            }

            var leadingTrivia = elementSyntax.StartTag.GetLeadingTrivia();

            leadingTrivia = leadingTrivia.AddRange(elementSyntax.StartTag.GetTrailingTrivia());
            leadingTrivia = leadingTrivia.AddRange(content[0].GetLeadingTrivia());
            content       = content.Replace(content[0], content[0].WithLeadingTrivia(leadingTrivia));

            var trailingTrivia = content[content.Count - 1].GetTrailingTrivia();

            trailingTrivia = trailingTrivia.AddRange(elementSyntax.EndTag.GetLeadingTrivia());
            trailingTrivia = trailingTrivia.AddRange(elementSyntax.EndTag.GetTrailingTrivia());
            content        = content.Replace(content[content.Count - 1], content[content.Count - 1].WithTrailingTrivia(trailingTrivia));

            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SyntaxNode newRoot = root.ReplaceNode(elementSyntax, content);

            return(document.WithSyntaxRoot(newRoot));
        }
Example #2
0
        private static async Task <Document> MoveDefaultLabelToLastPositionAsync(
            Document document,
            SwitchSectionSyntax switchSection,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SyntaxList <SwitchLabelSyntax> labels = switchSection.Labels;

            SwitchLabelSyntax defaultLabel = labels.First(f => f.IsKind(SyntaxKind.DefaultSwitchLabel));

            int index = labels.IndexOf(defaultLabel);

            SwitchLabelSyntax lastLabel = labels.Last();

            labels = labels.Replace(lastLabel, defaultLabel.WithTriviaFrom(lastLabel));

            labels = labels.Replace(labels[index], lastLabel.WithTriviaFrom(defaultLabel));

            SwitchSectionSyntax newSwitchSection = switchSection.WithLabels(labels);

            SyntaxNode newRoot = root.ReplaceNode(switchSection, newSwitchSection);

            return(document.WithSyntaxRoot(newRoot));
        }
Example #3
0
        private static SyntaxList <VBS.StatementSyntax> WithConvertedTrivia(this SyntaxList <VBS.StatementSyntax> vbStatements, CSS.BlockSyntax csBlock)
        {
            var last = csBlock.ChildNodesAndTokens().LastOrDefault();

            if (last != null)
            {
                if (last.IsKind(CS.SyntaxKind.CloseBraceToken))
                {
                    var lastToken        = last.AsToken();
                    var vbLastTriviaList = ConvertTriviaList(lastToken.LeadingTrivia);
                    var vbOldLast        = vbStatements.Last();
                    var vbNewLast        = vbOldLast.WithTrailingTrivia(vbOldLast.GetTrailingTrivia().AddRange(vbLastTriviaList));
                    vbStatements = vbStatements.Replace(vbOldLast, vbNewLast);
                }
                else if (last.IsKind(CS.SyntaxKind.Block))
                {
                    var lastBlock        = last.AsNode();
                    var vbLastTriviaList = ConvertTriviaList(lastBlock.GetLastToken().LeadingTrivia);
                    var vbOldLast        = vbStatements.Last();
                    var vbNewLast        = vbOldLast.WithTrailingTrivia(vbLastTriviaList);
                    vbStatements = vbStatements.Replace(vbOldLast, vbNewLast);
                }
            }
            return(vbStatements);
        }
Example #4
0
        SyntaxList <StatementSyntax> WrapInComment(SyntaxList <StatementSyntax> nodes, string comment)
        {
            if (nodes.Count > 0)
            {
                nodes = nodes.Replace(nodes[0], nodes[0].WithPrependedLeadingTrivia(SyntaxFactory.CommentTrivia("BEGIN TODO : " + comment)));
                nodes = nodes.Replace(nodes.Last(), nodes.Last().WithAppendedTrailingTrivia(SyntaxFactory.CommentTrivia("END TODO : " + comment)));
            }

            return(nodes);
        }
Example #5
0
        private static SyntaxList <T> WithSourceMappingFrom <T>(this SyntaxList <T> converted, SyntaxNode node) where T : SyntaxNode
        {
            if (!converted.Any())
            {
                return(converted);
            }
            var origLinespan = node.SyntaxTree.GetLineSpan(node.Span);
            var first        = converted.First();

            converted = converted.Replace(first, node.CopyAnnotationsTo(first).WithSourceStartLineAnnotation(origLinespan));
            var last = converted.Last();

            return(converted.Replace(last, last.WithSourceEndLineAnnotation(origLinespan)));
        }
        public static void Organize(
            SyntaxList <ExternAliasDirectiveSyntax> externAliasList,
            SyntaxList <UsingDirectiveSyntax> usingList,
            bool placeSystemNamespaceFirst,
            bool separateGroups,
            out SyntaxList <ExternAliasDirectiveSyntax> organizedExternAliasList,
            out SyntaxList <UsingDirectiveSyntax> organizedUsingList
            )
        {
            OrganizeWorker(
                externAliasList,
                usingList,
                placeSystemNamespaceFirst,
                out organizedExternAliasList,
                out organizedUsingList
                );

            if (separateGroups)
            {
                if (organizedExternAliasList.Count > 0 && organizedUsingList.Count > 0)
                {
                    var firstUsing = organizedUsingList[0];

                    if (!firstUsing.GetLeadingTrivia().Any(t => t.IsEndOfLine()))
                    {
                        var newFirstUsing = firstUsing.WithPrependedLeadingTrivia(s_newLine);
                        organizedUsingList = organizedUsingList.Replace(firstUsing, newFirstUsing);
                    }
                }

                for (var i = 1; i < organizedUsingList.Count; i++)
                {
                    var lastUsing    = organizedUsingList[i - 1];
                    var currentUsing = organizedUsingList[i];

                    if (
                        NeedsGrouping(lastUsing, currentUsing) &&
                        !currentUsing.GetLeadingTrivia().Any(t => t.IsEndOfLine())
                        )
                    {
                        var newCurrentUsing = currentUsing.WithPrependedLeadingTrivia(s_newLine);
                        organizedUsingList = organizedUsingList.Replace(
                            currentUsing,
                            newCurrentUsing
                            );
                    }
                }
            }
        }
Example #7
0
        public static async Task <Document> RefactorAsync(
            Document document,
            NamespaceDeclarationSyntax namespaceDeclaration,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            if (namespaceDeclaration == null)
            {
                throw new ArgumentNullException(nameof(namespaceDeclaration));
            }

            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var compilationUnit = (CompilationUnitSyntax)root;

            SyntaxList <UsingDirectiveSyntax> usings = namespaceDeclaration.Usings;

            CompilationUnitSyntax newCompilationUnit = compilationUnit
                                                       .RemoveNodes(usings, SyntaxRemoveOptions.KeepUnbalancedDirectives);

            if (!compilationUnit.Usings.Any())
            {
                SyntaxTriviaList leadingTrivia = compilationUnit.GetLeadingTrivia();

                SyntaxTrivia[] topTrivia = GetTopSingleLineComments(leadingTrivia).ToArray();

                if (topTrivia.Length > 0)
                {
                    newCompilationUnit = newCompilationUnit.WithoutLeadingTrivia();

                    usings = usings.Replace(
                        usings.First(),
                        usings.First().WithLeadingTrivia(topTrivia));

                    usings = usings.Replace(
                        usings.Last(),
                        usings.Last().WithTrailingTrivia(leadingTrivia.Skip(topTrivia.Length)));
                }
            }

            newCompilationUnit = newCompilationUnit.AddUsings(usings.Select(f => f.WithFormatterAnnotation()));

            return(document.WithSyntaxRoot(newCompilationUnit));
        }
        private static SyntaxList <MemberDeclarationSyntax> RemoveLeadingEndOfLine(SyntaxList <MemberDeclarationSyntax> members)
        {
            if (members.TryFirst(out var first) &&
                first.HasLeadingTrivia &&
                first.GetLeadingTrivia() is SyntaxTriviaList triviaList &&
                triviaList.TryFirst(x => x.IsKind(SyntaxKind.EndOfLineTrivia), out var eol))
            {
                return(members.Replace(
                           first,
                           first.WithLeadingTrivia(RemoveLeading())));
            }

            return(members);

            SyntaxTriviaList RemoveLeading()
            {
                for (var i = triviaList.IndexOf(eol); i >= 0; i--)
                {
                    if (triviaList[i] is SyntaxTrivia trivia &&
                        (trivia.IsKind(SyntaxKind.EndOfLineTrivia) || trivia.IsKind(SyntaxKind.WhitespaceTrivia)))
                    {
                        triviaList = triviaList.Remove(trivia);
                    }
                }

                return(triviaList);
            }
        }
        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));
        }
        private async Task <Document> RefactorAsync(
            Document document,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ConstructorDeclarationSyntax constructor = Constructor;

            var containingMember = constructor.Parent as MemberDeclarationSyntax;

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

            SyntaxList <MemberDeclarationSyntax> newMembers = members.Replace(
                constructor,
                constructor.AddBodyStatements(CreateAssignments().ToArray()));

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

            newMembers = newMembers.InsertRange(
                GetDeclarationIndex(members),
                CreateDeclarations(constructor, semanticModel, cancellationToken));

            return(await document.ReplaceNodeAsync(
                       containingMember,
                       containingMember.SetMembers(newMembers),
                       cancellationToken).ConfigureAwait(false));
        }
        private static Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            ReturnStatementSyntax returnStatement,
            IStatementContainer container,
            CancellationToken cancellationToken)
        {
            SyntaxList <StatementSyntax> statements = container.Statements;

            IfStatement ifElse = IfStatement.Create(ifStatement);

            StatementSyntax statement = returnStatement;

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

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

            IfStatementSyntax lastIfStatement = ifElse.Nodes.Last();

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

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

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

            ConstructorDeclarationSyntax constructor = Constructor;

            MemberDeclarationSyntax containingMember = constructor.GetParentMember();

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

            SyntaxList <MemberDeclarationSyntax> newMembers = members.Replace(
                constructor,
                constructor.AddBodyStatements(CreateAssignments().ToArray()));

            newMembers = newMembers.InsertRange(
                GetDeclarationIndex(members),
                CreateDeclarations());

            SyntaxNode newRoot = root.ReplaceNode(
                containingMember,
                containingMember.SetMembers(newMembers));

            return(document.WithSyntaxRoot(newRoot));
        }
Example #13
0
        public SyntaxList <AttributeListSyntax> Convert(
            SyntaxList <AttributeListSyntax> attributeList,
            bool isSkip,
            string skipText)
        {
            var attributes = attributeList.First(a =>
                                                 a.Attributes.Any(at => at.Name.ToString().Equals("Test", StringComparison.OrdinalIgnoreCase)));

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

            var newAttribute = attribute.WithName(SyntaxFactory.IdentifierName("Fact"));

            if (isSkip)
            {
                newAttribute = newAttribute.WithArgumentList(
                    SyntaxFactory.AttributeArgumentList(
                        SyntaxFactory.SeparatedList(new[]
                {
                    SyntaxFactory.AttributeArgument(
                        SyntaxFactory.NameEquals("Skip"),
                        null,
                        SyntaxFactory.IdentifierName(skipText))
                })));
            }

            return(attributeList.Replace(attributes, attributes.WithAttributes(
                                             attributes.Attributes.Replace(attribute, newAttribute))));
        }
Example #14
0
        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];

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

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

            ReturnStatementSyntax newReturnStatement = returnStatement
                                                       .WithExpression(expression)
                                                       .WithLeadingTrivia(localDeclaration.GetLeadingTrivia())
                                                       .WithTrailingTrivia(returnStatement.GetTrailingTrivia())
                                                       .WithFormatterAnnotation();

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

            BlockSyntax newBlock = block.WithStatements(newStatements);

            return(await document.ReplaceNodeAsync(block, newBlock, cancellationToken).ConfigureAwait(false));
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            FinallyClauseSyntax finallyClause,
            CancellationToken cancellationToken)
        {
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            if (finallyClause.GetLeadingTrivia().All(f => f.IsWhitespaceOrEndOfLineTrivia()))
            {
                var tryStatement = (TryStatementSyntax)finallyClause.Parent;

                SyntaxList <CatchClauseSyntax> catches = tryStatement.Catches;
                CatchClauseSyntax lastCatch            = catches[catches.Count - 1];

                if (lastCatch.GetTrailingTrivia().All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                {
                    TryStatementSyntax newTryStatement = tryStatement
                                                         .WithCatches(catches.Replace(lastCatch, lastCatch.WithTrailingTrivia(finallyClause.GetTrailingTrivia())))
                                                         .WithFinally(null);

                    return(await document.ReplaceNodeAsync(tryStatement, newTryStatement, cancellationToken).ConfigureAwait(false));
                }
            }

            return(await document.RemoveNodeAsync(finallyClause, SyntaxRemoveOptions.KeepExteriorTrivia, cancellationToken).ConfigureAwait(false));
        }
Example #16
0
        public static Task <Document> RefactorAsync(
            Document document,
            BlockSyntax block,
            CancellationToken cancellationToken)
        {
            SyntaxList <StatementSyntax> statements = block.Statements;

            var ifStatement = (IfStatementSyntax)statements[0];

            var returnStatement = (ReturnStatementSyntax)statements[1];

            var expressionStatement = (ExpressionStatementSyntax)ifStatement.GetSingleStatementOrDefault();

            var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;

            ExpressionSyntax expression = returnStatement.Expression.WithoutTrivia();

            BinaryExpressionSyntax coalesceExpression = CSharpFactory.CoalesceExpression(
                expression,
                CSharpFactory.SimpleAssignmentExpression(expression, assignment.Right.WithoutTrivia()).Parenthesize());

            ReturnStatementSyntax newReturnStatement = returnStatement
                                                       .WithExpression(coalesceExpression)
                                                       .WithLeadingTrivia(ifStatement.GetLeadingTrivia());

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Replace(returnStatement, newReturnStatement)
                                                         .RemoveAt(0);

            BlockSyntax newBlock = block.WithStatements(newStatements);

            return(document.ReplaceNodeAsync(block, newBlock, cancellationToken));
        }
Example #17
0
        private static SyntaxNode GetNewRoot(
            SyntaxNode root,
            IfStatementSyntax ifStatement,
            ReturnStatementSyntax newReturnStatement)
        {
            if (ifStatement.Else != null)
            {
                newReturnStatement = newReturnStatement.WithTriviaFrom(ifStatement);

                return(root.ReplaceNode(ifStatement, newReturnStatement));
            }
            else
            {
                var block = (BlockSyntax)ifStatement.Parent;

                int index = block.Statements.IndexOf(ifStatement);

                var returnStatement = (ReturnStatementSyntax)block.Statements[index + 1];

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

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

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

                return(root.ReplaceNode(block, block.WithStatements(statements)));
            }
        }
        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));
        }
Example #19
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));
        }
Example #20
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));
        }
        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));
        }
Example #22
0
        private static async Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            ConditionalExpressionSyntax conditionalExpression,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync().ConfigureAwait(false);

            TypeSyntax type = localDeclaration.Declaration.Type;

            LocalDeclarationStatementSyntax newLocalDeclaration = localDeclaration.RemoveNode(conditionalExpression.Parent, SyntaxRemoveOptions.KeepExteriorTrivia);

            if (type.IsVar)
            {
                ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(conditionalExpression);

                if (typeSymbol?.IsErrorType() == false)
                {
                    newLocalDeclaration = newLocalDeclaration.ReplaceNode(
                        newLocalDeclaration.Declaration.Type,
                        typeSymbol.ToMinimalTypeSyntax(semanticModel, type.SpanStart).WithSimplifierAnnotation());
                }
            }

            newLocalDeclaration = newLocalDeclaration
                                  .WithLeadingTrivia(localDeclaration.GetLeadingTrivia())
                                  .WithFormatterAnnotation();

            IfStatementSyntax ifStatement = CreateIfStatement(conditionalExpression)
                                            .WithTrailingTrivia(localDeclaration.GetTrailingTrivia())
                                            .WithFormatterAnnotation();

            SyntaxNode parent = localDeclaration.Parent;

            if (parent.IsKind(SyntaxKind.SwitchSection))
            {
                var section = (SwitchSectionSyntax)parent;

                SyntaxList <StatementSyntax> statements = section.Statements;

                statements = statements
                             .Replace(localDeclaration, newLocalDeclaration)
                             .Insert(statements.IndexOf(localDeclaration) + 1, ifStatement);

                return(await document.ReplaceNodeAsync(section, section.WithStatements(statements), cancellationToken).ConfigureAwait(false));
            }
            else
            {
                var block = (BlockSyntax)parent;

                SyntaxList <StatementSyntax> statements = block.Statements;

                statements = statements
                             .Replace(localDeclaration, newLocalDeclaration)
                             .Insert(statements.IndexOf(localDeclaration) + 1, ifStatement);

                return(await document.ReplaceNodeAsync(block, block.WithStatements(statements), cancellationToken).ConfigureAwait(false));
            }
        }
        public SyntaxList <MemberDeclarationSyntax> AddEndRegion(SyntaxList <MemberDeclarationSyntax> newMembersSyntaxList)
        {
            var modifiedLastMember = newMembersSyntaxList
                                     .Last()
                                     .WithTrailingTrivia(TriviaList(Trivia(EndRegionDirectiveTrivia(true))));

            return(newMembersSyntaxList.Replace(newMembersSyntaxList.Last(), modifiedLastMember));
        }
Example #24
0
        private static Task <Document> RefactorAsync(
            Document document,
            StatementListInfo statementsInfo,
            StatementSyntax statement,
            InitializerExpressionSyntax initializer,
            ExpressionSyntax initializedExpression,
            CancellationToken cancellationToken)
        {
            ExpressionStatementSyntax[] expressions = CreateExpressionStatements(initializer, initializedExpression).ToArray();

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

            var objectCreationExpression = (ObjectCreationExpressionSyntax)initializer.Parent;

            ObjectCreationExpressionSyntax newObjectCreationExpression = objectCreationExpression.WithInitializer(null);

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

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

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(statement);

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

            SyntaxKind statementKind = statement.Kind();

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

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

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

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

            SyntaxNode newNode = statementsInfo
                                 .WithStatements(newStatements.InsertRange(index + 1, expressions))
                                 .Parent
                                 .WithFormatterAnnotation();

            return(document.ReplaceNodeAsync(statementsInfo.Parent, newNode, cancellationToken));
        }
Example #25
0
        private static async Task <Document> IntroduceFieldToLockOnAsync(
            Document document,
            LockStatementSyntax lockStatement,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            MemberDeclarationSyntax containingMember = lockStatement.FirstAncestorOrSelf <MemberDeclarationSyntax>();

            if (containingMember != null)
            {
                var containingDeclaration = (MemberDeclarationSyntax)containingMember
                                            .Ancestors()
                                            .FirstOrDefault(f => f.IsKind(
                                                                SyntaxKind.ClassDeclaration,
                                                                SyntaxKind.InterfaceDeclaration,
                                                                SyntaxKind.StructDeclaration));

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

                    int index = members.IndexOf(containingMember);

                    string name = LockObjectName;

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

                        name = SyntaxUtility.GetUniqueName(name, semanticModel, lockStatement.Expression.Span.Start);
                    }

                    LockStatementSyntax newLockStatement = lockStatement
                                                           .WithExpression(IdentifierName(name));

                    MemberDeclarationSyntax newContainingMember = containingMember
                                                                  .ReplaceNode(lockStatement, newLockStatement);

                    bool isStatic = containingMember.GetModifiers().Contains(SyntaxKind.StaticKeyword);

                    FieldDeclarationSyntax field = CreateField(name, isStatic).WithFormatterAnnotation();

                    SyntaxList <MemberDeclarationSyntax> newMembers = members
                                                                      .Replace(members[index], newContainingMember)
                                                                      .Insert(FindField(members, index) + 1, field);

                    MemberDeclarationSyntax newNode = containingDeclaration.SetMembers(newMembers);

                    SyntaxNode newRoot = root.ReplaceNode(containingDeclaration, newNode);

                    return(document.WithSyntaxRoot(newRoot));
                }
            }

            return(document);
        }
Example #26
0
        public static Task <Document> RemoveRedundantAssignmentAfterLocalDeclarationAsync(
            Document document,
            VariableDeclaratorSyntax declarator,
            CancellationToken cancellationToken = default)
        {
            var declaration = (VariableDeclarationSyntax)declarator.Parent;

            var localDeclaration = (LocalDeclarationStatementSyntax)declaration.Parent;

            StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(localDeclaration);

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(localDeclaration);

            StatementSyntax nextStatement = statements[index + 1];

            var expressionStatement = (ExpressionStatementSyntax)nextStatement;

            var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;

            ExpressionSyntax right = assignment.Right;

            EqualsValueClauseSyntax initializer = declarator.Initializer;

            ExpressionSyntax value = initializer?.Value;

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

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

            SyntaxTriviaList trailingTrivia = localDeclaration.GetTrailingTrivia();

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

            SyntaxTriviaList leadingTrivia = nextStatement.GetLeadingTrivia();

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

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

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
        private static IEnumerable <XmlNodeSyntax> RemovePlaceHolder(XmlElementSyntax elementSyntax)
        {
            SyntaxList <XmlNodeSyntax> content = elementSyntax.Content;

            var leadingTrivia = elementSyntax.StartTag.GetLeadingTrivia();

            leadingTrivia = leadingTrivia.AddRange(elementSyntax.StartTag.GetTrailingTrivia());
            leadingTrivia = leadingTrivia.AddRange(content[0].GetLeadingTrivia());
            content       = content.Replace(content[0], content[0].WithLeadingTrivia(leadingTrivia));

            var trailingTrivia = content[content.Count - 1].GetTrailingTrivia();

            trailingTrivia = trailingTrivia.AddRange(elementSyntax.EndTag.GetLeadingTrivia());
            trailingTrivia = trailingTrivia.AddRange(elementSyntax.EndTag.GetTrailingTrivia());
            content        = content.Replace(content[content.Count - 1], content[content.Count - 1].WithTrailingTrivia(trailingTrivia));

            return(content);
        }
Example #28
0
        public static Task <Document> RefactorAsync(
            Document document,
            VariableDeclaratorSyntax declarator,
            CancellationToken cancellationToken)
        {
            var declaration = (VariableDeclarationSyntax)declarator.Parent;

            var localDeclaration = (LocalDeclarationStatementSyntax)declaration.Parent;

            StatementContainer container = StatementContainer.Create(localDeclaration);

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(localDeclaration);

            StatementSyntax nextStatement = statements[index + 1];

            var expressionStatement = (ExpressionStatementSyntax)nextStatement;

            var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;

            ExpressionSyntax right = assignment.Right;

            EqualsValueClauseSyntax initializer = declarator.Initializer;

            ExpressionSyntax value = initializer?.Value;

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

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

            SyntaxTriviaList trailingTrivia = localDeclaration.GetTrailingTrivia();

            if (trailingTrivia.Any(f => !f.IsWhitespaceOrEndOfLineTrivia()))
            {
                newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(trailingTrivia.Concat(nextStatement.GetTrailingTrivia()));
            }
            else
            {
                newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(nextStatement.GetTrailingTrivia());
            }

            SyntaxTriviaList leadingTrivia = nextStatement.GetLeadingTrivia();

            if (leadingTrivia.Any(f => !f.IsWhitespaceOrEndOfLineTrivia()))
            {
                newLocalDeclaration = newLocalDeclaration.WithLeadingTrivia(newLocalDeclaration.GetLeadingTrivia().Concat(leadingTrivia));
            }

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

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
Example #29
0
        public static SyntaxList <T> WithCsSourceMappingFrom <T>(this SyntaxList <T> converted, SyntaxNode node) where T : VisualBasicSyntaxNode
        {
            if (converted.Count != 1)
            {
                return(WithSourceMappingFrom(converted, node));
            }
            var single = converted.Single();

            return(converted.Replace(single, single.WithCsSourceMappingFrom(node)));
        }
            SyntaxList <StatementSyntax> ReWriteBlockStatements(SyntaxList <StatementSyntax> blockStatements)
            {
                if (blockStatements.Any() == false)
                {
                    return(blockStatements);
                }
                var first    = blockStatements[0];
                var newFirst = first.WithLeadingTrivia(CleanUpListWithExactNumberOfWhitespaces(first.GetLeadingTrivia(), 0));

                return(blockStatements.Replace(first, newFirst));
            }