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


C# Document.GetSyntaxTreeAsync方法代码示例

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


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

示例1: GetItemAsync

        public async Task<QuickInfoItem> GetItemAsync(
            Document document,
            int position,
            CancellationToken cancellationToken)
        {
            var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
            var token = await tree.GetTouchingTokenAsync(position, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);

            var state = await GetQuickInfoItemAsync(document, token, position, cancellationToken).ConfigureAwait(false);
            if (state != null)
            {
                return state;
            }

            if (ShouldCheckPreviousToken(token))
            {
                var previousToken = token.GetPreviousToken();

                if ((state = await GetQuickInfoItemAsync(document, previousToken, position, cancellationToken).ConfigureAwait(false)) != null)
                {
                    return state;
                }
            }

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

示例2: AnalyzeSemanticsAsync

        public override async Task AnalyzeSemanticsAsync(Document document, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
        {
            try
            {
                var encService = document.Project.Solution.Workspace.Services.GetService<IEditAndContinueWorkspaceService>();
                if (encService == null)
                {
                    return;
                }

                EditSession session = encService.EditSession;
                if (session == null || !session.HasProject(document.Project.Id))
                {
                    return;
                }

                var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
                var analysis = await session.GetDocumentAnalysis(document).GetValueAsync(cancellationToken).ConfigureAwait(false);
                if (!analysis.RudeEditErrors.IsDefault)
                {
                    session.LogRudeEditErrors(analysis.RudeEditErrors);

                    foreach (var error in analysis.RudeEditErrors)
                    {
                        addDiagnostic(error.ToDiagnostic(tree));
                    }
                }
            }
            catch (Exception e) when(FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
            }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:33,代码来源:RudeEditUserDiagnosticAnalyzer.cs

示例3: AnalyzeSyntaxAsync

            public async Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken)
            {
                if (!document.SupportsSyntaxTree)
                {
                    return;
                }

                // getting tree is cheap since tree always stays in memory
                var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
                var length = tree.Length;

                while (true)
                {
                    if (_map.TryAdd(document.Id, length))
                    {
                        Interlocked.Add(ref _size, length);
                        return;
                    }

                    long size;
                    if (_map.TryGetValue(document.Id, out size))
                    {
                        if (size == length)
                        {
                            return;
                        }

                        if (_map.TryUpdate(document.Id, length, size))
                        {
                            Interlocked.Add(ref _size, length - size);
                            return;
                        }
                    }
                }
            }
开发者ID:jkotas,项目名称:roslyn,代码行数:35,代码来源:SolutionSizeTracker.cs

示例4: AnalyzeSemanticsAsync

        public override async Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken)
        {
            try
            {
                var encService = document.Project.Solution.Workspace.Services.GetService<IEditAndContinueWorkspaceService>();
                if (encService == null)
                {
                    return ImmutableArray<Diagnostic>.Empty;
                }

                EditSession session = encService.EditSession;
                if (session == null ||
                    session.BaseSolution.WorkspaceVersion == document.Project.Solution.WorkspaceVersion ||
                    !session.HasProject(document.Project.Id))
                {
                    return ImmutableArray<Diagnostic>.Empty;
                }

                var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
                var analysis = await session.GetDocumentAnalysis(document).GetValueAsync(cancellationToken).ConfigureAwait(false);
                if (analysis.RudeEditErrors.IsDefault)
                {
                    return ImmutableArray<Diagnostic>.Empty;
                }

                session.LogRudeEditErrors(analysis.RudeEditErrors);
                return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree);
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:33,代码来源:RudeEditUserDiagnosticAnalyzer.cs

示例5: GetItemsWorkerAsync

        protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(Document document, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken)
        {
            var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

            if (tree.IsInNonUserCode(position, cancellationToken))
            {
                return null;
            }

            var targetToken = tree.FindTokenOnLeftOfPosition(position, cancellationToken).GetPreviousTokenIfTouchingWord(position);
            if (targetToken.IsKind(SyntaxKind.AliasKeyword) && targetToken.Parent.IsKind(SyntaxKind.ExternAliasDirective))
            {
                var compilation = await document.GetCSharpCompilationAsync(cancellationToken).ConfigureAwait(false);
                var aliases = compilation.ExternalReferences.SelectMany(r => r.Properties.Aliases).ToSet();

                if (aliases.Any())
                {
                    var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
                    var usedAliases = root.ChildNodes().OfType<ExternAliasDirectiveSyntax>().Where(e => !e.Identifier.IsMissing).Select(e => e.Identifier.ValueText);
                    aliases.RemoveRange(usedAliases);
                    aliases.Remove(MetadataReferenceProperties.GlobalAlias);
                    var textChangeSpan = CompletionUtilities.GetTextChangeSpan(await document.GetTextAsync(cancellationToken).ConfigureAwait(false), position);
                    return aliases.Select(e =>
                        new CompletionItem(this, e, textChangeSpan, glyph: Glyph.Namespace));
                }
            }

            return SpecializedCollections.EmptyEnumerable<CompletionItem>();
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:29,代码来源:ExternAliasCompletionProvider.cs

示例6: IsContext

        public static bool IsContext(Document document, int position, CancellationToken cancellationToken)
        {
            // Check to see if we're to the right of an $ or an @$
            var text = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);

            var start = position - 1;
            if (start < 0)
            {
                return false;
            }

            if (text[start] == '@')
            {
                start--;

                if (start < 0)
                {
                    return false;
                }
            }

            if (text[start] != '$')
            {
                return false;
            }

            var tree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var token = tree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition(start);

            return tree.IsExpressionContext(start, token, attributes: false, cancellationToken: cancellationToken)
                || tree.IsStatementContext(start, token, cancellationToken);
        }
开发者ID:RoryVL,项目名称:roslyn,代码行数:32,代码来源:InterpolatedStringCompletionSession.cs

示例7: AddSyntacticClassificationsAsync

        public async Task AddSyntacticClassificationsAsync(Document document, TextSpan textSpan, List<ClassifiedSpan> result, CancellationToken cancellationToken)
        {
            var classificationService = document.GetLanguageService<IClassificationService>();
            var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

            classificationService.AddSyntacticClassifications(syntaxTree, textSpan, result, cancellationToken);
        }
开发者ID:GloryChou,项目名称:roslyn,代码行数:7,代码来源:AbstractEditorClassificationService.cs

示例8: GetSnippetsForDocumentAsync

        private async Task<IEnumerable<CompletionItem>> GetSnippetsForDocumentAsync(
            Document document, int position, Workspace workspace, CancellationToken cancellationToken)
        {
            var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
            var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
            var semanticFacts = document.GetLanguageService<ISemanticFactsService>();

            if (syntaxFacts.IsInNonUserCode(syntaxTree, position, cancellationToken) ||
                syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken) ||
                syntaxFacts.GetContainingTypeDeclaration(await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false), position) is EnumDeclarationSyntax)
            {
                return SpecializedCollections.EmptyEnumerable<CompletionItem>();
            }

            var span = new TextSpan(position, 0);
            var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
            var isPossibleTupleContext = syntaxFacts.IsPossibleTupleContext(syntaxTree, position, cancellationToken);

            if (semanticFacts.IsPreProcessorDirectiveContext(semanticModel, position, cancellationToken))
            {
                var directive = syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition(position, includeDirectives: true).GetAncestor<DirectiveTriviaSyntax>();
                if (directive.DirectiveNameToken.IsKind(
                    SyntaxKind.IfKeyword,
                    SyntaxKind.RegionKeyword,
                    SyntaxKind.ElseKeyword,
                    SyntaxKind.ElifKeyword,
                    SyntaxKind.ErrorKeyword,
                    SyntaxKind.LineKeyword,
                    SyntaxKind.PragmaKeyword,
                    SyntaxKind.EndIfKeyword,
                    SyntaxKind.UndefKeyword,
                    SyntaxKind.EndRegionKeyword,
                    SyntaxKind.WarningKeyword))
                {
                    return SpecializedCollections.EmptyEnumerable<CompletionItem>();
                }

                return await GetSnippetCompletionItemsAsync(workspace, semanticModel, isPreProcessorContext: true,
                        isTupleContext: isPossibleTupleContext, cancellationToken: cancellationToken).ConfigureAwait(false);
            }

            if (semanticFacts.IsGlobalStatementContext(semanticModel, position, cancellationToken) ||
                semanticFacts.IsExpressionContext(semanticModel, position, cancellationToken) ||
                semanticFacts.IsStatementContext(semanticModel, position, cancellationToken) ||
                semanticFacts.IsTypeContext(semanticModel, position, cancellationToken) ||
                semanticFacts.IsTypeDeclarationContext(semanticModel, position, cancellationToken) ||
                semanticFacts.IsNamespaceContext(semanticModel, position, cancellationToken) ||
                semanticFacts.IsNamespaceDeclarationNameContext(semanticModel, position, cancellationToken) ||
                semanticFacts.IsMemberDeclarationContext(semanticModel, position, cancellationToken) ||
                semanticFacts.IsLabelContext(semanticModel, position, cancellationToken))
            {
                return await GetSnippetCompletionItemsAsync(workspace, semanticModel, isPreProcessorContext: false,
                    isTupleContext: isPossibleTupleContext, cancellationToken: cancellationToken).ConfigureAwait(false);
            }

            return SpecializedCollections.EmptyEnumerable<CompletionItem>();
        }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:57,代码来源:SnippetCompletionProvider.cs

示例9: GetItemsWorkerAsync

        protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(Document document, int position, CompletionTriggerInfo triggerInfo, System.Threading.CancellationToken cancellationToken)
        {
            var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
            if (!tree.IsEntirelyWithinCrefSyntax(position, cancellationToken))
            {
                return null;
            }

            var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken);
            token = token.GetPreviousTokenIfTouchingWord(position);
            if (token.Kind() == SyntaxKind.None)
            {
                return null;
            }

            var result = SpecializedCollections.EmptyEnumerable<ISymbol>();

            // To get a Speculative SemanticModel (which is much faster), we need to 
            // walk up to the node the DocumentationTrivia is attached to.
            var parentNode = token.GetAncestor<DocumentationCommentTriviaSyntax>().ParentTrivia.Token.Parent;
            var semanticModel = await document.GetSemanticModelForNodeAsync(parentNode, cancellationToken).ConfigureAwait(false);

            // cref ""|, ""|"", ""a|""
            if (token.IsKind(SyntaxKind.DoubleQuoteToken, SyntaxKind.SingleQuoteToken) && token.Parent.IsKind(SyntaxKind.XmlCrefAttribute))
            {
                result = semanticModel.LookupSymbols(token.SpanStart)
                                        .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation);

                result = result.Concat(GetOperatorsAndIndexers(token, semanticModel, cancellationToken));
            }
            else if (IsSignatureContext(token))
            {
                result = semanticModel.LookupNamespacesAndTypes(token.SpanStart)
                                        .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation);
            }
            else if (token.IsKind(SyntaxKind.DotToken) && token.Parent.IsKind(SyntaxKind.QualifiedCref))
            {
                // cref "a.|"
                var parent = token.Parent as QualifiedCrefSyntax;
                var leftType = semanticModel.GetTypeInfo(parent.Container, cancellationToken).Type;
                var leftSymbol = semanticModel.GetSymbolInfo(parent.Container, cancellationToken).Symbol;

                var container = leftSymbol ?? leftType;

                result = semanticModel.LookupSymbols(token.SpanStart, container: (INamespaceOrTypeSymbol)container)
                                        .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation);

                if (container is INamedTypeSymbol)
                {
                    result = result.Concat(((INamedTypeSymbol)container).InstanceConstructors);
                }
            }

            return await CreateItemsAsync(document.Project.Solution.Workspace, semanticModel,
                position, result, token, cancellationToken).ConfigureAwait(false);
        }
开发者ID:GloryChou,项目名称:roslyn,代码行数:56,代码来源:CrefCompletionProvider.cs

示例10: CheckCodeContext

        protected virtual bool CheckCodeContext(Document document, int position, char openingBrace, CancellationToken cancellationToken)
        {
            this.AssertIsForeground();

            // check that the user is not typing in a string literal or comment
            var tree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();

            return !syntaxFactsService.IsInNonUserCode(tree, position, cancellationToken);
        }
开发者ID:RoryVL,项目名称:roslyn,代码行数:10,代码来源:AbstractEditorBraceCompletionSessionFactory.cs

示例11: GetSpeculativeTCompletions

        private async Task<IEnumerable<CompletionItem>> GetSpeculativeTCompletions(Document document, int position, CancellationToken cancellationToken)
        {
            var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
            if (syntaxTree.IsInNonUserCode(position, cancellationToken) ||
                syntaxTree.IsPreProcessorDirectiveContext(position, cancellationToken))
            {
                return SpecializedCollections.EmptyEnumerable<CompletionItem>();
            }

            // If we're in a generic type argument context, use the start of the generic type name
            // as the position for the rest of the context checks.
            int testPosition = position;
            var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);

            var semanticModel = await document.GetSemanticModelForNodeAsync(leftToken.Parent, cancellationToken).ConfigureAwait(false);
            if (syntaxTree.IsGenericTypeArgumentContext(position, leftToken, cancellationToken, semanticModel))
            {
                // Walk out until we find the start of the partial written generic
                SyntaxToken nameToken;
                while (syntaxTree.IsInPartiallyWrittenGeneric(testPosition, cancellationToken, out nameToken))
                {
                    testPosition = nameToken.SpanStart;
                }

                // If the user types Foo<T, automatic brace completion will insert the close brace
                // and the generic won't be "partially written".
                if (testPosition == position)
                {
                    var typeArgumentList = leftToken.GetAncestor<TypeArgumentListSyntax>();
                    if (typeArgumentList != null)
                    {
                        if (typeArgumentList.LessThanToken != default(SyntaxToken) && typeArgumentList.GreaterThanToken != default(SyntaxToken))
                        {
                            testPosition = typeArgumentList.LessThanToken.SpanStart;
                        }
                    }
                }
            }

            if ((!leftToken.GetPreviousTokenIfTouchingWord(position).IsKindOrHasMatchingText(SyntaxKind.AsyncKeyword) &&
                syntaxTree.IsMemberDeclarationContext(testPosition, contextOpt: null, validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) ||
                syntaxTree.IsGlobalMemberDeclarationContext(testPosition, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
                syntaxTree.IsGlobalStatementContext(testPosition, cancellationToken) ||
                syntaxTree.IsDelegateReturnTypeContext(testPosition, syntaxTree.FindTokenOnLeftOfPosition(testPosition, cancellationToken), cancellationToken))
            {
                var text = await syntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
                var textChangeSpan = this.GetTextChangeSpan(text, position);

                const string T = "T";
                return SpecializedCollections.SingletonEnumerable(
                    new CompletionItem(this, T, textChangeSpan, descriptionFactory: null, glyph: Glyph.TypeParameter));
            }

            return SpecializedCollections.EmptyEnumerable<CompletionItem>();
        }
开发者ID:noahstein,项目名称:roslyn,代码行数:55,代码来源:SpeculativeTCompletionProvider.cs

示例12: CreateAsync

 internal static async Task<ItemGetter> CreateAsync(
     AbstractOverrideCompletionProvider overrideCompletionProvider,
     Document document,
     int position,
     CancellationToken cancellationToken)
 {
     var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
     var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
     var startLineNumber = text.Lines.IndexOf(position);
     var startLine = text.Lines[startLineNumber];
     return new ItemGetter(overrideCompletionProvider, document, position, text, syntaxTree, startLineNumber, startLine, cancellationToken);
 }
开发者ID:TyOverby,项目名称:roslyn,代码行数:12,代码来源:AbstractOverrideCompletionProvider.ItemGetter.cs

示例13: GetItemsWorkerAsync

        protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(Document document, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken)
        {
            var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

            DeclarationModifiers modifiers;
            SyntaxToken token;
            if (!IsPartialCompletionContext(tree, position, cancellationToken, out modifiers, out token))
            {
                return null;
            }

            return await CreatePartialItemsAsync(document, position, modifiers, token, cancellationToken).ConfigureAwait(false);
        }
开发者ID:noahstein,项目名称:roslyn,代码行数:13,代码来源:AbstractPartialCompletionProvider.cs

示例14: ItemGetter

            public ItemGetter(
                AbstractOverrideCompletionProvider overrideCompletionProvider,
                Document document, int position, CancellationToken cancellationToken)
            {
                _provider = overrideCompletionProvider;
                _document = document;
                _position = position;
                _cancellationToken = cancellationToken;

                _text = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
                _syntaxTree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
                _startLineNumber = _text.Lines.IndexOf(position);
                _startLine = _text.Lines[_startLineNumber];
            }
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:14,代码来源:AbstractOverrideCompletionProvider.ItemGetter.cs

示例15: TryCompleteTag

        protected override void TryCompleteTag(ITextView textView, ITextBuffer subjectBuffer, Document document, SnapshotPoint position, CancellationToken cancellationToken)
        {
            var tree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true);

            if (token.IsKind(SyntaxKind.GreaterThanToken))
            {
                var parentStartTag = token.Parent as XmlElementStartTagSyntax;
                if (parentStartTag == null)
                {
                    return;
                }

                // Slightly special case: <blah><blah$$</blah>
                // If we already have a matching end tag and we're parented by 
                // an xml element with the same start tag and a missing/non-matching end tag, 
                // do completion anyway. Generally, if this is the case, we have to walk
                // up the parent elements until we find an unmatched start tag.

                if (parentStartTag.Name.LocalName.ValueText.Length > 0 && HasMatchingEndTag(parentStartTag))
                {
                    if (HasUnmatchedIdenticalParent(parentStartTag))
                    {
                        InsertTextAndMoveCaret(textView, subjectBuffer, position, "</" + parentStartTag.Name.LocalName.ValueText + ">", position);
                        return;
                    }
                }

                CheckNameAndInsertText(textView, subjectBuffer, position, parentStartTag, position.Position, "</{0}>");
            }
            else if (token.IsKind(SyntaxKind.LessThanSlashToken))
            {
                // /// <summary>
                // /// </$$
                // /// </summary>
                // We need to check for non-trivia XML text tokens after $$ that match the expected end tag text.

                if (token.Parent.IsKind(SyntaxKind.XmlElementEndTag) &&
                    token.Parent.IsParentKind(SyntaxKind.XmlElement))
                {
                    var parentElement = token.Parent.Parent as XmlElementSyntax;

                    if (!HasFollowingEndTagTrivia(parentElement, token))
                    {
                        CheckNameAndInsertText(textView, subjectBuffer, position, parentElement.StartTag, null, "{0}>");
                    }
                }
            }
        }
开发者ID:RoryVL,项目名称:roslyn,代码行数:49,代码来源:XmlTagCompletionCommandHandler.cs


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