private static SyntaxTriviaList AddSingleLineComment(SyntaxTriviaList trivia, string text) { trivia = trivia.Add(Comment($"// {text}")); trivia = trivia.Add(CarriageReturnLineFeed); return(trivia.Add(CarriageReturnLineFeed)); }
static void setupFields() { setupBinaryOperators(); setupUnaryOperators(); syntaxTrivias = new SyntaxTriviaList(); syntaxTrivias.Add(SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "Mutation")); syntaxTrivias.Add(SyntaxFactory.EndOfLine("eof")); }
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) ); }
public static TNode AppendNewLine <TNode>(this TNode node, bool preserveExistingTrivia = true) where TNode : SyntaxNode { SyntaxTriviaList trivia = preserveExistingTrivia ? node.GetTrailingTrivia() : SyntaxFactory.TriviaList(); trivia = trivia.Add(SyntaxEx.EndOfLineTrivia); return(node.WithTrailingTrivia <TNode>(trivia)); }
private SyntaxTriviaList FixCommentWhitespace(SyntaxTriviaList textLines) { var changedLines = new SyntaxTriviaList(); bool skipNextNewline = false; foreach (var text in textLines) { if (skipNextNewline) { skipNextNewline = false; if (text.Kind() == SyntaxKind.EndOfLineTrivia) { continue; } } var removeTrivia = this.HasEmptyComment(text); if (!removeTrivia) { changedLines = changedLines.Add(text); } else { skipNextNewline = true; } } return changedLines; }
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 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)); }
internal static SyntaxTokenList TranslateTokenList(IEnumerable <SyntaxToken> ChildTokens) { var NewTokenList = new SyntaxTokenList(); foreach (SyntaxToken token in ChildTokens) { var NewLeadingTriviaList = new SyntaxTriviaList(); var NewTrailingTriviaList = new SyntaxTriviaList(); string TokenText = token.Text; string ValueText = token.ValueText; if (token.HasLeadingTrivia) { foreach (SyntaxTrivia t in token.LeadingTrivia) { if (t.IsKind(CS.SyntaxKind.DocumentationCommentExteriorTrivia)) { NewLeadingTriviaList = NewLeadingTriviaList.Add(VBFactory.DocumentationCommentExteriorTrivia(token.LeadingTrivia[0].ToString().Replace("///", "'''"))); if (!TokenText.StartsWith(" ")) { TokenText = " " + TokenText; ValueText = " " + ValueText; } } else { } } } var switchExpr = token.RawKind; switch (switchExpr) { case (int)CS.SyntaxKind.XmlTextLiteralToken: { NewTokenList = NewTokenList.Add(VBFactory.XmlTextLiteralToken(NewLeadingTriviaList, TokenText, ValueText, NewTrailingTriviaList)); break; } case (int)CS.SyntaxKind.XmlTextLiteralNewLineToken: { NewTokenList = NewTokenList.Add(VBFactory.XmlTextNewLine(text: Constants.vbCrLf, value: Constants.vbCrLf, NewLeadingTriviaList, NewTrailingTriviaList)); break; } case (int)CS.SyntaxKind.XmlEntityLiteralToken: { NewTokenList = NewTokenList.Add(VBFactory.XmlEntityLiteralToken(NewLeadingTriviaList, TokenText, ValueText, NewTrailingTriviaList)); break; } default: { break; } } } return(NewTokenList); }
/// <summary>Adds a new line at the end of a nodes leading trivia.</summary> /// <param name="node">The node whose leading trivia the new line should be added.</param> /// <param name="triviaSyntax">The structured tricia syntax to add.</param> /// <returns>The provided <paramref name="node"/> with a leading trivia including /// the original leading trivia and the provided <paramref name="triviaSyntax"/>.</returns> private static SyntaxNode AddLineToLeadingTrivia(SyntaxNode node, StructuredTriviaSyntax triviaSyntax) { SyntaxTriviaList currentLeadingTrivia = node.GetLeadingTrivia(); SyntaxTrivia newContentTrivia = SyntaxFactory.Trivia(triviaSyntax); SyntaxTrivia endOfLineTrivia = SyntaxFactory.EndOfLine(Environment.NewLine); SyntaxTriviaList newLeadingTrivia = currentLeadingTrivia.Add(newContentTrivia).Add(endOfLineTrivia); return(node.WithLeadingTrivia(newLeadingTrivia)); }
public static SyntaxTriviaList AddTrailingEndOfLineIfNotExist(this SyntaxTriviaList trivia) { if (trivia.Any(SyntaxKind.EndOfLineTrivia) == false) { return(trivia.Add(SyntaxFactory.EndOfLine(Environment.NewLine))); } return(trivia); }
/// <summary> /// Formats the specified <see cref="CompilationUnitSyntax"/> and returns its file string representation. /// </summary> /// <param name="syntax">The <see cref="CompilationUnitSyntax"/> to format.</param> /// <param name="rewriter">The <see cref="CSharpSyntaxRewriter"/> to use.</param> /// <returns>The formatted file string representation of the <paramref name="syntax"/>.</returns> internal static string ToFileString(this CompilationUnitSyntax syntax, CSharpSyntaxRewriter rewriter = null) { SyntaxTriviaList header = SyntaxFactory.ParseLeadingTrivia(string.Format(Strings.FileHeader, Environment.Version)); if (syntax.Usings.Count > 0 || syntax.Members.Count > 0) { header = header.Add(SyntaxFactory.CarriageReturnLineFeed).Add(SyntaxFactory.CarriageReturnLineFeed); } return(syntax.NormalizeWhitespace().Accept(rewriter ?? new Rewriter()).WithLeadingTrivia(header).WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed).ToFullString()); }
private static void RemoveWhiteSpacesAndLineBreaks(ref SyntaxTriviaList trivia) { var hasWhiteSpaces = trivia.Any(x => x.IsKind(SyntaxKind.WhitespaceTrivia)); RemoveLineBreaks(ref trivia); RemoveWhiteSpaces(ref trivia); if (hasWhiteSpaces) { trivia = trivia.Add(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " ")); } }
private void ProcessAdjacentTokens(SyntaxToken previous, SyntaxToken next) { var triviaBuffer = this.cachedTriviaBuffer; triviaBuffer.Clear(); foreach (var previousTrailing in previous.TrailingTrivia) { this.BufferTrivia(triviaBuffer, previousTrailing); } foreach (var nextLeading in next.LeadingTrivia) { this.BufferTrivia(triviaBuffer, nextLeading); } var spacingPolicy = GetSpacingPolicy(previous, next); // check for trailing trivia. A single line comment is ok; everything else is not var hasTrailingTrivia = triviaBuffer.Count > 0 && ( triviaBuffer[0].IsKind(SyntaxKind.SingleLineCommentTrivia) || (triviaBuffer[0].IsKind(SyntaxKind.MultiLineCommentTrivia) && triviaBuffer[0].ToFullString().IndexOf('\n') < 0) ); if (hasTrailingTrivia) { this.remappedTrailingTrivia.Add(previous, SingleWhitespaceList.Add(triviaBuffer[0])); triviaBuffer.RemoveAt(0); // TODO having a trailing comment like this should block the ban newlines policy, but at the same time { and ( // shouldn't even be allowed trailing comments... } else if (previous.TrailingTrivia.Any()) { this.remappedTrailingTrivia.Add(previous, SyntaxTriviaList.Empty); } // now calculate leading trivia // get trivial into canonical form this.MergeSingleLineComments(triviaBuffer); this.MergeNewLines(triviaBuffer, spacingPolicy, hadTrailingTrivia: hasTrailingTrivia); // split into annotation and trailing SyntaxAnnotation multiLineAnnotation; SyntaxTriviaList leadingTrivia; this.SplitOutMultiLineTriviaAndAddSpacing(triviaBuffer, spacingPolicy, out multiLineAnnotation, out leadingTrivia); this.remappedLeadingTriviaAndAnnotation.Add( next, new KeyValuePair <SyntaxTriviaList, SyntaxAnnotation>(leadingTrivia, multiLineAnnotation) ); }
private SyntaxTriviaList FixCommentWhitespace(SyntaxTriviaList textLines) { var changedLines = new SyntaxTriviaList(); foreach (var text in textLines) { var fixedText = this.FixCommentWhitespaceForLine(text); changedLines = changedLines.Add(fixedText); } return changedLines; }
public Func <SyntaxGenerator, InvocationExpressionSyntax, InvocationExpressionSyntax> GetAddCommentAction(string comment) { Func <SyntaxGenerator, InvocationExpressionSyntax, InvocationExpressionSyntax> AddComment = (SyntaxGenerator syntaxGenerator, InvocationExpressionSyntax node) => { SyntaxTriviaList currentTrivia = node.GetLeadingTrivia(); currentTrivia = currentTrivia.Add(SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, string.Format(Constants.CommentFormat, comment))); node = node.WithLeadingTrivia(currentTrivia).NormalizeWhitespace(); return(node); }; return(AddComment); }
internal T WithPrependedLeadingTrivia <T>(T node, SyntaxTriviaList trivia) where T : SyntaxNode { if (trivia.Count == 0) { return(node); } if (trivia.Last().IsKind(VB.SyntaxKind.CommentTrivia)) { trivia = trivia.Add(global::VisualBasicSyntaxFactory.VBEOLTrivia); } return(node.WithLeadingTrivia(trivia.Concat(node.GetLeadingTrivia()))); }
public Func <SyntaxGenerator, SyntaxNode, SyntaxNode> GetAddCommentAction(string comment) { SyntaxNode AddComment(SyntaxGenerator syntaxGenerator, SyntaxNode node) { SyntaxTriviaList currentTrivia = node.GetLeadingTrivia(); currentTrivia = currentTrivia.Add(SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, string.Format(Constants.CommentFormat, comment))); node = node.WithLeadingTrivia(currentTrivia).NormalizeWhitespace(); return(node); } return(AddComment); }
public Func <SyntaxGenerator, ClassDeclarationSyntax, ClassDeclarationSyntax> GetAddCommentAction(string comment) { Func <SyntaxGenerator, ClassDeclarationSyntax, ClassDeclarationSyntax> AddComment = (SyntaxGenerator syntaxGenerator, ClassDeclarationSyntax node) => { SyntaxTriviaList currentTrivia = node.GetLeadingTrivia(); //TODO see if this will lead NPE currentTrivia = currentTrivia.Add(SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, string.Format(Constants.CommentFormat, comment))); node = node.WithLeadingTrivia(currentTrivia).NormalizeWhitespace(); return(node); }; return(AddComment); }
static SyntaxTriviaList BuildCommentTrivia(IEnumerable<string> headerComments, string newLineText) { SyntaxTrivia newLineTrivia = SyntaxFactory.EndOfLine(newLineText); var commentTrivia = new SyntaxTriviaList(); var hasHeaderComments = false; foreach (string headerComment in headerComments) { hasHeaderComments = true; commentTrivia = commentTrivia.Add(SyntaxFactory.Comment(CommentPrefix + headerComment)); commentTrivia = commentTrivia.Add(newLineTrivia); } if (hasHeaderComments) { // Add an extra empty line below the header comments, if present. commentTrivia = commentTrivia.Add(newLineTrivia); } return commentTrivia; }
private static SyntaxTriviaList RemoveOrComment(SyntaxTriviaList leadingTrivia) { SyntaxTriviaList trivia = SyntaxTriviaList.Empty; foreach (SyntaxTrivia trivium in leadingTrivia) { if (!(trivium.IsKind(SyntaxKind.SingleLineCommentTrivia) && String.Equals(trivium.ToString().Replace("//", "").Trim(), "[OR]", StringComparison.OrdinalIgnoreCase))) { trivia = trivia.Add(trivium); } } return(trivia); }
private SyntaxTree getDebugCode(SyntaxTree tree) { SyntaxTree newTree = null; SyntaxTriviaList spaceTrivias = new SyntaxTriviaList(); SyntaxTrivia space = SyntaxFactory.Space; spaceTrivias = spaceTrivias.Add(space); SyntaxTriviaList endLineTrivias = new SyntaxTriviaList(); SyntaxTrivia endline = SyntaxFactory.CarriageReturnLineFeed; endLineTrivias = endLineTrivias.Add(endline); IdentifierNameSyntax debugIdentifier = SyntaxFactory.IdentifierName(SESCriptBuilderInstance.DebugName).WithLeadingTrivia(spaceTrivias); IfDirectiveTriviaSyntax ifOpen = SyntaxFactory.IfDirectiveTrivia(debugIdentifier, false, false, false).WithTrailingTrivia(endLineTrivias); SyntaxTrivia ifOpenTrivia = SyntaxFactory.Trivia(ifOpen); SyntaxTriviaList ifOpenList = new SyntaxTriviaList(); ifOpenList = ifOpenList.Add(ifOpenTrivia); EndIfDirectiveTriviaSyntax ifClose = SyntaxFactory.EndIfDirectiveTrivia(false).WithTrailingTrivia(endLineTrivias).WithLeadingTrivia(endLineTrivias); SyntaxTrivia ifCloseTrivia = SyntaxFactory.Trivia(ifClose); SyntaxTriviaList ifCloseList = new SyntaxTriviaList(); ifCloseList = ifCloseList.Add(ifCloseTrivia); CompilationUnitSyntax root = tree.GetCompilationUnitRoot(); // add begin and end ifs root = root.WithLeadingTrivia(ifOpenList); root = root.WithTrailingTrivia(ifCloseList); ClassDeclarationSyntax mainClass = this.getTopLevelClasses(root.SyntaxTree).First(); SyntaxToken token = mainClass.OpenBraceToken; SyntaxToken newToken = token.WithTrailingTrivia(ifCloseList); root = root.ReplaceToken(token, newToken); mainClass = this.getTopLevelClasses(root.SyntaxTree).First(); token = mainClass.CloseBraceToken; newToken = token.WithLeadingTrivia(ifOpenList); root = root.ReplaceToken(token, newToken); newTree = root.SyntaxTree; return(newTree); }
private static IdentifierNameSyntax PadMemberAccess( SimpleLambdaExpressionSyntax node, IdentifierNameSyntax memberAccess) { // We want to make the new span var originalSpan = node.GetLocation().GetMappedLineSpan(); var charactersToExclude = memberAccess.Identifier.Text.Length; var triviaList = new SyntaxTriviaList(); // Go through each token and // 1. Append leading trivia // 2. Append the same number of whitespace as the length of the token text // 3. Append trailing trivia foreach (var token in node.DescendantTokens()) { if (token.HasLeadingTrivia) { triviaList = triviaList.AddRange(token.LeadingTrivia); } // Need to exclude the length of the member name from the padding. var padding = token.Text.Length; if (padding > charactersToExclude) { padding -= charactersToExclude; charactersToExclude = 0; } else { charactersToExclude -= padding; padding = 0; } if (padding > 0) { triviaList = triviaList.Add(SyntaxFactory.Whitespace(new string(' ', padding))); } if (token.HasTrailingTrivia) { triviaList = triviaList.AddRange(token.TrailingTrivia); } } return(memberAccess .WithLeadingTrivia(node.GetLeadingTrivia()) .WithTrailingTrivia(triviaList)); }
public Func <SyntaxGenerator, ClassDeclarationSyntax, ClassDeclarationSyntax> GetAddCommentAction(string comment, string dontUseCTAPrefix = null) { ClassDeclarationSyntax AddComment(SyntaxGenerator syntaxGenerator, ClassDeclarationSyntax node) { SyntaxTriviaList currentTrivia = node.GetLeadingTrivia(); //TODO see if this will lead NPE var commentFormat = dontUseCTAPrefix != null ? Constants.CommentFormatBlank : Constants.CommentFormat; currentTrivia = currentTrivia.Add(SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, string.Format(commentFormat, comment))); node = node.WithLeadingTrivia(currentTrivia).NormalizeWhitespace(); return(node); } return(AddComment); }
private static Task <Document> RemoveBracesAsync( Document document, BlockSyntax block, CancellationToken cancellationToken) { var switchSection = (SwitchSectionSyntax)block.Parent; SyntaxList <StatementSyntax> statements = block.Statements; SyntaxTriviaList leadingTrivia = block.OpenBraceToken.LeadingTrivia; leadingTrivia = AddTriviaIfNecessary(leadingTrivia, block.OpenBraceToken.TrailingTrivia); leadingTrivia = AddTriviaIfNecessary(leadingTrivia, statements[0].GetLeadingTrivia()); SyntaxTriviaList trailingTrivia = statements.Last().GetTrailingTrivia(); trailingTrivia = AddTriviaIfNecessary(trailingTrivia, block.CloseBraceToken.LeadingTrivia); trailingTrivia = AddTriviaIfNecessary(trailingTrivia, block.CloseBraceToken.TrailingTrivia); trailingTrivia = trailingTrivia.TrimEnd().Add(CSharpFactory.NewLine()); var switchStatement = (SwitchStatementSyntax)switchSection.Parent; if (!switchStatement.Sections.IsLast(switchSection)) { trailingTrivia = trailingTrivia.Add(CSharpFactory.NewLine()); } SyntaxList <StatementSyntax> newStatements = statements.ReplaceAt(0, statements[0].WithLeadingTrivia(leadingTrivia)); newStatements = newStatements.ReplaceAt(newStatements.Count - 1, newStatements.Last().WithTrailingTrivia(trailingTrivia)); SwitchSectionSyntax newSwitchSection = switchSection .WithStatements(newStatements) .WithFormatterAnnotation(); return(document.ReplaceNodeAsync(switchSection, newSwitchSection, cancellationToken)); SyntaxTriviaList AddTriviaIfNecessary(SyntaxTriviaList trivia, SyntaxTriviaList triviaToAdd) { if (triviaToAdd.Any(f => f.IsKind(SyntaxKind.SingleLineCommentTrivia))) { trivia = trivia.AddRange(triviaToAdd); } return(trivia); } }
public override VB.VisualBasicSyntaxNode VisitXmlElement(CSS.XmlElementSyntax node) { var Content = new SyntaxList <VBS.XmlNodeSyntax>(); VBS.XmlElementStartTagSyntax StartTag = (VBS.XmlElementStartTagSyntax)node.StartTag.Accept(this); bool NoEndTag = string.IsNullOrWhiteSpace(node.EndTag.Name.LocalName.ValueText); var EndTag = NoEndTag ? VBFactory.XmlElementEndTag(((VBS.XmlNameSyntax)StartTag.Name)) : VBFactory.XmlElementEndTag((VBS.XmlNameSyntax)node.EndTag.Name.Accept(this)); try { for (int i = 0, loopTo = node.Content.Count - 1; i <= loopTo; i++) { var C = node.Content[i]; VBS.XmlNodeSyntax Node1 = (VBS.XmlNodeSyntax)C.Accept(this); if (NoEndTag) { var LastToken = Node1.GetLastToken(); if (LastToken.ValueText.IsNewLine()) { Node1 = Node1.ReplaceToken(LastToken, default(SyntaxToken)); } } Content = Content.Add(Node1); } if (node.EndTag?.HasLeadingTrivia == true && node.EndTag.GetLeadingTrivia()[0].IsKind(CS.SyntaxKind.DocumentationCommentExteriorTrivia) == true) { var NewLeadingTriviaList = new SyntaxTriviaList(); NewLeadingTriviaList = NewLeadingTriviaList.Add(VBFactory.DocumentationCommentExteriorTrivia(node.EndTag.GetLeadingTrivia()[0].ToString().Replace("///", "'''"))); var NewTokenList = new SyntaxTokenList(); NewTokenList = NewTokenList.Add(VBFactory.XmlTextLiteralToken(NewLeadingTriviaList, " ", " ", new SyntaxTriviaList())); Content = Content.Add(VBFactory.XmlText(NewTokenList)); EndTag = EndTag.WithoutLeadingTrivia(); } } catch (OperationCanceledException ex) { throw; } catch (Exception ex) { } var XmlElement = VBFactory.XmlElement(StartTag, Content, EndTag); return(XmlElement); }
private void AddComments() { StringBuilder sb = new StringBuilder("Please add the correponding references."); if (_addNugetReference.Count > 0) { sb.Append("Add the following nuget package references "); sb.Append(string.Join(",", _addNugetReference)); } sb.Append("."); sb.Append(string.Join(".", ServerConfigTemplates.AdditonalComments)); SyntaxTriviaList currentTrivia = _startupRoot.GetLeadingTrivia(); currentTrivia = currentTrivia.Add(SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, string.Format(Constants.CommentFormat, sb.ToString()))); _startupRoot = _startupRoot.WithLeadingTrivia(currentTrivia).NormalizeWhitespace(); }
private static BlockSyntax FormatBlock(BlockSyntax block, SyntaxTriviaList startTrivia, bool useTabs, int tabSize) { var statementTrivia = useTabs ? startTrivia.Add(SyntaxFactory.Tab) : startTrivia.AddRange(Enumerable.Repeat(SyntaxFactory.Space, tabSize)); var prevToken = block.OpenBraceToken.GetPreviousToken(); var newBlock = block.Update( block.OpenBraceToken .WithLeadingTrivia(startTrivia) .WithTrailingTrivia(block.OpenBraceToken.TrailingTrivia.AddTrailingEndOfLineIfNotExist()), SyntaxFactory.List(block.Statements.Select(st => IndentationHelper.FormatNodeRecursive(st, statementTrivia, useTabs, tabSize).WithTrailingTrivia(st.GetTrailingTrivia().AddTrailingEndOfLineIfNotExist()))), block.CloseBraceToken.WithLeadingTrivia(startTrivia)); if (prevToken != null && prevToken.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia) == false) { return(newBlock = newBlock.WithLeadingTrivia(newBlock.GetLeadingTrivia().AddLeadingEndOfLineIfNotExist())); } return(newBlock); }
public override SyntaxNode VisitBlock(BlockSyntax node) { var newNode = base.VisitBlock(node); node = newNode as BlockSyntax; if (node == null) { return newNode; } var triviaList = node.OpenBraceToken.GetNextToken().LeadingTrivia; var newList = new SyntaxTriviaList(); foreach (var trivia in triviaList) { if (trivia.Kind() != SyntaxKind.EndOfLineTrivia) { newList.Add(trivia); } } return node.WithLeadingTrivia(newList); }
/// <summary> /// Applies formatting to the specified syntax nod. /// </summary> /// <param name="node">The syntax node to format.</param> protected virtual SyntaxNode Apply(SyntaxNode node) { if (node.GetTrailingTrivia().FullSpan.Length == 0) { SyntaxTriviaList trivia = SyntaxFactory.TriviaList(SyntaxFactory.CarriageReturnLineFeed); foreach (SyntaxTrivia syntaxTrivia in node.GetLeadingTrivia().Reverse()) { if (syntaxTrivia.IsKind(SyntaxKind.WhitespaceTrivia)) { trivia = trivia.Add(syntaxTrivia); } else { break; } } node = node.WithTrailingTrivia(trivia); } return(node); }
internal static void AddItemToCollectionInitializer(this DocumentEditor editor, ObjectCreationExpressionSyntax objectCreation, ExpressionSyntax expression, SyntaxTriviaList trivia) { if (objectCreation.Initializer != null || trivia.Any(SyntaxKind.SingleLineCommentTrivia)) { editor.ReplaceNode(objectCreation, (x, _) => ComputeReplacement(x)); SyntaxNode ComputeReplacement(SyntaxNode x) { var oc = ((ObjectCreationExpressionSyntax)x).RemoveEmptyArgumentList(); if (oc.Initializer != null && oc.Initializer.Expressions.Count > 0) { var last = oc.Initializer.Expressions.Last(); var updatedExpressions = oc.Initializer.Expressions .Remove(last) .Add(last.WithoutTrailingTrivia()) .GetWithSeparators() .Add(SyntaxFactory.Token(SyntaxKind.CommaToken) .WithTrailingTrivia(last.GetTrailingTrivia())) .Add(expression.WithoutTrailingTrivia()) .Add(SyntaxFactory.Token(SyntaxKind.CommaToken) .WithTrailingTrivia(trivia)); return(oc.WithInitializer( SyntaxFactory.InitializerExpression( SyntaxKind.CollectionInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>(updatedExpressions)) .WithOpenBraceToken( SyntaxFactory.Token(SyntaxKind.OpenBraceToken) .WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed))) .WithAdditionalAnnotations(Formatter.Annotation)); } else { var updatedExpressions = SyntaxFactory.NodeOrTokenList( expression.WithoutTrailingTrivia(), SyntaxFactory.Token(SyntaxKind.CommaToken) .WithTrailingTrivia(trivia.Add(SyntaxFactory.ElasticCarriageReturnLineFeed))); return(oc.WithInitializer( SyntaxFactory.InitializerExpression( SyntaxKind.CollectionInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>(updatedExpressions)) .WithOpenBraceToken( SyntaxFactory.Token(SyntaxKind.OpenBraceToken) .WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)))); } } } else { editor.ReplaceNode(objectCreation, (x, _) => ComputeReplacement(x)); SyntaxNode ComputeReplacement(SyntaxNode x) { return(((ObjectCreationExpressionSyntax)x).RemoveEmptyArgumentList() .WithInitializer( SyntaxFactory.InitializerExpression( SyntaxKind.CollectionInitializerExpression, SyntaxFactory .SingletonSeparatedList(expression)))); } } }
private static XmlElementSyntax TrimWhitespaceContent(XmlElementSyntax paragraph, out SyntaxList <XmlNodeSyntax> leadingWhitespaceContent, out SyntaxList <XmlNodeSyntax> trailingWhitespaceContent) { SyntaxList <XmlNodeSyntax> completeContent = XmlSyntaxFactory.List(paragraph.Content.SelectMany(ExpandTextNodes).ToArray()); leadingWhitespaceContent = XmlSyntaxFactory.List(completeContent.TakeWhile(x => XmlCommentHelper.IsConsideredEmpty(x)).ToArray()); trailingWhitespaceContent = XmlSyntaxFactory.List(completeContent.Skip(leadingWhitespaceContent.Count).Reverse().TakeWhile(x => XmlCommentHelper.IsConsideredEmpty(x)).Reverse().ToArray()); SyntaxList <XmlNodeSyntax> trimmedContent = XmlSyntaxFactory.List(completeContent.Skip(leadingWhitespaceContent.Count).Take(completeContent.Count - leadingWhitespaceContent.Count - trailingWhitespaceContent.Count).ToArray()); SyntaxTriviaList leadingTrivia = SyntaxFactory.TriviaList(); SyntaxTriviaList trailingTrivia = SyntaxFactory.TriviaList(); if (trimmedContent.Any()) { leadingTrivia = trimmedContent[0].GetLeadingTrivia(); trailingTrivia = trimmedContent.Last().GetTrailingTrivia(); trimmedContent = trimmedContent.Replace(trimmedContent[0], trimmedContent[0].WithoutLeadingTrivia()); trimmedContent = trimmedContent.Replace(trimmedContent.Last(), trimmedContent.Last().WithoutTrailingTrivia()); } else { leadingTrivia = SyntaxFactory.TriviaList(); trailingTrivia = SyntaxFactory.TriviaList(); } XmlElementSyntax result = paragraph; if (leadingWhitespaceContent.Any()) { var first = leadingWhitespaceContent[0]; var newFirst = first.WithLeadingTrivia(first.GetLeadingTrivia().InsertRange(0, paragraph.GetLeadingTrivia())); leadingWhitespaceContent = leadingWhitespaceContent.Replace(first, newFirst); } else { leadingTrivia = leadingTrivia.InsertRange(0, result.GetLeadingTrivia()); } if (trailingWhitespaceContent.Any()) { var last = trailingWhitespaceContent.Last(); var newLast = last.WithLeadingTrivia(last.GetLeadingTrivia().AddRange(paragraph.GetTrailingTrivia())); trailingWhitespaceContent = trailingWhitespaceContent.Replace(last, newLast); } else { trailingTrivia = trailingTrivia.AddRange(result.GetTrailingTrivia()); } if (trimmedContent.FirstOrDefault() is XmlTextSyntax firstTextNode && firstTextNode.TextTokens.Any()) { SyntaxToken firstTextToken = firstTextNode.TextTokens[0]; string leadingWhitespace = new(firstTextToken.Text.Cast <char>().TakeWhile(char.IsWhiteSpace).ToArray()); if (leadingWhitespace.Length > 0) { SyntaxToken newFirstTextToken = XmlSyntaxFactory.TextLiteral(firstTextToken.Text.Substring(leadingWhitespace.Length)).WithTriviaFrom(firstTextToken); XmlTextSyntax newFirstTextNode = firstTextNode.WithTextTokens(firstTextNode.TextTokens.Replace(firstTextToken, newFirstTextToken)); trimmedContent = trimmedContent.Replace(firstTextNode, newFirstTextNode); leadingTrivia = leadingTrivia.Add(SyntaxFactory.Whitespace(leadingWhitespace)); } } if (trimmedContent.LastOrDefault() is XmlTextSyntax lastTextNode && lastTextNode.TextTokens.Any()) { SyntaxToken lastTextToken = lastTextNode.TextTokens.Last(); string trailingWhitespace = new(lastTextToken.Text.Cast <char>().Reverse().TakeWhile(char.IsWhiteSpace).Reverse().ToArray()); if (trailingWhitespace.Length > 0) { SyntaxToken newLastTextToken = XmlSyntaxFactory.TextLiteral(lastTextToken.Text.Substring(0, lastTextToken.Text.Length - trailingWhitespace.Length)).WithTriviaFrom(lastTextToken); XmlTextSyntax newLastTextNode = lastTextNode.WithTextTokens(lastTextNode.TextTokens.Replace(lastTextToken, newLastTextToken)); trimmedContent = trimmedContent.Replace(lastTextNode, newLastTextNode); trailingTrivia = trailingTrivia.Insert(0, SyntaxFactory.Whitespace(trailingWhitespace)); } } return(result.WithContent(trimmedContent) .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(trailingTrivia)); }
IfStatementSyntax GetNewIF(IfStatementSyntax orginalIFnode, StatementSyntax singleStatementInsideIf) { var closeParenTrivia = orginalIFnode.CloseParenToken.WithoutWhitespaceTrivia(); var trailingTriviaList = new SyntaxTriviaList() .AddRange(closeParenTrivia.TrailingTrivia.Where(t => t.IsWhitespaceTrivia() == false)) .AddRange(singleStatementInsideIf.GetTrailingTrivia().Where(t => t.IsWhitespaceTrivia() == false)); if (singleStatementInsideIf != orginalIFnode.Statement) { trailingTriviaList = trailingTriviaList.AddRange(orginalIFnode.Statement.GetTrailingTrivia().Where(t => t.IsWhitespaceTrivia() == false)); } trailingTriviaList = trailingTriviaList.Add(_endOfLineTrivia); var newIf = orginalIFnode .WithIfKeyword(orginalIFnode.IfKeyword.WithTrailingTrivia(SyntaxFactory.Space)) .WithOpenParenToken(orginalIFnode.OpenParenToken.WithoutWhitespaceTrivia()) .WithCloseParenToken(SyntaxTokenExtensions.WithoutTrivia(closeParenTrivia)) .WithCondition(orginalIFnode.Condition.WithoutWhitespaceTrivia()) .WithStatement( singleStatementInsideIf .WithLeadingTrivia(SyntaxFactory.Space) .WithTrailingTrivia(trailingTriviaList) ); if (singleStatementInsideIf is ReturnStatementSyntax returnStatement) { if ( (returnStatement.Expression == null && newIf.WithElse(null).Span.Length <= 2 * MAX_IF_LINE_LENGTH) || ( newIf.WithElse(null).Span.Length <= MAX_IF_LINE_LENGTH && (returnStatement.Expression is LiteralExpressionSyntax || returnStatement.Expression.Span.Length <= MAX_RETURN_STATEMENT_LENGTH) ) ) { return(newIf); } if (singleStatementInsideIf.WithoutTrivia().DescendantTrivia().Any(t => t.IsKind(SyntaxKind.EndOfLineTrivia))) { return(orginalIFnode); } if (newIf.WithElse(null).WithoutTrivia().Span.Length <= MAX_IF_LINE_LENGTH) { return(newIf); } return(orginalIFnode); } if (singleStatementInsideIf.WithoutTrivia().DescendantTrivia().Any(t => t.IsKind(SyntaxKind.EndOfLineTrivia))) { return(orginalIFnode); } if (newIf.WithElse(null).Span.Length > MAX_IF_LINE_LENGTH) { return(orginalIFnode); } return(newIf); }
PropertyDeclarationSyntax ConvertProperty(PropertyDeclarationSyntax propertyDeclaration, FieldDeclarationSyntax relatedField) { var leadingList = new SyntaxTriviaList(); if (relatedField.Declaration.Variables.Count == 1) { leadingList = leadingList.AddRange(relatedField.GetLeadingTrivia()); } var propertyDeclaration_GetLeadingTrivia = propertyDeclaration.GetLeadingTrivia(); if (leadingList.Any() && propertyDeclaration_GetLeadingTrivia.First().IsKind(SyntaxKind.EndOfLineTrivia) == false) { var endOfLine = relatedField.GetLeadingTrivia().FirstOrDefault(x => x.IsKind(SyntaxKind.EndOfLineTrivia)); if (endOfLine != null) { leadingList = leadingList.Add(endOfLine); } } leadingList = leadingList.AddRange(propertyDeclaration.GetLeadingTrivia()); var getNode = propertyDeclaration.AccessorList.Accessors.FirstOrDefault(x => x.Keyword.IsKind(SyntaxKind.GetKeyword)); var setNode = propertyDeclaration.AccessorList.Accessors.FirstOrDefault(x => x.Keyword.IsKind(SyntaxKind.SetKeyword)); propertyDeclaration = propertyDeclaration .WithAccessorList ( propertyDeclaration.AccessorList.WithAccessors( new SyntaxList <AccessorDeclarationSyntax>() .Add( getNode .WithBody(null) .WithTrailingTrivia() .WithSemicolonToken( SyntaxFactory.ParseToken(";") .WithTrailingTrivia(SyntaxFactory.Space) ) .WithLeadingTrivia(SyntaxFactory.Space) ) .Add( setNode .WithBody(null) .WithTrailingTrivia() .WithSemicolonToken( SyntaxFactory.ParseToken(";") .WithTrailingTrivia(SyntaxFactory.Space) ) .WithLeadingTrivia(SyntaxFactory.Space) ) ) .WithOpenBraceToken(propertyDeclaration.AccessorList.OpenBraceToken.WithLeadingTrivia().WithTrailingTrivia()) .WithCloseBraceToken(propertyDeclaration.AccessorList.CloseBraceToken.WithLeadingTrivia()) ) .WithIdentifier(propertyDeclaration.Identifier.WithTrailingTrivia(SyntaxFactory.Space)) .WithLeadingTrivia(leadingList); return(propertyDeclaration); }
public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node) { if (node.ToString().Length < 110) { return(base.VisitExpressionStatement(node)); } var m = node.Expression; List <SyntaxToken> rewritableToken = new List <SyntaxToken>(); var trivia = new SyntaxTriviaList(SyntaxFactory.EndOfLine("\n")); trivia = trivia.AddRange(node.GetLeadingTrivia().Reverse() .TakeWhile(x => !x.IsKind(SyntaxKind.EndOfLineTrivia))); trivia = trivia.Add(SyntaxFactory.Tab); var newExpression = SyntaxFactory.ParseExpression(""); while (m != null && m.ChildNodes().Any()) { var m2 = m.ChildNodes(); if (m2.FirstOrDefault() is MemberAccessExpressionSyntax && m2.LastOrDefault() is ArgumentListSyntax) { var methodName = m2.FirstOrDefault().As <MemberAccessExpressionSyntax>(); var arguments = m2.LastOrDefault().As <ArgumentListSyntax>(); m = m2.FirstOrDefault().As <MemberAccessExpressionSyntax>()?.Expression; if (newExpression.ToString() == "") { newExpression = SyntaxFactory.InvocationExpression(methodName.Name, arguments) .WithoutTrailingTrivia(); } else { newExpression = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.InvocationExpression(methodName.Name, arguments).WithoutTrailingTrivia(), SyntaxFactory.Token(SyntaxKind.DotToken).WithLeadingTrivia(trivia), SyntaxFactory.IdentifierName(newExpression.ToString())); } } else if (m2.FirstOrDefault() is IdentifierNameSyntax && m2.LastOrDefault() is ArgumentListSyntax) { var identifierName = m2.FirstOrDefault() as IdentifierNameSyntax; var arguments = m2.LastOrDefault() as ArgumentListSyntax; m = null; if (newExpression.ToString() == "") { newExpression = SyntaxFactory.InvocationExpression(identifierName, arguments).WithoutTrailingTrivia(); } else { newExpression = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.InvocationExpression(identifierName.WithoutTrailingTrivia(), arguments.WithoutTrailingTrivia()), SyntaxFactory.Token(SyntaxKind.DotToken).WithLeadingTrivia(trivia), SyntaxFactory.IdentifierName(newExpression.ToString())); } } else { if (newExpression.ToString() == "") { newExpression = m.WithoutTrailingTrivia(); } else { newExpression = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, m.WithoutTrailingTrivia(), SyntaxFactory.Token(SyntaxKind.DotToken).WithLeadingTrivia(trivia), SyntaxFactory.IdentifierName(newExpression.ToString())); } m = null; } } if (m != null) { newExpression = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, m, SyntaxFactory.IdentifierName(newExpression.ToString())); } return(SyntaxFactory.ExpressionStatement(newExpression) .WithLeadingTrivia(node.GetLeadingTrivia()) .WithTrailingTrivia(node.GetTrailingTrivia())); }
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)); }