private bool IsBeginningOrEndOfDocumentComment(SyntaxTrivia trivia) { var currentParent = trivia.Token.Parent; while (currentParent != null) { if (currentParent.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia || currentParent.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia) { if (trivia.Span.End == currentParent.SpanStart || trivia.Span.End == currentParent.Span.End) { return true; } else { return false; } } currentParent = currentParent.Parent; } return false; }
private IEnumerable<OutliningSpan> GetRegions(SyntaxTree syntaxTree, SyntaxTrivia trivia) { var outliner = new DisabledTextTriviaOutliner(); var spans = new List<OutliningSpan>(); outliner.CollectOutliningSpans(syntaxTree, trivia, spans, CancellationToken.None); return spans; }
private static bool IsComment(SyntaxTrivia trivia) { return trivia.IsKind(SyntaxKind.SingleLineCommentTrivia) || trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) || trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia) || trivia.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia); }
private bool NeedsSpaceAdding(SyntaxTrivia trivia) { if (trivia.Kind != SyntaxKind.SingleLineCommentTrivia) { return false; } var text = trivia.ToFullString(); if (!text.StartsWith("//")) { return false; } if (text.StartsWith("///") || text.StartsWith("////")) { return false; } if (text.Length >= 3 && text[2] != ' ') { return true; } if (text.Length >= 4 && text[2] == ' ' && text[3] == ' ') { return true; } return false; }
public virtual void VisitTrivia(SyntaxTrivia trivia) { if (this.Depth >= SyntaxWalkerDepth.StructuredTrivia && trivia.HasStructure) { this.Visit((CSharpSyntaxNode)trivia.GetStructure()); } }
public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia) { if (trivia.Kind() == SyntaxKind.WhitespaceTrivia || trivia.Kind() == SyntaxKind.EndOfLineTrivia) return SyntaxTrivia(SyntaxKind.WhitespaceTrivia, string.Empty); return base.VisitTrivia(trivia); }
public override void VisitTrivia(SyntaxTrivia trivia) { if (TriviaPredicate != null && TriviaAction != null && TriviaPredicate(trivia)) { TriviaAction(trivia); } }
public override void VisitTrivia(SyntaxTrivia trivia) { if (trivia.Kind != SyntaxKind.DocumentationCommentExteriorTrivia) { arg.Append(trivia.ToString()); } }
public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia) { if (trivia.Kind() == SyntaxKind.RegionDirectiveTrivia) { if (trivia == _region) { _nests = 0; return SyntaxFactory.ElasticSpace; } else if (_nests >= 0) { _nests++; } } else if (trivia.Kind() == SyntaxKind.EndRegionDirectiveTrivia) { if (_nests == 0) { _nests = -1; return SyntaxFactory.ElasticSpace; } else if (_nests >= 0) { _nests--; } } return base.VisitTrivia(trivia); }
private static void HandleSingleLineComment(SyntaxTreeAnalysisContext context, SyntaxTrivia singleLineComment) { int index = 0; // PERF: Explicitly cast to IReadOnlyList so we only box once. IReadOnlyList<SyntaxTrivia> list = TriviaHelper.GetContainingTriviaList(singleLineComment, out index); var firstNonWhiteSpace = TriviaHelper.IndexOfFirstNonWhitespaceTrivia(list); // When we encounter a block of single line comments, we only want to raise this diagnostic // on the first or last line. This ensures that whitespace in code commented out using // the Comment Selection option in Visual Studio will not raise the diagnostic for every // blank line in the code which is commented out. bool isFirst = index == firstNonWhiteSpace; if (!isFirst) { // This is -2 because we need to go back past the end of line trivia as well. var lastNonWhiteSpace = TriviaHelper.IndexOfTrailingWhitespace(list) - 2; if (index != lastNonWhiteSpace) { return; } } if (IsNullOrWhiteSpace(singleLineComment.ToString(), 2)) { var diagnostic = Diagnostic.Create(Descriptor, singleLineComment.GetLocation()); context.ReportDiagnostic(diagnostic); } }
public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia) { var comment = trivia.ToString(); if (trivia.Kind() == SyntaxKind.MultiLineCommentTrivia) { if (!comment.StartsWith("/*uncomment")) { bool shouldCreateTextBlock = trivia.GetParents().Count(p => IsNestingParent(p, trivia)) <= 1; if (shouldCreateTextBlock) Blocks.Add(ExtractMarkDownFromComment(trivia)); } } else if (trivia.Kind() == SyntaxKind.SingleLineCommentTrivia) { if (comment.StartsWith("//#")) { var parts = comment.Split(new[] { ' ' }, 2); if (parts[0] == "//#video") EmbedVideo(parts[1]); if (parts[0] == "//#include") EmbedCode(parts[1]); if (parts[0] == "//#para") EmbedPara(parts[1]); if (parts[0] == "//#gallery") EmbedGallery(parts[1]); } } return base.VisitTrivia(trivia); }
public EvaluationResult Evaluate(SyntaxTrivia node) { var result = EvaluateImpl(node); if (result != null) { var sourceTree = node.GetLocation().SourceTree; var filePath = sourceTree.FilePath; var typeDefinition = GetNodeType(node.Token.Parent); var unitNamespace = GetNamespace(node.Token.Parent); if (result.ErrorCount == 0) { result.ErrorCount = 1; } result.LinesOfCodeAffected = 0; result.Namespace = unitNamespace; result.TypeKind = typeDefinition.Item1; result.TypeName = typeDefinition.Item2; result.Title = Title; result.Suggestion = Suggestion; result.Quality = Quality; result.QualityAttribute = QualityAttribute; result.ImpactLevel = ImpactLevel; result.FilePath = filePath; } return result; }
private void AddClassification(SyntaxTrivia trivia, string type) { if (trivia.Width() > 0 && _textSpan.OverlapsWith(trivia.Span)) { AddClassification(trivia.Span, type); } }
protected override void AppendTodoComments(ImmutableArray<TodoCommentDescriptor> commentDescriptors, SyntacticDocument document, SyntaxTrivia trivia, List<TodoComment> todoList) { if (PreprocessorHasComment(trivia)) { var message = trivia.ToFullString(); var index = message.IndexOf(SingleLineCommentPrefix); var start = trivia.FullSpan.Start + index; AppendTodoCommentInfoFromSingleLine(commentDescriptors, document, message.Substring(index), start, todoList); return; } if (IsSingleLineComment(trivia)) { ProcessMultilineComment(commentDescriptors, document, trivia, postfixLength: 0, todoList: todoList); return; } if (IsMultilineComment(trivia)) { ProcessMultilineComment(commentDescriptors, document, trivia, s_multilineCommentPostfixLength, todoList); return; } throw ExceptionUtilities.Unreachable; }
public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia) { if (trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia) { if (IsBeginningOrEndOfDocumentComment(trivia)) { return base.VisitTrivia(trivia); } else { var triviaText = trivia.ToFullString(); var newTriviaText = triviaText.AdjustIndentForXmlDocExteriorTrivia( _forceIndentation, _indentation, _indentationDelta, _optionSet.GetOption(FormattingOptions.UseTabs, LanguageNames.CSharp), _optionSet.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp)); if (triviaText == newTriviaText) { return base.VisitTrivia(trivia); } var parsedNewTrivia = SyntaxFactory.DocumentationCommentExterior(newTriviaText); return parsedNewTrivia; } } return base.VisitTrivia(trivia); }
private Task<Document> ReplaceTabWithFourSpacesAsync(Document document, SyntaxNode root, SyntaxTrivia tabTrivia , CancellationToken cancellationToken) { SyntaxTrivia fourSpacesTrivia = SyntaxFactory.Whitespace(new string(' ', 4 * tabTrivia.Span.Length)); SyntaxNode newRoot = root.ReplaceTrivia(tabTrivia, fourSpacesTrivia); return Task.FromResult(document.WithSyntaxRoot(newRoot)); }
public override void CollectOutliningSpans( Document document, SyntaxTrivia trivia, List<OutliningSpan> spans, CancellationToken cancellationToken) { CollectOutliningSpans(trivia.SyntaxTree, trivia, spans, cancellationToken); }
public override void CollectBlockSpans( Document document, SyntaxTrivia trivia, ArrayBuilder<BlockSpan> spans, CancellationToken cancellationToken) { CollectBlockSpans(trivia.SyntaxTree, trivia, spans, cancellationToken); }
internal static StructuredTriviaSyntax Create(SyntaxTrivia trivia) { var node = trivia.UnderlyingNode; var parent = (CSharpSyntaxNode)trivia.Token.Parent; var position = trivia.Position; var red = (StructuredTriviaSyntax)node.CreateRed(parent, position); red.parent = trivia; return red; }
private void HandleWhitespaceTrivia(SyntaxTreeAnalysisContext context, SyntaxTrivia trivia) { if (trivia.ToFullString().IndexOf('\t') < 0) { return; } // Tabs must not be used. context.ReportDiagnostic(Diagnostic.Create(Descriptor, trivia.GetLocation())); }
public SyntaxTriviaListBuilder Add(SyntaxTrivia item) { if (_nodes == null || _count >= _nodes.Length) { this.Grow(_count == 0 ? 8 : _nodes.Length * 2); } _nodes[_count++] = item; return this; }
public void Add(SyntaxTrivia[] items, int offset, int length) { if (_nodes == null || _count + length > _nodes.Length) { this.Grow(_count + length); } Array.Copy(items, offset, _nodes, _count, length); _count += length; }
private Task<Document> RemoveComment(Document document, SyntaxNode root, SyntaxTrivia comment, CancellationToken cancellationToken) { var line = comment.Token.LeadingTrivia.SplitLines().First(n => n.Contains(comment)); var newRoot = root.ReplaceTrivia(line, (_, __) => default(SyntaxTrivia)); var newDocument = document.WithSyntaxRoot(newRoot); return Task.FromResult(newDocument); }
public void Add(SyntaxTrivia[] items, int offset, int length) { if (nodes == null || count + length > nodes.Length) { this.Grow(count + length); } Array.Copy(items, offset, nodes, count, length); count += length; }
public SyntaxTriviaListBuilder Add(SyntaxTrivia item) { if (nodes == null || count >= nodes.Length) { this.Grow(count == 0 ? 8 : nodes.Length * 2); } nodes[count++] = item; return this; }
protected override SyntaxTrivia CreateEndOfLine() { if (_newLine == default(SyntaxTrivia)) { var text = this.Context.OptionSet.GetOption(FormattingOptions.NewLine, LanguageNames.CSharp); _newLine = SyntaxFactory.EndOfLine(text); } return _newLine; }
internal static SyntaxTrivia GetBestNewLineTrivia(SyntaxTriviaList list, SyntaxTrivia? defaultNewLineTrivia = null) { SyntaxTrivia trivia; if (TryGetExistingNewLine(list, out trivia)) { return trivia; } return defaultNewLineTrivia ?? SyntaxFactory.CarriageReturnLineFeed; }
/// <summary> /// Look at the context of the node to determine the best possible new line trivia. It will prefer /// existing new lines over creating a new one to help ensure the same new lines are preserved /// throughout the file. /// </summary> internal static SyntaxTrivia GetBestNewLineTrivia(SyntaxNode node, SyntaxTrivia? defaultNewLineTrivia = null) { SyntaxTrivia trivia; if (TryGetExistingNewLine(node.GetLeadingTrivia(), out trivia) || TryGetExistingNewLine(node.GetTrailingTrivia(), out trivia)) { return trivia; } return defaultNewLineTrivia ?? SyntaxFactory.CarriageReturnLineFeed; }
public static IFormattingResult Format( SyntaxTrivia trivia, int initialColumn, OptionSet optionSet, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { var root = trivia.GetStructure(); var formatter = new CSharpStructuredTriviaFormatEngine(trivia, initialColumn, optionSet, formattingRules, root.GetFirstToken(includeZeroWidth: true), root.GetLastToken(includeZeroWidth: true)); return formatter.FormatAsync(cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); }
internal static SyntaxTrivia GetBestNewLineTrivia(SyntaxToken token, SyntaxTrivia? defaultNewLineTrivia = null) { SyntaxTrivia trivia; if (TryGetExistingNewLine(token.LeadingTrivia, out trivia) || TryGetExistingNewLine(token.TrailingTrivia, out trivia)) { return trivia; } return defaultNewLineTrivia ?? SyntaxFactory.CarriageReturnLineFeed; }
public static bool IsSingleLineComment(this SyntaxTrivia trivia) { return(trivia.Kind() == SyntaxKind.SingleLineCommentTrivia); }
public static bool IsDocComment(this SyntaxTrivia trivia) { return(trivia.IsSingleLineDocComment() || trivia.IsMultiLineDocComment()); }
protected internal override SyntaxNode InsertTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia, bool insertBefore) { return SyntaxReplacer.InsertTriviaInList(this, originalTrivia, newTrivia, insertBefore); }
internal SyntaxTrivia ConvertTrivia(SyntaxTrivia t) { var switchExpr = t.RawKind; /* TODO ERROR: Skipped RegionDirectiveTrivia */ switch (switchExpr) { case (int)CS.SyntaxKind.WhitespaceTrivia: { return(VBFactory.WhitespaceTrivia(t.ToString())); } case (int)CS.SyntaxKind.EndOfLineTrivia: { return(global::VisualBasicSyntaxFactory.VBEOLTrivia); } case (int)CS.SyntaxKind.SingleLineCommentTrivia: { if (t.ToFullString().EndsWith("*/")) { return(VBFactory.CommentTrivia($"'{ReplaceLeadingSlashes(t.ToFullString().Substring(2, t.ToFullString().Length - 4))}")); } return(VBFactory.CommentTrivia($"'{ReplaceLeadingSlashes(t.ToFullString().Substring(2))}")); } case (int)CS.SyntaxKind.MultiLineCommentTrivia: { if (t.ToFullString().EndsWith("*/")) { return(VBFactory.CommentTrivia($"'{ReplaceLeadingSlashes(t.ToFullString().Substring(2, t.ToFullString().Length - 4)).Replace(Constants.vbLf, "").Replace(Constants.vbCr, "")}")); } return(VBFactory.CommentTrivia($"'{ReplaceLeadingSlashes(t.ToFullString().Substring(2)).Replace(Constants.vbLf, "").Replace(Constants.vbCr, "")}")); } case (int)CS.SyntaxKind.DocumentationCommentExteriorTrivia: { return(VBFactory.SyntaxTrivia(VB.SyntaxKind.CommentTrivia, "'''")); } case (int)CS.SyntaxKind.DisabledTextTrivia: { if (TriviaDepth > 0) { return(VBFactory.DisabledTextTrivia(t.ToString().WithoutNewLines(' '))); } return(VBFactory.DisabledTextTrivia(t.ToString().ConsistentNewlines())); } case (int)CS.SyntaxKind.PreprocessingMessageTrivia: { return(VBFactory.CommentTrivia($" ' {t}")); } case (int)CS.SyntaxKind.None: { return(default(SyntaxTrivia)); } } /* TODO ERROR: Skipped EndRegionDirectiveTrivia */ /* TODO ERROR: Skipped RegionDirectiveTrivia */ CSS.StructuredTriviaSyntax StructuredTrivia = (CSS.StructuredTriviaSyntax)t.GetStructure(); Debug.Assert(StructuredTrivia != null, $"Found new type of non structured trivia {t.RawKind}"); var switchExpr1 = t.RawKind; switch (switchExpr1) { case (int)CS.SyntaxKind.DefineDirectiveTrivia: { CSS.DefineDirectiveTriviaSyntax DefineDirective = (CSS.DefineDirectiveTriviaSyntax)StructuredTrivia; var Name = VBFactory.Identifier(DefineDirective.Name.ValueText); VBS.ExpressionSyntax value = VBFactory.TrueLiteralExpression(global::VisualBasicSyntaxFactory.TrueKeyword); return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken(WithConvertedTriviaFrom(VBFactory.ConstDirectiveTrivia(Name, value), DefineDirective), DefineDirective.EndOfDirectiveToken) )); } case (int)CS.SyntaxKind.UndefDirectiveTrivia: { CSS.UndefDirectiveTriviaSyntax UndefineDirective = (CSS.UndefDirectiveTriviaSyntax)StructuredTrivia; var Name = VBFactory.Identifier(UndefineDirective.Name.ValueText); VBS.ExpressionSyntax value = global::VisualBasicSyntaxFactory.NothingExpression; return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken(WithConvertedTriviaFrom(VBFactory.ConstDirectiveTrivia(Name, value), UndefineDirective), UndefineDirective.EndOfDirectiveToken) )); } case (int)CS.SyntaxKind.EndIfDirectiveTrivia: { if (TriviaDepth > 0) { TriviaDepth -= 1; return(VBFactory.CommentTrivia($"' TODO VB does not allow directives here, original statement {t.ToFullString().WithoutNewLines(' ')}")); } CSS.EndIfDirectiveTriviaSyntax EndIfDirective = (CSS.EndIfDirectiveTriviaSyntax)StructuredTrivia; return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken(VBFactory.EndIfDirectiveTrivia().WithConvertedTrailingTriviaFrom(EndIfDirective.EndIfKeyword), EndIfDirective.EndOfDirectiveToken) )); } case (int)CS.SyntaxKind.ErrorDirectiveTrivia: { CSS.ErrorDirectiveTriviaSyntax ErrorDirective = (CSS.ErrorDirectiveTriviaSyntax)StructuredTrivia; return(VBFactory.CommentTrivia($"' TODO: Check VB does not support Error Directive Trivia, Original Directive {ErrorDirective.ToFullString()}")); } case (int)CS.SyntaxKind.IfDirectiveTrivia: { if (t.Token.Parent?.AncestorsAndSelf().OfType <CSS.InitializerExpressionSyntax>().Any() == true) { TriviaDepth += 1; } CSS.IfDirectiveTriviaSyntax IfDirective = (CSS.IfDirectiveTriviaSyntax)StructuredTrivia; string Expression1 = StringReplaceCondition(IfDirective.Condition.ToString()); return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken(VBFactory.IfDirectiveTrivia(global::VisualBasicSyntaxFactory.IfKeyword, VBFactory.ParseExpression(Expression1)).With(IfDirective.GetLeadingTrivia().ConvertTrivia(), IfDirective.Condition.GetTrailingTrivia().ConvertTrivia()), IfDirective.EndOfDirectiveToken))); } case (int)CS.SyntaxKind.ElifDirectiveTrivia: { if (t.Token.Parent.AncestorsAndSelf().OfType <CSS.InitializerExpressionSyntax>().Any()) { TriviaDepth += 1; } CSS.ElifDirectiveTriviaSyntax ELIfDirective = (CSS.ElifDirectiveTriviaSyntax)StructuredTrivia; string Expression1 = StringReplaceCondition(ELIfDirective.Condition.ToString()); SyntaxToken IfOrElseIfKeyword; if (t.IsKind(CS.SyntaxKind.ElifDirectiveTrivia)) { IfOrElseIfKeyword = global::VisualBasicSyntaxFactory.ElseIfKeyword; } else { IfOrElseIfKeyword = global::VisualBasicSyntaxFactory.IfKeyword; } return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken(VBFactory.ElseIfDirectiveTrivia(IfOrElseIfKeyword, VBFactory.ParseExpression(Expression1)) .With(ELIfDirective.GetLeadingTrivia().ConvertTrivia(), ELIfDirective.Condition.GetTrailingTrivia().ConvertTrivia()) , ELIfDirective.EndOfDirectiveToken))); } case (int)CS.SyntaxKind.LineDirectiveTrivia: { return(VBFactory.CommentTrivia($"' TODO: Check VB does not support Line Directive Trivia, Original Directive {t}")); } case (int)CS.SyntaxKind.ElseDirectiveTrivia: { return(VBFactory.Trivia(WithTrailingEOL(VBFactory.ElseDirectiveTrivia().NormalizeWhitespace().WithConvertedTrailingTriviaFrom(((CSS.ElseDirectiveTriviaSyntax)StructuredTrivia).ElseKeyword)))); } case (int)CS.SyntaxKind.EndRegionDirectiveTrivia: { CSS.EndRegionDirectiveTriviaSyntax EndRegionDirective = (CSS.EndRegionDirectiveTriviaSyntax)StructuredTrivia; return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken(VBFactory.EndRegionDirectiveTrivia(global::VisualBasicSyntaxFactory.HashToken, global::VisualBasicSyntaxFactory.EndKeyword, global::VisualBasicSyntaxFactory.RegionKeyword), EndRegionDirective.EndOfDirectiveToken))); } case (int)CS.SyntaxKind.PragmaWarningDirectiveTrivia: { // Dim PragmaWarningDirectiveTrivia As CSS.PragmaWarningDirectiveTriviaSyntax = DirectCast(StructuredTrivia, CSS.PragmaWarningDirectiveTriviaSyntax) // Dim ErrorList As New List(Of VBS.IdentifierNameSyntax) // Dim TrailingTriviaStringBuilder As New StringBuilder // For Each i As CSS.ExpressionSyntax In PragmaWarningDirectiveTrivia.ErrorCodes // Dim ErrorCode As String = i.ToString // If ErrorCode.IsInteger Then // ErrorCode = $"CS_{ErrorCode}" // End If // ErrorList.Add(VBFactory.IdentifierName(ErrorCode)) // For Each Trivial As SyntaxTrivia In i.GetTrailingTrivia // TrailingTriviaStringBuilder.Append(Trivial.ToString) // Next // Next // Dim WarningDirectiveTrivia As VBS.DirectiveTriviaSyntax // If PragmaWarningDirectiveTrivia.DisableOrRestoreKeyword.IsKind(CS.SyntaxKind.DisableKeyword) Then // WarningDirectiveTrivia = VBFactory.DisableWarningDirectiveTrivia(ErrorList.ToArray) // Else // WarningDirectiveTrivia = VBFactory.EnableWarningDirectiveTrivia(ErrorList.ToArray) // End If // Return VBFactory.CommentTrivia($" ' TODO {WarningDirectiveTrivia.NormalizeWhitespace}{TrailingTriviaStringBuilder.ToString}") return(default(SyntaxTrivia)); } case (int)CS.SyntaxKind.RegionDirectiveTrivia: { CSS.RegionDirectiveTriviaSyntax RegionDirective = (CSS.RegionDirectiveTriviaSyntax)StructuredTrivia; var EndOfDirectiveToken = RegionDirective.EndOfDirectiveToken; string NameString = $"\"{EndOfDirectiveToken.LeadingTrivia.ToString().Replace("\"", "")}\""; var RegionDirectiveTriviaNode = VBFactory.RegionDirectiveTrivia(global::VisualBasicSyntaxFactory.HashToken, global::VisualBasicSyntaxFactory.RegionKeyword, VBFactory.StringLiteralToken(NameString, NameString) ).WithConvertedTrailingTriviaFrom(EndOfDirectiveToken); return(VBFactory.Trivia(WithTrailingEOL(RegionDirectiveTriviaNode))); } case (int)CS.SyntaxKind.SingleLineDocumentationCommentTrivia: { CSS.DocumentationCommentTriviaSyntax SingleLineDocumentationComment = (CSS.DocumentationCommentTriviaSyntax)StructuredTrivia; var walker = new XMLVisitor(); walker.Visit(SingleLineDocumentationComment); var xmlNodes = new List <VBS.XmlNodeSyntax>(); for (int i = 0, loopTo = SingleLineDocumentationComment.Content.Count - 1; i <= loopTo; i++) { var node = SingleLineDocumentationComment.Content[i]; if (!node.IsKind(CS.SyntaxKind.XmlText) && node.GetLeadingTrivia().Count > 0 && node.GetLeadingTrivia().First().IsKind(CS.SyntaxKind.DocumentationCommentExteriorTrivia)) { if (i < SingleLineDocumentationComment.Content.Count - 1) { var NextNode = SingleLineDocumentationComment.Content[i + 1]; if (!NextNode.IsKind(CS.SyntaxKind.XmlText) || NextNode.GetLeadingTrivia().Count == 0 || !NextNode.GetLeadingTrivia().First().IsKind(CS.SyntaxKind.DocumentationCommentExteriorTrivia)) { xmlNodes.Add(VBFactory.XmlText(" ").WithLeadingTrivia(VBFactory.DocumentationCommentExteriorTrivia("'''"))); } } node = node.WithoutLeadingTrivia(); } VBS.XmlNodeSyntax Item = (VBS.XmlNodeSyntax)node.Accept(walker); xmlNodes.Add(Item); } var DocumentationCommentTrivia = VBFactory.DocumentationCommentTrivia(VBFactory.List(xmlNodes.ToArray())); if (!DocumentationCommentTrivia.HasLeadingTrivia || !DocumentationCommentTrivia.GetLeadingTrivia()[0].IsKind(VB.SyntaxKind.DocumentationCommentExteriorTrivia)) { DocumentationCommentTrivia = DocumentationCommentTrivia.WithLeadingTrivia(VBFactory.DocumentationCommentExteriorTrivia("''' ")); } var _DocumentationComment = VBFactory.Trivia(DocumentationCommentTrivia.WithTrailingTrivia(VBFactory.EndOfLine(""))); return(_DocumentationComment); } case (int)CS.SyntaxKind.PragmaChecksumDirectiveTrivia: { CSS.PragmaChecksumDirectiveTriviaSyntax PragmaChecksumDirective = (CSS.PragmaChecksumDirectiveTriviaSyntax)StructuredTrivia; var Guid1 = VBFactory.ParseToken(PragmaChecksumDirective.Guid.Text.ToUpperInvariant()); var Bytes = VBFactory.ParseToken(PragmaChecksumDirective.Bytes.Text); var ExternalSource = VBFactory.ParseToken(PragmaChecksumDirective.File.Text); return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken( VBFactory.ExternalChecksumDirectiveTrivia(global::VisualBasicSyntaxFactory.HashToken, global::VisualBasicSyntaxFactory.ExternalChecksumKeyword, global::VisualBasicSyntaxFactory.OpenParenToken, ExternalSource, global::VisualBasicSyntaxFactory.CommaToken, Guid1, global::VisualBasicSyntaxFactory.CommaToken, Bytes, global::VisualBasicSyntaxFactory.CloseParenToken), PragmaChecksumDirective.EndOfDirectiveToken))); } case (int)CS.SyntaxKind.SkippedTokensTrivia: { var Builder = new StringBuilder(); foreach (SyntaxToken tok in ((CSS.SkippedTokensTriviaSyntax)StructuredTrivia).Tokens) { Builder.Append(tok.ToString()); } return(VBFactory.CommentTrivia($"' TODO: Error SkippedTokensTrivia '{Builder}'")); } case (int)CS.SyntaxKind.BadDirectiveTrivia: { return(VBFactory.CommentTrivia($"' TODO: Skipped BadDirectiveTrivia")); } case (int)CS.SyntaxKind.ConflictMarkerTrivia: { break; } case (int)CS.SyntaxKind.LoadDirectiveTrivia: { break; } default: { Debug.WriteLine(((VB.SyntaxKind)Conversions.ToUShort(t.RawKind)).ToString()); break; } } throw new NotImplementedException($"t.Kind({(VB.SyntaxKind)Conversions.ToUShort(t.RawKind)}) Is unknown"); }
protected abstract bool IsLineComment(SyntaxTrivia trivia);
public static bool MatchesKind(this SyntaxTrivia trivia, params SyntaxKind[] kinds) { return(kinds.Contains(trivia.Kind())); }
public static void AddInfo(SyntaxTrivia node, XElement xml, XmlOptions options) { AddNodeInfo(node.GetNodeInfo(), xml); }
//FIXME: we should compute the text on demand, but XWT doesn't let us do this void AddSyntaxTrivia(TreeNavigator nav, SyntaxTrivia trivia) { var kind = (Microsoft.CodeAnalysis.CSharp.SyntaxKind)trivia.RawKind; SetNodeText(nav, $"{kind}", trivia.Span, Colors.DarkRed, trivia); }
private static string GetIndent(SyntaxTrivia trivia, SourceText sourceText, CancellationToken cancellationToken) { int lineIndex = trivia.GetSpanStartLine(cancellationToken); return(new string(' ', trivia.FullSpan.Start - sourceText.Lines[lineIndex].Start)); }
public sealed override SyntaxNode GetStructure(SyntaxTrivia parentTrivia) { throw ExceptionUtilities.Unreachable; }
protected override ReadOnlyMemory <char> GetTextContextOfComment(SyntaxTrivia commentTrivia) { if (commentTrivia.IsKind(SyntaxKind.SingleLineCommentTrivia)) { return(commentTrivia.ToFullString().AsMemory()[2..]);
protected abstract SyntaxTrivia CreateTrivia(SyntaxTrivia trivia, string text);
protected internal override SyntaxNode ReplaceTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia) { return SyntaxReplacer.ReplaceTriviaInList(this, originalTrivia, newTrivia); }
public virtual void VisitSyntaxTrivia(SyntaxTrivia node) { DefaultVisit(node); }
private static SyntaxTrivia SelectExteriorTrivia(SyntaxTrivia rewrittenTrivia, SyntaxTrivia trivia, SyntaxTrivia triviaWithSpace) { // if the trivia had a trailing space, make sure to preserve it if (rewrittenTrivia.ToString().EndsWith(" ")) { return(triviaWithSpace); } // otherwise the space is part of the leading trivia of the following token, so don't add an extra one to // the exterior trivia return(trivia); }
public static bool MatchesKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2) { var triviaKind = trivia.Kind(); return(triviaKind == kind1 || triviaKind == kind2); }
protected override bool IsCommentTrivia(SyntaxTrivia trivia) => trivia.IsComment();
public static bool IsMultiLineDocComment(this SyntaxTrivia trivia) { return(trivia.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia); }
internal static GetFullCommentedCodeResult GetFullCommentedCode(SyntaxNode root, SyntaxTrivia firstComment) { var result = new StringBuilder(); var current = firstComment; var numberOfComments = 1; var start = firstComment.GetLocation().SourceSpan.Start; int end; do { end = current.GetLocation().SourceSpan.End; result.Append(current.ToString().Substring(2)); var eol = root.FindTrivia(current.GetLocation().SourceSpan.End + 1); if (!eol.IsKind(SyntaxKind.EndOfLineTrivia)) { break; } var whitespace = root.FindTrivia(eol.GetLocation().SourceSpan.End + 1); if (!whitespace.IsKind(SyntaxKind.WhitespaceTrivia)) { break; } current = root.FindTrivia(whitespace.GetLocation().SourceSpan.End + 1); if (!current.IsKind(SyntaxKind.SingleLineCommentTrivia)) { break; } numberOfComments++; } while (true); return(new GetFullCommentedCodeResult(result.ToString(), numberOfComments, start, end)); }
protected override bool IsEndOfLine(SyntaxTrivia trivia) { return(trivia.Kind() == SyntaxKind.EndOfLineTrivia); }
public CodeActionEdit GetEdit(CancellationToken cancellationToken) { SyntaxNode root = (SyntaxNode)this.document.GetSyntaxRoot(cancellationToken); ISemanticModel model = this.document.GetSemanticModel(cancellationToken); TypeSyntax classTypeSyntax = this.expression.Type; // TODO: extract container info and propose solutions IDictionary <TypeSymbol, String> typeParametersMap = new Dictionary <TypeSymbol, String>(); SeparatedSyntaxList <ParameterSyntax> ctorParameters = Syntax.SeparatedList <ParameterSyntax>(); SeparatedSyntaxList <TypeParameterSyntax> typeParameters = Syntax.SeparatedList <TypeParameterSyntax>(); SyntaxList <StatementSyntax> ctorStatements = Syntax.List <StatementSyntax>(); SyntaxList <MemberDeclarationSyntax> classMembers = Syntax.List <MemberDeclarationSyntax>(); if (classTypeSyntax.Kind == SyntaxKind.IdentifierName) { } else if (classTypeSyntax.Kind == SyntaxKind.GenericName) { const string paramNames = "TUV"; int index = 0; GenericNameSyntax genericName = (GenericNameSyntax)classTypeSyntax; TypeArgumentListSyntax typeArgumentList = genericName.TypeArgumentList; foreach (TypeSyntax typeArgument in typeArgumentList.Arguments) { string typeParameterName = new string(paramNames[index % paramNames.Length], index / paramNames.Length + 1); TypeParameterSyntax typeParameter = Syntax.TypeParameter(typeParameterName); typeParametersMap.Add(model.GetTypeInfo(typeArgument, cancellationToken).Type as TypeSymbol, typeParameterName); typeParameters = typeParameters.Add(typeParameter); index += 1; } } else if (classTypeSyntax.Kind == SyntaxKind.QualifiedName) { } // Add comment SyntaxTrivia commentTrivia = Syntax.Comment("// TODO: Complete member initialization"); ctorStatements = ctorStatements.Add(Syntax.EmptyStatement().WithLeadingTrivia(commentTrivia)); int order = 0; ArgumentListSyntax argumentList = this.expression.ArgumentList; foreach (ArgumentSyntax argument in argumentList.Arguments) { // Generate new identifier SyntaxToken identifier = Syntax.Identifier(String.Format("param{0}", ++order)); // For named arguments use the associated name // Considers: // new foo(a: 2); -> foo(int a) { this.a = a; } if (argument.NameColon != null) { identifier = argument.NameColon.Identifier.Identifier; } // Determine argument type TypeSymbol typeSymbol = model.GetTypeInfo(argument.Expression, cancellationToken).Type as TypeSymbol; TypeSyntax typeSyntax = null; // Check if the type of parameter specified as template type // Considers: // new A<int>(1) -> class A<T> { A(>T< param) {} } if (typeParametersMap.ContainsKey(typeSymbol)) { typeSyntax = Syntax.ParseTypeName(typeParametersMap[typeSymbol]); } else { typeSyntax = Syntax.ParseTypeName(typeSymbol.ToDisplayString()); } // Create new parameter ParameterSyntax parameter = Syntax.Parameter(identifier) .WithType(typeSyntax); ctorParameters = ctorParameters.Add(parameter); // Create new field to store parameter value VariableDeclaratorSyntax variableDeclarator = Syntax.VariableDeclarator(identifier); VariableDeclarationSyntax variableDeclaration = Syntax.VariableDeclaration(typeSyntax) .WithVariables(Syntax.SeparatedList <VariableDeclaratorSyntax>(variableDeclarator)); FieldDeclarationSyntax fieldDeclaration = Syntax.FieldDeclaration(variableDeclaration) .WithModifiers(Syntax.TokenList(Syntax.Token(SyntaxKind.PrivateKeyword))) .WithTrailingTrivia(Syntax.EndOfLine("")); classMembers = classMembers.Add(fieldDeclaration); // Create ctor initializing statement: // Considers: // this.a = a; ExpressionStatementSyntax statement = Syntax.ExpressionStatement( Syntax.BinaryExpression(SyntaxKind.AssignExpression, Syntax.MemberAccessExpression(SyntaxKind.MemberAccessExpression, Syntax.ThisExpression(), Syntax.IdentifierName(identifier)), Syntax.IdentifierName(identifier) )); ctorStatements = ctorStatements.Add(statement); } ConstructorDeclarationSyntax ctorDeclaration = Syntax.ConstructorDeclaration(this.className) .WithModifiers(Syntax.TokenList(Syntax.Token(SyntaxKind.PublicKeyword))) .WithBody(Syntax.Block(ctorStatements)) .WithParameterList(Syntax.ParameterList(ctorParameters)); classMembers = classMembers.Add(ctorDeclaration); ClassDeclarationSyntax classDeclaration = Syntax.ClassDeclaration(this.className) .WithMembers(classMembers) .WithTrailingTrivia(Syntax.ElasticCarriageReturnLineFeed) .WithAdditionalAnnotations(CodeAnnotations.Formatting); if (typeParameters.Count > 0) { classDeclaration = classDeclaration.WithTypeParameterList(Syntax.TypeParameterList(typeParameters)); } CompilationUnitSyntax compilationUnit = this.expression.FirstAncestorOrSelf <CompilationUnitSyntax>(); CompilationUnitSyntax newCompilationUnit = compilationUnit.AddMembers(classDeclaration); SyntaxNode newRoot = root.ReplaceNode(compilationUnit, newCompilationUnit); return(new CodeActionEdit(document.UpdateSyntaxRoot(newRoot))); }
public static bool IsElastic(this SyntaxTrivia trivia) { return(trivia.HasAnnotation(SyntaxAnnotation.ElasticAnnotation)); }
public static bool IsWhitespaceOrEndOfLine(this SyntaxTrivia trivia) { return(trivia.Kind() == SyntaxKind.WhitespaceTrivia || trivia.Kind() == SyntaxKind.EndOfLineTrivia); }
public static bool MatchesKind(this SyntaxTrivia trivia, SyntaxKind kind) { return(trivia.Kind() == kind); }
private Task <Document> ReplaceTabWithFourSpacesAsync(Document document, SyntaxNode root, SyntaxTrivia tabTrivia , CancellationToken cancellationToken) { SyntaxTrivia fourSpacesTrivia = SyntaxFactory.Whitespace(new string(' ', 4 * tabTrivia.Span.Length)); SyntaxNode newRoot = root.ReplaceTrivia(tabTrivia, fourSpacesTrivia); return(Task.FromResult(document.WithSyntaxRoot(newRoot))); }
public static int FullWidth(this SyntaxTrivia trivia) { return(trivia.FullSpan.Length); }
protected abstract bool IsNewLine(SyntaxTrivia trivia);
public bool IsAllowed(SyntaxNode root, SyntaxTrivia trivia) => true;
protected abstract bool IsWhitespace(SyntaxTrivia trivia);
private static bool Filter(SyntaxTrivia t) => t.Kind() == SyntaxKind.SingleLineCommentTrivia || t.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia || t.Kind() == SyntaxKind.MultiLineCommentTrivia || t.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia;