private static SyntaxTriviaList InsertDocumentationCommentTrivia(SyntaxTriviaList leadingTrivia, SyntaxTrivia commentTrivia)
        {
            int index = leadingTrivia.LastIndexOf(SyntaxKind.EndOfLineTrivia);

            if (index != -1)
            {
                return(leadingTrivia.Insert(index + 1, commentTrivia));
            }
            else
            {
                return(leadingTrivia.Insert(0, commentTrivia));
            }
        }
Example #2
0
        private void DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxTriviaList list)
        {
            Assert.Equal(0, list.Count);

            var triviaD = SyntaxFactory.ParseLeadingTrivia("/*D*/")[0];
            var triviaE = SyntaxFactory.ParseLeadingTrivia("/*E*/")[0];

            var newList = list.Add(triviaD);

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

            newList = list.AddRange(new[] { triviaD, triviaE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("/*D*//*E*/", newList.ToFullString());

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

            newList = list.InsertRange(0, new[] { triviaD, triviaE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("/*D*//*E*/", newList.ToFullString());

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

            Assert.Equal(-1, list.IndexOf(triviaD));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.RemoveAt(0));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.Insert(1, triviaD));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.Insert(-1, triviaD));
            Assert.Throws <ArgumentOutOfRangeException>(
                () => list.InsertRange(1, new[] { triviaD })
                );
            Assert.Throws <ArgumentOutOfRangeException>(
                () => list.InsertRange(-1, new[] { triviaD })
                );
            Assert.Throws <ArgumentOutOfRangeException>(() => list.Replace(triviaD, triviaE));
            Assert.Throws <ArgumentOutOfRangeException>(
                () => list.ReplaceRange(triviaD, new[] { triviaE })
                );
            Assert.Throws <ArgumentOutOfRangeException>(() => list.Add(default(SyntaxTrivia)));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxTrivia)));
            Assert.Throws <ArgumentNullException>(
                () => list.AddRange((IEnumerable <SyntaxTrivia>)null)
                );
            Assert.Throws <ArgumentNullException>(
                () => list.InsertRange(0, (IEnumerable <SyntaxTrivia>)null)
                );
        }
        private BlockSyntax ToBlockSyntax(StatementSyntax body, SyntaxTriviaList leading, SyntaxTriviaList trailing)
        {
            //TODO: fix trivia
            var bracketLeadingTrivia          = leading.Insert(0, SyntaxFactory.EndOfLine(Environment.NewLine));
            List <StatementSyntax> statements = new List <StatementSyntax>();

            if (body.Kind() == SyntaxKind.Block)
            {
                body = (StatementSyntax)Visit(body);
                return((BlockSyntax)body);
            }
            else
            {
                var leadingTrivia = body.GetLeadingTrivia();
                body = (StatementSyntax)Visit(body);
                statements.Add(body);
            }

            BlockSyntax block = SyntaxFactory.Block(statements);

            block = block.WithOpenBraceToken(
                SyntaxFactory.Token(SyntaxKind.OpenBraceToken)
                .WithLeadingTrivia(bracketLeadingTrivia)
                .WithTrailingTrivia(SyntaxFactory.EndOfLine(Environment.NewLine))
                );
            block = block.WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken).
                                              WithLeadingTrivia(bracketLeadingTrivia).
                                              WithTrailingTrivia(SyntaxFactory.EndOfLine(Environment.NewLine)));

            return(block);
        }
        private SyntaxList <StatementSyntax> ToBlockSyntax(SyntaxList <StatementSyntax> body, SyntaxTriviaList leading, SyntaxTriviaList trailing)
        {
            if (body.Count == 1)
            {
                var firstStatement = body[0];
                if (firstStatement.Kind() == SyntaxKind.Block)
                {
                    return(body);
                }
            }

            BlockSyntax block = SyntaxFactory.Block(body);
            var         bracketLeadingTrivia = leading.Insert(0, SyntaxFactory.EndOfLine(Environment.NewLine));

            block = block.WithOpenBraceToken(
                SyntaxFactory.Token(SyntaxKind.OpenBraceToken)
                .WithLeadingTrivia(bracketLeadingTrivia)
//                    .WithTrailingTrivia(SyntaxFactory.EndOfLine(Environment.NewLine))
                );
            block = block.WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken).
                                              WithLeadingTrivia(bracketLeadingTrivia)
//                .WithTrailingTrivia(SyntaxFactory.EndOfLine(Environment.NewLine))
                                              );

            SyntaxList <StatementSyntax> list = new SyntaxList <StatementSyntax>();

            list = list.Add(block);

            return(list);
        }
Example #5
0
        public static Task <Document> ToMultiLineAsync(
            Document document,
            MemberAccessExpressionSyntax[] expressions,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            MemberAccessExpressionSyntax expression = expressions[0];

            SyntaxTriviaList leadingTrivia = GetIncreasedIndentation(expression, cancellationToken);

            leadingTrivia = leadingTrivia.Insert(0, NewLine());

            MemberAccessExpressionSyntax newNode = expression.ReplaceNodes(expressions, (node, node2) =>
            {
                SyntaxToken operatorToken = node.OperatorToken;

                if (!operatorToken.HasLeadingTrivia)
                {
                    return(node2.WithOperatorToken(operatorToken.WithLeadingTrivia(leadingTrivia)));
                }
                else
                {
                    return(node2);
                }
            });

            newNode = newNode.WithFormatterAnnotation();

            return(document.ReplaceNodeAsync(expression, newNode, cancellationToken));
        }
        /// <summary>
        /// Adds documentation header async.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="root">The root.</param>
        /// <param name="declarationSyntax">The declaration syntax.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A Document.</returns>
        private async Task <Document> AddDocumentationHeaderAsync(Document document, SyntaxNode root, PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
        {
            SyntaxTriviaList leadingTrivia = declarationSyntax.GetLeadingTrivia();

            bool isBoolean = false;

            if (declarationSyntax.Type is PredefinedTypeSyntax)
            {
                isBoolean = ((PredefinedTypeSyntax)declarationSyntax.Type).Keyword.Kind() == SyntaxKind.BoolKeyword;
            }

            bool hasSetter = false;

            if (declarationSyntax.AccessorList != null && declarationSyntax.AccessorList.Accessors.Any(o => o.Kind() == SyntaxKind.SetAccessorDeclaration))
            {
                hasSetter = true;
            }

            string propertyComment = CommentHelper.CreatePropertyComment(declarationSyntax.Identifier.ValueText, isBoolean, hasSetter);
            DocumentationCommentTriviaSyntax commentTrivia = await Task.Run(() => DocumentationHeaderHelper.CreateOnlySummaryDocumentationCommentTrivia(propertyComment), cancellationToken);

            SyntaxTriviaList          newLeadingTrivia = leadingTrivia.Insert(leadingTrivia.Count - 1, SyntaxFactory.Trivia(commentTrivia));
            PropertyDeclarationSyntax newDeclaration   = declarationSyntax.WithLeadingTrivia(newLeadingTrivia);

            SyntaxNode newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);

            return(document.WithSyntaxRoot(newRoot));
        }
Example #7
0
        private static InitializerExpressionSyntax GetMultilineInitializer(InitializerExpressionSyntax initializer)
        {
            SyntaxNode parent = initializer.Parent;

            if (parent.IsKind(SyntaxKind.ObjectCreationExpression) &&
                !initializer.IsKind(SyntaxKind.CollectionInitializerExpression))
            {
                return(initializer
                       .WithExpressions(
                           SeparatedList(
                               initializer.Expressions.Select(expression => expression.WithLeadingTrivia(SyntaxHelper.NewLine))))
                       .WithAdditionalAnnotations(Formatter.Annotation));
            }

            SyntaxTriviaList indent  = initializer.GetIndentTrivia();
            SyntaxTriviaList indent2 = indent.Add(SyntaxHelper.DefaultIndent);

            indent  = indent.Insert(0, SyntaxHelper.NewLine);
            indent2 = indent2.Insert(0, SyntaxHelper.NewLine);

            return(initializer
                   .WithExpressions(
                       SeparatedList(
                           initializer.Expressions.Select(expression => expression.WithLeadingTrivia(indent2))))
                   .WithOpenBraceToken(initializer.OpenBraceToken.WithLeadingTrivia(indent))
                   .WithCloseBraceToken(initializer.CloseBraceToken.WithLeadingTrivia(indent))
                   .WithAdditionalAnnotations(Formatter.Annotation));
        }
        private static InitializerExpressionSyntax GetMultilineInitializer(InitializerExpressionSyntax initializer)
        {
            SyntaxNode parent = initializer.Parent;

            if (parent.IsKind(SyntaxKind.ObjectCreationExpression) &&
                !initializer.IsKind(SyntaxKind.CollectionInitializerExpression))
            {
                return(initializer
                       .WithExpressions(
                           SeparatedList(
                               initializer.Expressions.Select(expression => expression.WithLeadingTrivia(CSharpFactory.NewLineTrivia()))))
                       .WithFormatterAnnotation());
            }

            SyntaxTriviaList indent  = SyntaxUtility.GetIndentTrivia(initializer);
            SyntaxTriviaList indent2 = indent.Add(CSharpFactory.IndentTrivia());

            indent  = indent.Insert(0, CSharpFactory.NewLineTrivia());
            indent2 = indent2.Insert(0, CSharpFactory.NewLineTrivia());

            return(initializer
                   .WithExpressions(
                       SeparatedList(
                           initializer.Expressions.Select(expression => expression.WithLeadingTrivia(indent2))))
                   .WithOpenBraceToken(initializer.OpenBraceToken.WithLeadingTrivia(indent))
                   .WithCloseBraceToken(initializer.CloseBraceToken.WithLeadingTrivia(indent))
                   .WithFormatterAnnotation());
        }
        private static IEnumerable <StatementSyntax> GetNewNodes(StatementSyntax statement)
        {
            SyntaxTriviaList leadingTrivia = statement.Parent.GetLeadingTrivia();

            if (statement.IsKind(SyntaxKind.ElseClause))
            {
                leadingTrivia.Insert(0, SyntaxHelper.NewLine);
            }

            if (statement.IsKind(SyntaxKind.Block))
            {
                SyntaxList <StatementSyntax> .Enumerator en = ((BlockSyntax)statement).Statements.GetEnumerator();

                if (en.MoveNext())
                {
                    yield return(en.Current.WithLeadingTrivia(leadingTrivia));

                    while (en.MoveNext())
                    {
                        yield return(en.Current);
                    }
                }
            }
            else
            {
                yield return(statement.WithLeadingTrivia(leadingTrivia));
            }
        }
Example #10
0
        private static ConditionalExpressionSyntax CreateMultilineConditionalExpression(ConditionalExpressionSyntax conditionalExpression)
        {
            SyntaxTriviaList triviaList = SyntaxUtility.GetIndentTrivia(conditionalExpression.Parent).Add(CSharpFactory.IndentTrivia());

            triviaList = triviaList.Insert(0, CSharpFactory.NewLineTrivia());

            ParenthesizedExpressionSyntax condition = null;

            if (conditionalExpression.Condition.IsKind(SyntaxKind.ParenthesizedExpression))
            {
                condition = (ParenthesizedExpressionSyntax)conditionalExpression.Condition;
            }
            else
            {
                condition = ParenthesizedExpression(conditionalExpression.Condition.WithoutTrailingTrivia())
                            .WithCloseParenToken(CreateTokenWithTrailingNewLine(SyntaxKind.CloseParenToken));
            }

            return(ConditionalExpression(
                       condition.WithoutTrailingTrivia(),
                       conditionalExpression.WhenTrue.WithoutTrailingTrivia(),
                       conditionalExpression.WhenFalse.WithoutTrailingTrivia())
                   .WithQuestionToken(CreateToken(SyntaxKind.QuestionToken, triviaList))
                   .WithColonToken(CreateToken(SyntaxKind.ColonToken, triviaList)));
        }
Example #11
0
        private static Document InsertInheritdocComment(Document document, SyntaxNode root, SyntaxNode syntaxNode, CancellationToken cancellationToken)
        {
            // Currently unused
            _ = cancellationToken;

            SyntaxTriviaList leadingTrivia = syntaxNode.GetLeadingTrivia();
            int insertionIndex             = leadingTrivia.Count;

            while (insertionIndex > 0 && !leadingTrivia[insertionIndex - 1].HasBuiltinEndLine())
            {
                insertionIndex--;
            }

            string newLineText          = document.Project.Solution.Workspace.Options.GetOption(FormattingOptions.NewLine, LanguageNames.CSharp);
            var    documentationComment =
                XmlSyntaxFactory.DocumentationComment(
                    newLineText,
                    XmlSyntaxFactory.EmptyElement(XmlCommentHelper.InheritdocXmlTag));
            var trivia = SyntaxFactory.Trivia(documentationComment);

            SyntaxTriviaList newLeadingTrivia = leadingTrivia.Insert(insertionIndex, trivia);
            SyntaxNode       newElement       = syntaxNode.WithLeadingTrivia(newLeadingTrivia);

            return(document.WithSyntaxRoot(root.ReplaceNode(syntaxNode, newElement)));
        }
        public static SyntaxTriviaList AddLeadingEndOfLineIfNotExist(this SyntaxTriviaList trivia)
        {
            if (trivia.Any(SyntaxKind.EndOfLineTrivia) == false)
            {
                return(trivia.Insert(0, SyntaxFactory.EndOfLine(Environment.NewLine)));
            }

            return(trivia);
        }
Example #13
0
        /// <summary>
        /// Ensure the trivia list has a blank line at the end.  Both the second to last
        /// and final line may contain spaces.
        ///
        /// Note: This function assumes the trivia token before <param name="startIndex" />
        /// is an end of line trivia.
        /// </summary>
        private static void EnsureHasBlankLineAtEnd(ref SyntaxTriviaList list, int startIndex, SyntaxTrivia newLineTrivia)
        {
            const int StateNone      = 0;
            const int StateEol       = 1;
            const int StateBlankLine = 2;

            var state    = StateEol;
            var index    = startIndex;
            var eolIndex = startIndex - 1;

            while (index < list.Count)
            {
                var current = list[index];
                if (current.IsKind(SyntaxKind.WhitespaceTrivia))
                {
                    index++;
                    continue;
                }

                var isStateAnyEol = (state == StateEol || state == StateBlankLine);
                if (isStateAnyEol && current.IsKind(SyntaxKind.EndOfLineTrivia))
                {
                    state = StateBlankLine;
                }
                else if (current.IsAnyEndOfLine())
                {
                    eolIndex = index;
                    state    = StateEol;
                }
                else
                {
                    state = StateNone;
                }

                index++;
            }

            switch (state)
            {
            case StateNone:
                list = list.InsertRange(list.Count, new[] { newLineTrivia, newLineTrivia });
                break;

            case StateEol:
                list = list.Insert(eolIndex + 1, newLineTrivia);
                break;

            case StateBlankLine:
                // Nothing to do.
                break;

            default:
                Debug.Assert(false);
                break;
            }
        }
Example #14
0
        private SyntaxTriviaList RemoveIllegalHeadersFromMultilineComment(SyntaxTriviaList newTrivia, SyntaxTrivia trivia, string illegalHeader)
        {
            StringBuilder newTriviaString          = new StringBuilder();
            bool          commentHasMeaningfulInfo = false;
            bool          removedIllegalHeaders    = false;

            using (StringReader sr = new StringReader(trivia.ToFullString()))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    // If the current line contains the illegal header
                    if (line.IndexOf(illegalHeader, StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        // special care must be had to keep the /* and */ tokens.
                        if (line.TrimStart().StartsWith("/*"))
                        {
                            // Note: This will also cover the case where the comment is: /* illegalHeader */ as we remove the entire line (including the */).
                            newTriviaString.AppendLine("/*");
                        }
                        else if (line.TrimEnd().EndsWith("*/"))
                        {
                            newTriviaString.AppendLine("*/");
                        }
                        removedIllegalHeaders = true;
                    }
                    else
                    {
                        commentHasMeaningfulInfo |= CommentLineContainsMeaningfulIInformation(line);

                        newTriviaString.AppendLine(line);
                    }
                }
            }

            // We should not remove any comments if we don't have to.
            if (!removedIllegalHeaders)
            {
                return(newTrivia);
            }

            // Remove the old trivia and replace it with the new trivia
            var index = newTrivia.IndexOf(trivia);

            newTrivia = RemoveTriviaAtIndex(newTrivia, index);

            if (commentHasMeaningfulInfo)
            {
                // we need to remove the original multiline comment and replace it with this new one.
                var newMultilineComment = SyntaxFactory.Comment(newTriviaString.ToString());
                newTrivia = newTrivia.Insert(index, newMultilineComment);
            }

            return(newTrivia);
        }
Example #15
0
        public Func <SyntaxGenerator, MemberAccessExpressionSyntax, MemberAccessExpressionSyntax> GetAddCommentAction(string comment)
        {
            Func <SyntaxGenerator, MemberAccessExpressionSyntax, MemberAccessExpressionSyntax> AddComment = (SyntaxGenerator syntaxGenerator, MemberAccessExpressionSyntax node) =>
            {
                SyntaxTriviaList currentTrivia = node.GetLeadingTrivia();
                currentTrivia = currentTrivia.Insert(0, SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, string.Format(Constants.CommentFormat, comment)));
                node          = node.WithLeadingTrivia(currentTrivia).NormalizeWhitespace();
                return(node);
            };

            return(AddComment);
        }
Example #16
0
        /// <summary>
        /// Adds documentation header async.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="root">The root.</param>
        /// <param name="declarationSyntax">The declaration syntax.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A Task.</returns>
        private async Task <Document> AddDocumentationHeaderAsync(Document document, SyntaxNode root, MethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
        {
            SyntaxTriviaList leadingTrivia = declarationSyntax.GetLeadingTrivia();
            DocumentationCommentTriviaSyntax commentTrivia = await Task.Run(() => CreateDocumentationCommentTriviaSyntax(declarationSyntax), cancellationToken);

            SyntaxTriviaList        newLeadingTrivia = leadingTrivia.Insert(leadingTrivia.Count - 1, SyntaxFactory.Trivia(commentTrivia));
            MethodDeclarationSyntax newDeclaration   = declarationSyntax.WithLeadingTrivia(newLeadingTrivia);

            SyntaxNode newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);

            return(document.WithSyntaxRoot(newRoot));
        }
Example #17
0
        public Func <SyntaxGenerator, SyntaxNode, SyntaxNode> GetAddCommentAction(string comment)
        {
            SyntaxNode AddComment(SyntaxGenerator syntaxGenerator, SyntaxNode node)
            {
                SyntaxTriviaList currentTrivia = node.GetLeadingTrivia();

                currentTrivia = currentTrivia.Insert(0, SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, string.Format(Constants.CommentFormat, comment)));
                node          = node.WithLeadingTrivia(currentTrivia).NormalizeWhitespace();
                return(node);
            }

            return(AddComment);
        }
Example #18
0
        public static ConditionalExpressionSyntax ToMultiLine(ConditionalExpressionSyntax conditionalExpression, CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxTriviaList leadingTrivia = conditionalExpression.GetIncreasedIndentation(cancellationToken);

            leadingTrivia = leadingTrivia.Insert(0, NewLine());

            return(ConditionalExpression(
                       conditionalExpression.Condition.WithoutTrailingTrivia(),
                       Token(leadingTrivia, SyntaxKind.QuestionToken, TriviaList(Space)),
                       conditionalExpression.WhenTrue.WithoutTrailingTrivia(),
                       Token(leadingTrivia, SyntaxKind.ColonToken, TriviaList(Space)),
                       conditionalExpression.WhenFalse.WithoutTrailingTrivia()));
        }
Example #19
0
        public Func <SyntaxGenerator, AttributeListSyntax, AttributeListSyntax> GetAddCommentAction(string comment)
        {
            Func <SyntaxGenerator, AttributeListSyntax, AttributeListSyntax> AddComment = (SyntaxGenerator syntaxGenerator, AttributeListSyntax node) =>
            {
                //TODO IS there possibility of NPE , if there are no Trivia or it always returns a node...
                SyntaxTriviaList currentTrivia = node.GetLeadingTrivia();
                currentTrivia = currentTrivia.Insert(0, SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, string.Format(Constants.CommentFormat, comment)));
                node          = node.WithLeadingTrivia(currentTrivia).NormalizeWhitespace();
                return(node);
            };

            return(AddComment);
        }
Example #20
0
        /// <summary>
        /// Extract the last indendation from the trivia passed.
        /// </summary>
        /// <param name="leadingTrivia"></param>
        /// <returns></returns>
        public static SyntaxTriviaList KeepLastLine(SyntaxTriviaList leadingTrivia)
        {
            SyntaxTriviaList triviaBuild = SyntaxTriviaList.Empty;

            foreach (SyntaxTrivia trivium in leadingTrivia.Reverse())
            {
                if (trivium.IsKind(SyntaxKind.WhitespaceTrivia))
                {
                    triviaBuild = triviaBuild.Insert(0, trivium);
                    break;
                }
            }
            return(triviaBuild);
        }
Example #21
0
        public Func <SyntaxGenerator, MethodDeclarationSyntax, MethodDeclarationSyntax> GetAddCommentAction(string comment, string dontUseCTAPrefix = null)
        {
            MethodDeclarationSyntax AddComment(SyntaxGenerator syntaxGenerator, MethodDeclarationSyntax node)
            {
                SyntaxTriviaList currentTrivia = node.GetLeadingTrivia();
                var commentFormat = !string.IsNullOrEmpty(dontUseCTAPrefix) ? Constants.CommentFormatBlank : Constants.CommentFormat;

                currentTrivia = currentTrivia.Insert(0, SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, string.Format(commentFormat, comment)));
                node          = node.WithLeadingTrivia(currentTrivia).NormalizeWhitespace();
                return(node);
            }

            return(AddComment);
        }
        /// <summary>
        /// Adds documentation header async.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="root">The root.</param>
        /// <param name="declarationSyntax">The declaration syntax.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A Document.</returns>
        private async Task <Document> AddDocumentationHeaderAsync(Document document, SyntaxNode root, ClassDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
        {
            SyntaxTriviaList leadingTrivia = declarationSyntax.GetLeadingTrivia();

            string comment = CommentHelper.CreateClassComment(declarationSyntax.Identifier.ValueText);
            DocumentationCommentTriviaSyntax commentTrivia = await Task.Run(() => DocumentationHeaderHelper.CreateOnlySummaryDocumentationCommentTrivia(comment), cancellationToken);

            SyntaxTriviaList       newLeadingTrivia = leadingTrivia.Insert(leadingTrivia.Count - 1, SyntaxFactory.Trivia(commentTrivia));
            ClassDeclarationSyntax newDeclaration   = declarationSyntax.WithLeadingTrivia(newLeadingTrivia);

            SyntaxNode newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);

            return(document.WithSyntaxRoot(newRoot));
        }
Example #23
0
        public static async Task <Document> RefactorAsync(
            Document document,
            StatementSyntax statement,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxTriviaList trailingTrivia = statement.GetTrailingTrivia();

            int index = trailingTrivia.IndexOf(SyntaxKind.EndOfLineTrivia);

            SyntaxTriviaList newTrailingTrivia = trailingTrivia.Insert(index, CSharpFactory.NewLineTrivia());

            StatementSyntax newStatement = statement.WithTrailingTrivia(newTrailingTrivia);

            return(await document.ReplaceNodeAsync(statement, newStatement, cancellationToken).ConfigureAwait(false));
        }
Example #24
0
        public static Task <Document> ToMultiLineAsync(
            Document document,
            BinaryExpressionSyntax condition,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxTriviaList leadingTrivia = condition.GetIncreasedIndentation(cancellationToken);

            leadingTrivia = leadingTrivia.Insert(0, NewLine());

            var rewriter = new BinaryExpressionToMultiLineRewriter(leadingTrivia);

            var newCondition = (ExpressionSyntax)rewriter.Visit(condition);

            return(document.ReplaceNodeAsync(condition, newCondition, cancellationToken));
        }
Example #25
0
        private static Task <Document> AddEmptyLineBeforeWhileInDoStatementAsync(
            Document document,
            StatementSyntax statement,
            CancellationToken cancellationToken = default)
        {
            SyntaxTriviaList trailingTrivia = statement.GetTrailingTrivia();

            int index = trailingTrivia.IndexOf(SyntaxKind.EndOfLineTrivia);

            SyntaxTriviaList newTrailingTrivia = trailingTrivia.Insert(index, CSharpFactory.NewLine());

            StatementSyntax newStatement = statement.WithTrailingTrivia(newTrailingTrivia);

            return(document.ReplaceNodeAsync(statement, newStatement, cancellationToken));
        }
Example #26
0
        /// <summary>
        /// Adds documentation header async.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="root">The root.</param>
        /// <param name="declarationSyntax">The declaration syntax.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A Document.</returns>
        private async Task <Document> AddDocumentationHeaderAsync(Document document, SyntaxNode root, FieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
        {
            SyntaxTriviaList leadingTrivia = declarationSyntax.GetLeadingTrivia();

            VariableDeclaratorSyntax field = declarationSyntax.DescendantNodes().OfType <VariableDeclaratorSyntax>().First();
            string comment = CommentHelper.CreateFieldComment(field.Identifier.ValueText);
            DocumentationCommentTriviaSyntax commentTrivia = await Task.Run(() => DocumentationHeaderHelper.CreateOnlySummaryDocumentationCommentTrivia(comment), cancellationToken);

            SyntaxTriviaList       newLeadingTrivia = leadingTrivia.Insert(leadingTrivia.Count - 1, SyntaxFactory.Trivia(commentTrivia));
            FieldDeclarationSyntax newDeclaration   = declarationSyntax.WithLeadingTrivia(newLeadingTrivia);

            SyntaxNode newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);

            return(document.WithSyntaxRoot(newRoot));
        }
Example #27
0
        public static Task <Document> AddEmptyLineAfterDirectiveAsync(
            Document document,
            DirectiveTriviaSyntax directiveTrivia,
            CancellationToken cancellationToken = default)
        {
            SyntaxTrivia     parentTrivia  = directiveTrivia.ParentTrivia;
            SyntaxToken      token         = parentTrivia.Token;
            SyntaxTriviaList leadingTrivia = token.LeadingTrivia;

            int index = leadingTrivia.IndexOf(parentTrivia);

            SyntaxTriviaList newLeadingTrivia = leadingTrivia.Insert(index + 1, DetermineEndOfLine(token));

            SyntaxToken newToken = token.WithLeadingTrivia(newLeadingTrivia);

            return(document.ReplaceTokenAsync(token, newToken, cancellationToken));
        }
        private static async Task <Document> AddEmptyLineAsync(
            Document document,
            StatementSyntax statement,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SyntaxTriviaList trailingTrivia = statement.GetTrailingTrivia();

            int index = trailingTrivia.IndexOf(SyntaxKind.EndOfLineTrivia);

            SyntaxTriviaList newTrailingTrivia = trailingTrivia.Insert(index, CSharpFactory.NewLineTrivia());

            StatementSyntax newStatement = statement.WithTrailingTrivia(newTrailingTrivia);

            SyntaxNode newRoot = root.ReplaceNode(statement, newStatement);

            return(document.WithSyntaxRoot(newRoot));
        }
        private static async Task <Document> FormatExpressionChainOnMultipleLinesAsync(
            Document document,
            MemberAccessExpressionSyntax expression,
            CancellationToken cancellationToken)
        {
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken);

            SyntaxTriviaList triviaList = expression.GetIndentTrivia().Add(SyntaxHelper.DefaultIndent);

            triviaList = triviaList.Insert(0, SyntaxHelper.NewLine);

            var rewriter = new ExpressionChainSyntaxRewriter(triviaList);

            SyntaxNode newNode = rewriter.Visit(expression)
                                 .WithAdditionalAnnotations(Formatter.Annotation);

            SyntaxNode newRoot = oldRoot.ReplaceNode(expression, newNode);

            return(document.WithSyntaxRoot(newRoot));
        }
Example #30
0
        /// <summary>
        /// Adds documentation header async.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="root">The root.</param>
        /// <param name="declarationSyntax">The declaration syntax.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A Document.</returns>
        private async Task <Document> AddDocumentationHeaderAsync(Document document, SyntaxNode root, PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
        {
            SyntaxTriviaList leadingTrivia = declarationSyntax.GetLeadingTrivia();

            bool isBoolean = false;

            if (declarationSyntax.Type.IsKind(SyntaxKind.PredefinedType))
            {
                isBoolean = ((PredefinedTypeSyntax)declarationSyntax.Type).Keyword.Kind() == SyntaxKind.BoolKeyword;
            }
            else if (declarationSyntax.Type.IsKind(SyntaxKind.NullableType))
            {
                var retrunType = ((NullableTypeSyntax)declarationSyntax.Type).ElementType as PredefinedTypeSyntax;
                isBoolean = retrunType?.Keyword.Kind() == SyntaxKind.BoolKeyword;
            }

            bool hasSetter = false;

            if (declarationSyntax.AccessorList != null && declarationSyntax.AccessorList.Accessors.Any(o => o.Kind() == SyntaxKind.SetAccessorDeclaration))
            {
                if (declarationSyntax.AccessorList.Accessors.First(o => o.Kind() == SyntaxKind.SetAccessorDeclaration).ChildTokens().Any(o => o.Kind() == SyntaxKind.PrivateKeyword || o.Kind() == SyntaxKind.InternalKeyword))
                {
                    // private set or internal set should consider as no set.
                    hasSetter = false;
                }
                else
                {
                    hasSetter = true;
                }
            }

            string propertyComment = CommentHelper.CreatePropertyComment(declarationSyntax.Identifier.ValueText, isBoolean, hasSetter);
            DocumentationCommentTriviaSyntax commentTrivia = await Task.Run(() => DocumentationHeaderHelper.CreateOnlySummaryDocumentationCommentTrivia(propertyComment), cancellationToken);

            SyntaxTriviaList          newLeadingTrivia = leadingTrivia.Insert(leadingTrivia.Count - 1, SyntaxFactory.Trivia(commentTrivia));
            PropertyDeclarationSyntax newDeclaration   = declarationSyntax.WithLeadingTrivia(newLeadingTrivia);

            SyntaxNode newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);

            return(document.WithSyntaxRoot(newRoot));
        }
        private SyntaxTriviaList RemoveIllegalHeadersFromMultilineComment(SyntaxTriviaList newTrivia, SyntaxTrivia trivia, string illegalHeader)
        {
            StringBuilder newTriviaString = new StringBuilder();
            bool commentHasMeaningfulInfo = false;
            bool removedIllegalHeaders = false;
            using (StringReader sr = new StringReader(trivia.ToFullString()))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    // If the current line contains the illegal header
                    if (line.IndexOf(illegalHeader, StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        // special care must be had to keep the /* and */ tokens.
                        if (line.TrimStart().StartsWith("/*"))
                        {
                            // Note: This will also cover the case where the comment is: /* illegalHeader */ as we remove the entire line (including the */).
                            newTriviaString.AppendLine("/*");
                        }
                        else if (line.TrimEnd().EndsWith("*/"))
                        {
                            newTriviaString.AppendLine("*/");
                        }
                        removedIllegalHeaders = true;
                    }
                    else
                    {
                        commentHasMeaningfulInfo |= CommentLineContainsMeaningfulIInformation(line);

                        newTriviaString.AppendLine(line);
                    }
                }
            }

            // We should not remove any comments if we don't have to.
            if (!removedIllegalHeaders)
            {
                return newTrivia;
            }

            // Remove the old trivia and replace it with the new trivia
            var index = newTrivia.IndexOf(trivia);
            newTrivia = RemoveTriviaAtIndex(newTrivia, index);

            if (commentHasMeaningfulInfo)
            {
                // we need to remove the original multiline comment and replace it with this new one.
                var newMultilineComment = SyntaxFactory.Comment(newTriviaString.ToString());
                newTrivia = newTrivia.Insert(index, newMultilineComment);
            }

            return newTrivia;
        }
Example #32
0
        private void DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxTriviaList list)
        {
            Assert.Equal(0, list.Count);

            var triviaD = SyntaxFactory.ParseLeadingTrivia("/*D*/")[0];
            var triviaE = SyntaxFactory.ParseLeadingTrivia("/*E*/")[0];

            var newList = list.Add(triviaD);
            Assert.Equal(1, newList.Count);
            Assert.Equal("/*D*/", newList.ToFullString());

            newList = list.AddRange(new[] { triviaD, triviaE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("/*D*//*E*/", newList.ToFullString());

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

            newList = list.InsertRange(0, new[] { triviaD, triviaE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("/*D*//*E*/", newList.ToFullString());

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

            Assert.Equal(-1, list.IndexOf(triviaD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, triviaD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, triviaD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { triviaD }));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { triviaD }));
            Assert.Throws<ArgumentException>(() => list.Replace(triviaD, triviaE));
            Assert.Throws<ArgumentException>(() => list.ReplaceRange(triviaD, new[] { triviaE }));
            Assert.Throws<ArgumentException>(() => list.Add(default(SyntaxTrivia)));
            Assert.Throws<ArgumentException>(() => list.Insert(0, default(SyntaxTrivia)));
            Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxTrivia>)null));
            Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxTrivia>)null));
        }