当前位置: 首页>>代码示例>>C#>>正文


C# SyntaxNode.GetLeadingTrivia方法代码示例

本文整理汇总了C#中Microsoft.CodeAnalysis.SyntaxNode.GetLeadingTrivia方法的典型用法代码示例。如果您正苦于以下问题:C# SyntaxNode.GetLeadingTrivia方法的具体用法?C# SyntaxNode.GetLeadingTrivia怎么用?C# SyntaxNode.GetLeadingTrivia使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.CodeAnalysis.SyntaxNode的用法示例。


在下文中一共展示了SyntaxNode.GetLeadingTrivia方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ReplaceDateTimeAsync

        private async Task<Document> ReplaceDateTimeAsync(Document document, 
                         SyntaxNode node,
                         CancellationToken cancellationToken)
        {
            // Get the root syntax node for the current document
            var root = await document.GetSyntaxRootAsync();

            // Convert the syntax node into the specialized kind
            var convertedNode = (IdentifierNameSyntax)node;

            // Create a new syntax node
            var newNode = convertedNode?.WithIdentifier(SyntaxFactory.
                          ParseToken("DateTimeOffset")).
                          WithLeadingTrivia(node.GetLeadingTrivia()).
                          WithTrailingTrivia(node.GetTrailingTrivia());

            // Create a new root syntax node for the current document
            // replacing the syntax node that has diagnostic with
            // a new syntax node
            var newRoot = root.ReplaceNode(node, newNode);

            // Generate a new document
            var newDocument = document.WithSyntaxRoot(newRoot);
            return newDocument;
        }
开发者ID:AlessandroDelSole,项目名称:RoslynSuccinctly,代码行数:25,代码来源:CodeFixProvider.cs

示例2: Visit

		public override void Visit(SyntaxNode node)
		{
			if (_firstVisit)
			{
				_firstVisit = false;
				var leadingTabs = new String('\t', 2 + ClassDepth);
				_code = node.WithoutLeadingTrivia().WithTrailingTrivia().ToFullString()
					.Replace(leadingTabs, "");

				var nodeLine = node.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line;

				var line = _lineNumberOverride ?? nodeLine;

				var codeBlocks = Regex.Split(_code, @"\/\*\*.*?\*\/", RegexOptions.Singleline)
					.Select(b => b.TrimStart('\r', '\n').TrimEnd('\r', '\n', '\t'))
					.Where(b => !string.IsNullOrEmpty(b) && b != ";")
					.Select(b=>new CodeBlock(b, line))
					.ToList();

				base.Visit(node);

				var nodeHasLeadingTriva = node.HasLeadingTrivia && node.GetLeadingTrivia()
					.Any(c=>c.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia);
				var blocks = codeBlocks.Intertwine<IDocumentationBlock>(this.TextBlocks, swap: nodeHasLeadingTriva);
				this.Blocks.Add(new CombinedBlock(blocks, line));
				return;
			}

			base.Visit(node);
		}
开发者ID:emohebi,项目名称:elasticsearch-net,代码行数:30,代码来源:CodeWithDocumentationWalker.cs

示例3: GetBestNewLineTrivia

        /// <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;
        }
开发者ID:transformersprimeabcxyz,项目名称:_TO-DO-codeformatter-dotnet,代码行数:16,代码来源:SyntaxUtil.cs

示例4: ReplaceAddExpressionByStringBuilderAppendExpression

 private static SyntaxNode ReplaceAddExpressionByStringBuilderAppendExpression(AssignmentExpressionSyntax assignmentExpression, SyntaxNode expressionStatement, SyntaxNode expressionStatementParent, string builderName)
 {
     var appendExpressionOnLoop = assignmentExpression.IsKind(SyntaxKind.SimpleAssignmentExpression)
         ? SyntaxFactory.ParseStatement($"{builderName}.Append({((BinaryExpressionSyntax)assignmentExpression.Right).Right.ToString()});\r\n")
         : SyntaxFactory.ParseStatement($"{builderName}.Append({assignmentExpression.Right.ToString()});\r\n");
     appendExpressionOnLoop = appendExpressionOnLoop
         .WithLeadingTrivia(expressionStatement.GetLeadingTrivia())
         .WithTrailingTrivia(expressionStatement.GetTrailingTrivia());
     var newExpressionStatementParent = expressionStatementParent.ReplaceNode(expressionStatement, appendExpressionOnLoop);
     return newExpressionStatementParent;
 }
开发者ID:haroldhues,项目名称:code-cracker,代码行数:11,代码来源:StringBuilderInLoopCodeFixProvider.cs

示例5: UseVarAsync

        private Task<Solution> UseVarAsync(Document document, SyntaxNode root, SyntaxNode statement)
        {
            var varIdentifier = SyntaxFactory.IdentifierName("var")
                                             .WithLeadingTrivia(statement.GetLeadingTrivia())
                                             .WithTrailingTrivia(statement.GetTrailingTrivia());

            var newRoot = root.ReplaceNode(statement, varIdentifier);

            var newDocument = document.WithSyntaxRoot(newRoot);
            return Task.FromResult(newDocument.Project.Solution);
        }
开发者ID:nemec,项目名称:VSDiagnostics,代码行数:11,代码来源:TypeToVarCodeFix.cs

示例6: Visit

            public override SyntaxNode Visit(SyntaxNode node)
            {
                node = base.Visit(node);

                if (node == null)
                {
                    return null;
                }

                var needsRewrite = node.HasLeadingTrivia &&
                                   node.GetLeadingTrivia().Any(
                                       y => y.Kind() == SyntaxKind.SingleLineCommentTrivia &&
                                            !y.IsDirective &&
                                            !y.ContainsDiagnostics);

                if (!needsRewrite)
                {
                    return node;
                }

                return node.WithLeadingTrivia(this.FixCommentWhitespace(node.GetLeadingTrivia()));
            }
开发者ID:OliverKurowski,项目名称:StylecopCodeFormatter,代码行数:22,代码来源:SA1120_CommentMustNotBeEmpty.cs

示例7: ProcessAsync

        public Task<SyntaxNode> ProcessAsync(Document document, SyntaxNode syntaxNode, CancellationToken cancellationToken)
        {
            var leadingTrivia = syntaxNode.GetLeadingTrivia();
            SyntaxTriviaList newTrivia = leadingTrivia;
            var illegalHeaders = GetIllegalHeaders(document);

            // We also want to add the filename (without path but with extension) to this list.

            // because we are mutating the list, once we remove a header, we won't remove any others...
            for (int idx = 0; idx < illegalHeaders.Length; idx++)
            {
                var illegalHeader = illegalHeaders[idx];
                foreach (var trivia in newTrivia)
                {
                    // If we have an illegal header here...
                    if (trivia.ToFullString().IndexOf(illegalHeader, StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        if (trivia.IsKind(SyntaxKind.MultiLineCommentTrivia))
                        {
                            // For multiline comment trivia we need to process them line by line and remove all the illegal headers.
                            // We then need to re-create the multiline comment and append it to the list.
                            var modifiedTrivia = RemoveIllegalHeadersFromMultilineComment(newTrivia, trivia, illegalHeader);

                            // We need to go back and re-try the current illegal header if we have modified the multiline trivia.
                            if (modifiedTrivia != newTrivia)
                            {
                                newTrivia = modifiedTrivia;
                                idx--;
                            }
                            break;
                        }
                        else
                        {
                            var index = newTrivia.IndexOf(trivia);

                            newTrivia = RemoveTriviaAtIndex(newTrivia, index);

                            // We need to re-try the current illegal header to make sure there are no other comments containing it
                            // further down the trivia list
                            idx--;
                            break;
                        }
                    }
                }
            }

            if (leadingTrivia.Equals(newTrivia))
                return Task.FromResult(syntaxNode);

            return Task.FromResult(syntaxNode.WithLeadingTrivia(newTrivia));
        }
开发者ID:transformersprimeabcxyz,项目名称:_TO-DO-codeformatter-dotnet,代码行数:51,代码来源:HasNoIllegalHeadersFormattingRule.cs

示例8: GetFix

        private async Task<Document> GetFix(Document document, SyntaxNode expression, CancellationToken cancellationToken)
        {
            // Rewrite the expression to include a .ConfigureAwait() after it. We reattach trailing trivia to the end.
            // This is especially important for VB, as the end-of-line may be in the trivia
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
            SyntaxGenerator generator = editor.Generator;
            SyntaxNode memberAccess = generator.MemberAccessExpression(expression.WithoutTrailingTrivia(), "ConfigureAwait");
            SyntaxNode falseLiteral = generator.FalseLiteralExpression();
            SyntaxNode invocation = generator.InvocationExpression(memberAccess, falseLiteral);
            invocation = invocation.WithLeadingTrivia(expression.GetLeadingTrivia()).WithTrailingTrivia(expression.GetTrailingTrivia());

            editor.ReplaceNode(expression, invocation);
            return editor.GetChangedDocument();
        }
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:14,代码来源:DoNotDirectlyAwaitATask.Fixer.cs

示例9: Visit

		public override void Visit(SyntaxNode node)
		{
			if (_firstVisit)
			{
				_firstVisit = false;

				var repeatedTabs = 2 + ClassDepth;
				var language = Language.CSharp;



				_code = node.WithoutLeadingTrivia().WithTrailingTrivia().ToFullString();
				_code = _code.RemoveNumberOfLeadingTabsAfterNewline(repeatedTabs);

#if !DOTNETCORE
				if (_propertyOrMethodName == "ExpectJson" || _propertyOrMethodName == "QueryJson")
				{
					// try to get the json for the anonymous type.
					// Only supports system types and Json.Net LINQ objects e.g. JObject
					string json;
					if (_code.TryGetJsonForAnonymousType(out json))
					{
						language = Language.JavaScript;
						_code = json;
					}
				}
#endif
				// TODO: Can do this once we get the generic arguments from the Property declaration
				//if (_propertyName == "Fluent")
				//{
				//  // need to know what type we're operating on
				//	_code += $"client.Search({_code});";
				//}

				var nodeLine = node.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line;
				var line = _lineNumberOverride ?? nodeLine;
				var codeBlocks = ParseCodeBlocks(_code, line, language, _propertyOrMethodName);

				base.Visit(node);

				var nodeHasLeadingTriva = node.HasLeadingTrivia &&
					node.GetLeadingTrivia().Any(c => c.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia);
				var blocks = codeBlocks.Intertwine<IDocumentationBlock>(this.TextBlocks, swap: nodeHasLeadingTriva);
				this.Blocks.Add(new CombinedBlock(blocks, line));
				return;
			}

			base.Visit(node);
		}
开发者ID:RossLieberman,项目名称:NEST,代码行数:49,代码来源:CodeWithDocumentationWalker.cs

示例10: ReplaceHeader

        private static SyntaxNode ReplaceHeader(Document document, SyntaxNode root, StyleCopSettings settings)
        {
            // Skip single line comments, whitespace, and end of line trivia until a blank line is encountered.
            SyntaxTriviaList trivia = root.GetLeadingTrivia();

            bool onBlankLine = false;
            while (trivia.Any())
            {
                bool done = false;
                switch (trivia[0].Kind())
                {
                case SyntaxKind.SingleLineCommentTrivia:
                    trivia = trivia.RemoveAt(0);
                    onBlankLine = false;
                    break;

                case SyntaxKind.WhitespaceTrivia:
                    trivia = trivia.RemoveAt(0);
                    break;

                case SyntaxKind.EndOfLineTrivia:
                    trivia = trivia.RemoveAt(0);

                    if (onBlankLine)
                    {
                        done = true;
                    }
                    else
                    {
                        onBlankLine = true;
                    }

                    break;

                default:
                    done = true;
                    break;
                }

                if (done)
                {
                    break;
                }
            }

            string newLineText = document.Project.Solution.Workspace.Options.GetOption(FormattingOptions.NewLine, LanguageNames.CSharp);
            return root.WithLeadingTrivia(CreateNewHeader(document.Name, settings, newLineText).Add(SyntaxFactory.CarriageReturnLineFeed).Add(SyntaxFactory.CarriageReturnLineFeed).AddRange(trivia));
        }
开发者ID:ChrSteinert,项目名称:StyleCopAnalyzers,代码行数:48,代码来源:FileHeaderCodeFixProvider.cs

示例11: Process

        public SyntaxNode Process(SyntaxNode syntaxNode, string languageName)
        {
            // SetHeaders
            if (!SetHeaders())
                return syntaxNode;

            var triviaList = syntaxNode.GetLeadingTrivia();

            SyntaxTrivia start;
            SyntaxTrivia end;
            if (!TryGetStartAndEndOfXmlHeader(triviaList, out start, out end))
                return syntaxNode;

            var filteredList = Filter(triviaList, start, end);
            return syntaxNode.WithLeadingTrivia(filteredList);
        }
开发者ID:OliverKurowski,项目名称:StylecopCodeFormatter,代码行数:16,代码来源:HasNoCustomCopyrightHeaderFormattingRule.cs

示例12: CheckForInvalid

            void CheckForInvalid(SyntaxNode node)
            {
                context.CancellationToken.ThrowIfCancellationRequested();
                foreach (var triva in node.GetLeadingTrivia())
                {
                    if (triva.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia))
                        storedXmlComment.Add((DocumentationCommentTriviaSyntax)triva.GetStructure());
                }

                if (storedXmlComment.Count == 0)
                    return;

                context.ReportDiagnostic(Diagnostic.Create(
                    descriptor,
                    Location .Create(context.Tree, storedXmlComment[0].FullSpan),
                    storedXmlComment.Skip(1).Select(cmt => Location .Create(context.Tree, cmt.FullSpan)),
                    GettextCatalog.GetString("Xml comment is not placed before a valid language element")
                ));
                storedXmlComment.Clear();
            }
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:20,代码来源:XmlDocAnalyzer.cs

示例13: ConvertToArrayEmpty

        private async Task<Document> ConvertToArrayEmpty(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken)
        {
            DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            SyntaxGenerator generator = editor.Generator;

            SyntaxNode variableDecl = generator.GetDeclaration(nodeToFix, DeclarationKind.Variable);
            SyntaxNode typeNode = generator.GetType(variableDecl);

            var type = semanticModel.GetTypeInfo(typeNode, cancellationToken).Type as IArrayTypeSymbol;
            INamedTypeSymbol arrayTypeSymbol = semanticModel.Compilation.GetTypeByMetadataName(AvoidZeroLengthArrayAllocationsAnalyzer.ArrayTypeName);

            SyntaxNode arrayEmptyName = generator.QualifiedName(generator.TypeExpression(arrayTypeSymbol),
                                                         generator.GenericName(AvoidZeroLengthArrayAllocationsAnalyzer.ArrayEmptyMethodName, type.ElementType));
            SyntaxNode arrayEmptyInvocation = generator.InvocationExpression(arrayEmptyName);
            arrayEmptyInvocation = arrayEmptyInvocation.WithLeadingTrivia(nodeToFix.GetLeadingTrivia()).WithTrailingTrivia(nodeToFix.GetTrailingTrivia());
            editor.ReplaceNode(nodeToFix, arrayEmptyInvocation);
            return editor.GetChangedDocument();
        }
开发者ID:bkoelman,项目名称:roslyn-analyzers,代码行数:20,代码来源:AvoidZeroLengthArrayAllocations.Fixer.cs

示例14: Parse

 public static DeclarationItemDescription Parse(SyntaxNode node)
 {
     // wywalili  SyntaxKind.DocumentationCommentTrivia
     var documentationCommentTrivia =
               node.GetLeadingTrivia()
               .SingleOrDefault(t => t.CSharpKind() == (SyntaxKind)0/* SyntaxKind.DocumentationCommentTrivia */);
     if (documentationCommentTrivia.CSharpKind() == SyntaxKind.None)
         return null;
     var result = new DeclarationItemDescription();
     {
         var doc = (StructuredTriviaSyntax)documentationCommentTrivia.GetStructure();
         var docChilds = doc.ChildNodes().OfType<XmlElementSyntax>().ToArray();
         foreach (var child in docChilds)
         {
             var xmlNameSyntax = child.StartTag.Name;
             var text = xmlNameSyntax.GetText().ToString();
             switch (text)
             {
                 case "summary":
                     result.Summary = GetText(child);
                     break;
                 case "param":
                 {
                     var xmlAttributeSyntax = child.StartTag.Attributes.SingleOrDefault(i => i.Name.ToString() == "name");
                     if (xmlAttributeSyntax == null) continue;
                     var name = xmlAttributeSyntax.Name.ToString();
                     var p = GetText(child);
                     if (p != "")
                         result.Parameters[name] = p;
                 }
                     break;
                 case "returns":
                     result.Returns = GetText(child);
                     break;
                 default:
                     throw new NotSupportedException();
             }
         }
     }
     return result;
 }
开发者ID:exaphaser,项目名称:cs2php,代码行数:41,代码来源:DeclarationItemDescription.cs

示例15: SyntaxNode

        /// <summary>
        /// Converts a C# Roslyn SyntaxNode to its Swift equivilant
        /// </summary>
        /// <param name="node">Roslyn SyntaxNode representing the C# code to convert</param>
        /// <returns>A string with the converted Swift code</returns>
        public static string SyntaxNode(SyntaxNode node)
        {
            if (node == null) return "";

            if (node.HasLeadingTrivia)
            {
                var ignoreNode = node.GetLeadingTrivia()
                    .Where(trivia =>
                            trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) ||
                            trivia.IsKind(SyntaxKind.SingleLineCommentTrivia))
                    .Any(trivia => trivia.ToString().TrimStart('/', '*').ToLower().Trim() == "ignore");

                if (ignoreNode) return "";
            }

            if (node is BlockSyntax)
            {
                //Block() takes two arguments, & I don't want to worry about it w/ reflection.
                return Block((BlockSyntax)node);
            }

            /*
             * We're gonna search through ConvertToSwift's static methods for one
             * with the ParsesType attribute that matches the typeof node.
             * If one isn't found we'll just return the C# code
             */
            var nodeType = node.GetType();

            var methods = typeof(ConvertToSwift).GetMethods();
            var matchedMethod =
                methods.FirstOrDefault(method => //find method that parses this syntax
                        method.GetCustomAttributes(true).OfType<ParsesTypeAttribute>()
                            .Any(attr => attr.ParsesType == nodeType));

            if (matchedMethod != null)
            {
                return matchedMethod.Invoke(new ConvertToSwift(), new[] { node }).ToString();
            }

            return node + NewLine;
        }
开发者ID:UIKit0,项目名称:SharpSwift,代码行数:46,代码来源:SyntaxNodeConverter.cs


注:本文中的Microsoft.CodeAnalysis.SyntaxNode.GetLeadingTrivia方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。