• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# SyntaxTree类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中SyntaxTree的典型用法代码示例。如果您正苦于以下问题:C# SyntaxTree类的具体用法?C# SyntaxTree怎么用?C# SyntaxTree使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



SyntaxTree类属于命名空间,在下文中一共展示了SyntaxTree类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: BeginsWithAutoGeneratedComment

            private static bool BeginsWithAutoGeneratedComment(SyntaxTree tree, Func<SyntaxTrivia, bool> isComment, CancellationToken cancellationToken)
            {
                var root = tree.GetRoot(cancellationToken);
                if (root.HasLeadingTrivia)
                {
                    var leadingTrivia = root.GetLeadingTrivia();

                    foreach (var trivia in leadingTrivia)
                    {
                        if (!isComment(trivia))
                        {
                            continue;
                        }

                        var text = trivia.ToString();

                        // Check to see if the text of the comment contains an auto generated comment.
                        foreach (var autoGenerated in s_autoGeneratedStrings)
                        {
                            if (text.Contains(autoGenerated))
                            {
                                return true;
                            }
                        }
                    }
                }

                return false;
            }            
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:29,代码来源:AnalyzerDriver.GeneratedCodeUtilities.cs


示例2: PathSyntaxReference

 public PathSyntaxReference(SyntaxNode node)
 {
     _tree = node.SyntaxTree;
     _kind = node.Kind();
     _textSpan = node.Span;
     _pathFromRoot = ComputePathFromRoot(node);
 }
开发者ID:Rickinio,项目名称:roslyn,代码行数:7,代码来源:CSharpSyntaxTreeFactory.PathSyntaxReference.cs


示例3: GetClassificationForToken

        /// <summary>
        /// Determine the classification type for a given token.
        /// </summary>
        /// <param name="classificationTypes">A classification service to retrieve classification types.</param>
        /// <param name="token">The token.</param>
        /// <param name="syntaxTree">The tree containing the token (can be null for tokens that are
        /// unparented).</param>
        /// <returns>The correct syntactic classification for the token.</returns>
        public static IClassificationType GetClassificationForToken(this IClassificationTypes classificationTypes, SyntaxToken token, SyntaxTree syntaxTree)
        {
            if (SyntaxFacts.IsKeywordKind(token.Kind))
            {
                return classificationTypes.Keyword;
            }
            else if (token.Kind.IsPunctuation())
            {
                return GetClassificationForPunctuation(classificationTypes, token);
            }
            else if (token.Kind == SyntaxKind.IdentifierToken)
            {
                return GetClassificationForIdentifer(classificationTypes, token, syntaxTree);
            }
            else if (token.Kind == SyntaxKind.StringLiteralToken || token.Kind == SyntaxKind.CharacterLiteralToken)
            {
                return token.IsVerbatimStringLiteral()
                    ? classificationTypes.VerbatimStringLiteral
                    : classificationTypes.StringLiteral;
            }
            else if (token.Kind == SyntaxKind.NumericLiteralToken)
            {
                return classificationTypes.NumericLiteral;
            }

            return null;
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:35,代码来源:ClassificationExtensions.cs


示例4: GetClassificationForIdentifer

 private static IClassificationType GetClassificationForIdentifer(IClassificationTypes classificationTypes, SyntaxToken token, SyntaxTree syntaxTree)
 {
     if (token.Parent is TypeDeclarationSyntax &&
         ((token.Parent as TypeDeclarationSyntax).Identifier == token))
     {
         return GetClassificationForTypeDeclarationIdentifier(classificationTypes, token);
     }
     else if (token.Parent is EnumDeclarationSyntax &&
         (token.Parent as EnumDeclarationSyntax).Identifier == token)
     {
         return classificationTypes.EnumTypeName;
     }
     else if (token.Parent is DelegateDeclarationSyntax &&
         (token.Parent as DelegateDeclarationSyntax).Identifier == token)
     {
         return classificationTypes.DelegateTypeName;
     }
     else if (token.Parent is TypeParameterSyntax &&
         (token.Parent as TypeParameterSyntax).Identifier == token)
     {
         return classificationTypes.TypeParameterName;
     }
     else if (syntaxTree != null && (syntaxTree.IsActualContextualKeyword(token) || syntaxTree.CouldBeVarKeywordInDeclaration(token)))
     {
         return classificationTypes.Keyword;
     }
     else
     {
         return classificationTypes.Identifier;
     }
 }
开发者ID:Rickinio,项目名称:roslyn,代码行数:31,代码来源:ClassificationExtensions.cs


示例5: GetIndenter

 protected override AbstractIndenter GetIndenter(
     ISyntaxFactsService syntaxFacts, SyntaxTree syntaxTree, TextLine lineToBeIndented, IEnumerable<IFormattingRule> formattingRules, OptionSet optionSet, CancellationToken cancellationToken)
 {
     return new Indenter(
         syntaxFacts, syntaxTree, formattingRules,
         optionSet, lineToBeIndented, cancellationToken);
 }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:7,代码来源:CSharpIndentationService.cs


示例6: Init

		void Init(string code)
		{
			syntaxTree = SyntaxTree.Parse(code, "test.cs");
			unresolvedFile = syntaxTree.ToTypeSystem();
			compilation = TypeSystemHelper.CreateCompilation(unresolvedFile);
			findReferences = new FindReferences();
		}
开发者ID:Gobiner,项目名称:ILSpy,代码行数:7,代码来源:FindReferencesTest.cs


示例7: GetRegions

 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;
 }
开发者ID:nileshjagtap,项目名称:roslyn,代码行数:7,代码来源:DisabledTextOutlinerTests.cs


示例8: Resolve

        public static ResolveResult Resolve(Lazy<ICompilation> compilation, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree, TextLocation location, out AstNode node,
		                                    CancellationToken cancellationToken = default(CancellationToken))
        {
            node = syntaxTree.GetNodeAt(location);
            if (node == null || node is ArrayInitializerExpression)
                return null;
            if (node.Parent is UsingAliasDeclaration && node.Role == UsingAliasDeclaration.AliasRole) {
                var r = new CSharpAstResolver(compilation.Value, syntaxTree, unresolvedFile);
                return r.Resolve(((UsingAliasDeclaration)node.Parent).Import, cancellationToken);
            }
            if (CSharpAstResolver.IsUnresolvableNode(node)) {
                if (node is Identifier) {
                    node = node.Parent;
                } else if (node.NodeType == NodeType.Token) {
                    if (node.Parent is IndexerExpression || node.Parent is ConstructorInitializer) {
                        // There's no other place where one could hover to see the indexer's tooltip,
                        // so we need to resolve it when hovering over the '[' or ']'.
                        // For constructor initializer, the same applies to the 'base'/'this' token.
                        node = node.Parent;
                    } else {
                        return null;
                    }
                } else {
                    // don't resolve arbitrary nodes - we don't want to show tooltips for everything
                    return null;
                }
            } else {
                // It's a resolvable node.
                // However, we usually don't want to show the tooltip everywhere
                // For example, hovering with the mouse over an empty line between two methods causes
                // node==TypeDeclaration, but we don't want to show any tooltip.

                if (!node.GetChildByRole(Roles.Identifier).IsNull) {
                    // We'll suppress the tooltip for resolvable nodes if there is an identifier that
                    // could be hovered over instead:
                    return null;
                }
            }

            if (node == null)
                return null;

            if (node.Parent is ObjectCreateExpression && node.Role == Roles.Type) {
                node = node.Parent;
            }

            InvocationExpression parentInvocation = null;
            if ((node is IdentifierExpression || node is MemberReferenceExpression || node is PointerReferenceExpression) && node.Role != Roles.Argument) {
                // we also need to resolve the invocation
                parentInvocation = node.Parent as InvocationExpression;
            }

            // TODO: I think we should provide an overload so that an existing CSharpAstResolver can be reused
            CSharpAstResolver resolver = new CSharpAstResolver(compilation.Value, syntaxTree, unresolvedFile);
            ResolveResult rr = resolver.Resolve(node, cancellationToken);
            if (rr is MethodGroupResolveResult && parentInvocation != null)
                return resolver.Resolve(parentInvocation);
            else
                return rr;
        }
开发者ID:riviti,项目名称:NRefactory,代码行数:60,代码来源:ResolveAtLocation.cs


示例9: Create

            public static StringSplitter Create(
                Document document, int position,
                SyntaxTree syntaxTree, SyntaxNode root, SourceText sourceText,
                bool useTabs, int tabSize, CancellationToken cancellationToken)
            {
                var token = root.FindToken(position);

                if (token.IsKind(SyntaxKind.StringLiteralToken))
                {
                    return new SimpleStringSplitter(
                        document, position, syntaxTree, root,
                        sourceText, token, useTabs, tabSize,
                        cancellationToken);
                }

                var interpolatedStringExpression = TryGetInterpolatedStringExpression(token, position);
                if (interpolatedStringExpression != null)
                {
                    return new InterpolatedStringSplitter(
                        document, position, syntaxTree, root,
                        sourceText, interpolatedStringExpression,
                        useTabs, tabSize, cancellationToken);
                }

                return null;
            }
开发者ID:RoryVL,项目名称:roslyn,代码行数:26,代码来源:SplitStringLiteralCommandHandler.StringSplitter.cs


示例10: setSource

 public void setSource(string source)
 {
     this.source = source;
     this.tree = ASTUtil.GetSyntaxTreeFromSource(source);
     methods = ASTUtil.GetAllMethodDeclarations(tree);
     blocks = new List<string>();
     methodNames = new List<string>();
     foreach (MethodDeclarationSyntax method in methods)
     {
         SyntaxNode block = ASTUtil.GetBlockOfMethod(method);
         if(block != null)
         {
             StringBuilder sb = new StringBuilder();
             IEnumerable<SyntaxNode> stats = ASTUtil.GetStatementsInNode(block);
             foreach(StatementSyntax st in stats)
             {
                 sb.AppendLine(st.GetText());
             }
             blocks.Add(sb.ToString());
         }
         else
         {
             blocks.Add("");
         }
         methodNames.Add(method.Identifier.GetText());
     }
 }
开发者ID:nkcsgexi,项目名称:ghostfactor1,代码行数:27,代码来源:MethodBodyRetriever.cs


示例11: AbstractIndenter

            public AbstractIndenter(
                ISyntaxFactsService syntaxFacts,
                SyntaxTree syntaxTree,
                IEnumerable<IFormattingRule> rules,
                OptionSet optionSet,
                TextLine lineToBeIndented,
                CancellationToken cancellationToken)
            {
                var syntaxRoot = syntaxTree.GetRoot(cancellationToken);

                this._syntaxFacts = syntaxFacts;
                this.OptionSet = optionSet;
                this.Tree = syntaxTree;
                this.LineToBeIndented = lineToBeIndented;
                this.TabSize = this.OptionSet.GetOption(FormattingOptions.TabSize, syntaxRoot.Language);
                this.CancellationToken = cancellationToken;

                this.Rules = rules;
                this.Finder = new BottomUpBaseIndentationFinder(
                         new ChainedFormattingRules(this.Rules, OptionSet),
                         this.TabSize,
                         this.OptionSet.GetOption(FormattingOptions.IndentationSize, syntaxRoot.Language),
                         tokenStream: null,
                         lastToken: default(SyntaxToken));
            }
开发者ID:Rickinio,项目名称:roslyn,代码行数:25,代码来源:AbstractIndentationService.AbstractIndenter.cs


示例12: GetSpanIn

 private TextSpan GetSpanIn(SyntaxTree syntaxTree, string textToFind)
 {
     string s = syntaxTree.GetText().ToString();
     int index = s.IndexOf(textToFind);
     Assert.True(index >= 0, "textToFind not found in the tree");
     return new TextSpan(index, textToFind.Length);
 }
开发者ID:riversky,项目名称:roslyn,代码行数:7,代码来源:LocationsTests.cs


示例13: visit

 public override void visit(SyntaxTree.var_statement defs)
 {
     indef = true;
     ProcessNode(defs.var_def.vars); // исключаем типы - 
       // просматриваем только имена переменных
     indef = false;
 }
开发者ID:Slav76,项目名称:pascalabcnet,代码行数:7,代码来源:LambdaHelper.cs


示例14: ToolTipData

			public ToolTipData (ICSharpCode.NRefactory.CSharp.SyntaxTree unit, ICSharpCode.NRefactory.Semantics.ResolveResult result, ICSharpCode.NRefactory.CSharp.AstNode node, CSharpAstResolver file)
			{
				this.Unit = unit;
				this.Result = result;
				this.Node = node;
				this.Resolver = file;
			}
开发者ID:kthguru,项目名称:monodevelop,代码行数:7,代码来源:LanguageItemTooltipProvider.cs


示例15: AssertMappedSpanEqual

        private void AssertMappedSpanEqual(
            SyntaxTree syntaxTree,
            string sourceText,
            string expectedPath,
            int expectedStartLine,
            int expectedStartOffset,
            int expectedEndLine,
            int expectedEndOffset,
            bool hasMappedPath)
        {
            var span = GetSpanIn(syntaxTree, sourceText);
            var mappedSpan = syntaxTree.GetMappedLineSpan(span);
            var actualDisplayPath = syntaxTree.GetDisplayPath(span, s_resolver);

            Assert.Equal(hasMappedPath, mappedSpan.HasMappedPath);
            Assert.Equal(expectedPath, mappedSpan.Path);
            if (expectedPath == "")
            {
                Assert.Equal("", actualDisplayPath);
            }
            else
            {
                Assert.Equal(string.Format("[{0};{1}]", expectedPath, hasMappedPath ? syntaxTree.FilePath : null), actualDisplayPath);
            }

            Assert.Equal(expectedStartLine, mappedSpan.StartLinePosition.Line);
            Assert.Equal(expectedStartOffset, mappedSpan.StartLinePosition.Character);
            Assert.Equal(expectedEndLine, mappedSpan.EndLinePosition.Line);
            Assert.Equal(expectedEndOffset, mappedSpan.EndLinePosition.Character);
        }
开发者ID:GloryChou,项目名称:roslyn,代码行数:30,代码来源:LocationsTests.cs


示例16: RecoverNode

        protected static SyntaxNode RecoverNode(SyntaxTree tree, TextSpan textSpan, int kind)
        {
            var token = tree.GetRoot().FindToken(textSpan.Start, findInsideTrivia: true);
            var node = token.Parent;

            while (node != null)
            {
                if (node.Span == textSpan && node.RawKind == kind)
                {
                    return node;
                }

                var structuredTrivia = node as IStructuredTriviaSyntax;
                if (structuredTrivia != null)
                {
                    node = structuredTrivia.ParentTrivia.Token.Parent;
                }
                else
                {
                    node = node.Parent;
                }
            }

            throw Contract.Unreachable;
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:25,代码来源:AbstractSyntaxTreeFactoryService.cs


示例17: RemoveCachedSemanticModel

 public bool RemoveCachedSemanticModel(SyntaxTree tree)
 {
     lock (_semanticModelsMap)
     {
         return _semanticModelsMap.Remove(tree);
     }
 }
开发者ID:e42s,项目名称:roslyn,代码行数:7,代码来源:AnalyzerDriver.CompilationData.cs


示例18: WriteDocumentationCommentXml

        /// <summary>
        /// Traverses the symbol table processing XML documentation comments and optionally writing them to
        /// a provided stream.
        /// </summary>
        /// <param name="compilation">Compilation that owns the symbol table.</param>
        /// <param name="assemblyName">Assembly name override, if specified. Otherwise the <see cref="ISymbol.Name"/> of the source assembly is used.</param>
        /// <param name="xmlDocStream">Stream to which XML will be written, if specified.</param>
        /// <param name="diagnostics">Will be supplemented with documentation comment diagnostics.</param>
        /// <param name="cancellationToken">To stop traversing the symbol table early.</param>
        /// <param name="filterTree">Only report diagnostics from this syntax tree, if non-null.</param>
        /// <param name="filterSpanWithinTree">If <paramref name="filterTree"/> and filterSpanWithinTree is non-null, report diagnostics within this span in the <paramref name="filterTree"/>.</param>
        public static void WriteDocumentationCommentXml(CSharpCompilation compilation, string assemblyName, Stream xmlDocStream, DiagnosticBag diagnostics, CancellationToken cancellationToken, SyntaxTree filterTree = null, TextSpan? filterSpanWithinTree = null)
        {
            StreamWriter writer = null;
            if (xmlDocStream != null && xmlDocStream.CanWrite)
            {
                writer = new StreamWriter(
                    stream: xmlDocStream,
                    encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false),
                    bufferSize: 0x400, // Default.
                    leaveOpen: true); // Don't close caller's stream.
            }

            using (writer)
            {
                var compiler = new DocumentationCommentCompiler(assemblyName ?? compilation.SourceAssembly.Name, compilation, writer, filterTree, filterSpanWithinTree,
                    processIncludes: true, isForSingleSymbol: false, diagnostics: diagnostics, cancellationToken: cancellationToken);
                compiler.Visit(compilation.SourceAssembly.GlobalNamespace);
                Debug.Assert(compiler._indentDepth == 0);
            }

            if (filterTree != null)
            {
                // Will respect the DocumentationMode.
                UnprocessedDocumentationCommentFinder.ReportUnprocessed(filterTree, filterSpanWithinTree, diagnostics, cancellationToken);
            }
            else
            {
                foreach (SyntaxTree tree in compilation.SyntaxTrees)
                {
                    // Will respect the DocumentationMode.
                    UnprocessedDocumentationCommentFinder.ReportUnprocessed(tree, null, diagnostics, cancellationToken);
                }
            }
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:45,代码来源:DocumentationCommentCompiler.cs


示例19: PathSyntaxReference

 public PathSyntaxReference(SyntaxNode node)
 {
     this.tree = node.SyntaxTree;
     this.kind = node.CSharpKind();
     this.textSpan = node.Span;
     this.pathFromRoot = ComputePathFromRoot(node);
 }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:7,代码来源:CSharpSyntaxTreeFactory.PathSyntaxReference.cs


示例20: CheckResult

        protected override void CheckResult(bool validLocation, int position, SyntaxTree syntaxTree)
        {
            var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, CancellationToken.None);
            var isPossibleTupleContext = syntaxTree.IsPossibleTupleContext(leftToken, position);

            Assert.Equal(validLocation, isPossibleTupleContext);
        }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:7,代码来源:PossibleTupleContextTests.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# SyntaxTreeAnalysisContext类代码示例发布时间:2022-05-24
下一篇:
C# SyntaxTokenList类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap