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


C# Document.GetSyntaxRootSynchronously方法代码示例

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


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

示例1: Format

        public Document Format(Document document, IEnumerable<TextSpan> changes, CancellationToken cancellationToken)
        {
            var root = document.GetSyntaxRootSynchronously(cancellationToken);
            var formattingSpans = changes.Select(s => CommonFormattingHelpers.GetFormattingSpan(root, s));

            return Formatter.FormatAsync(document, formattingSpans, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:7,代码来源:AbstractCommentUncommentService.cs

示例2: IsThirdPartyNavigationAllowed

        private static bool IsThirdPartyNavigationAllowed(ISymbol symbolToNavigateTo, int caretPosition, Document document, CancellationToken cancellationToken)
        {
            var syntaxRoot = document.GetSyntaxRootSynchronously(cancellationToken);
            var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();
            var containingTypeDeclaration = syntaxFactsService.GetContainingTypeDeclaration(syntaxRoot, caretPosition);

            if (containingTypeDeclaration != null)
            {
                var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
                var containingTypeSymbol = semanticModel.GetDeclaredSymbol(containingTypeDeclaration, cancellationToken) as ITypeSymbol;

                // Allow third parties to navigate to all symbols except types/constructors
                // if we are navigating from the corresponding type.

                if (containingTypeSymbol != null &&
                    (symbolToNavigateTo is ITypeSymbol || symbolToNavigateTo.IsConstructor()))
                {
                    var candidateTypeSymbol = symbolToNavigateTo is ITypeSymbol
                        ? symbolToNavigateTo
                        : symbolToNavigateTo.ContainingType;

                    if (containingTypeSymbol == candidateTypeSymbol)
                    {
                        // We are navigating from the same type, so don't allow third parties to perform the navigation.
                        // This ensures that if we navigate to a class from within that class, we'll stay in the same file
                        // rather than navigate to, say, XAML.
                        return false;
                    }
                }
            }

            return true;
        }
开发者ID:vslsnap,项目名称:roslyn,代码行数:33,代码来源:AbstractGoToDefinitionService.cs

示例3: TreatAsReturn

        protected override bool TreatAsReturn(Document document, int position, CancellationToken cancellationToken)
        {
            var root = document.GetSyntaxRootSynchronously(cancellationToken);

            var endToken = root.FindToken(position);
            if (endToken.IsMissing)
            {
                return false;
            }

            var tokenToLeft = root.FindTokenOnLeftOfPosition(position);
            var startToken = endToken.GetPreviousToken();

            // case 1:
            //      Consider code like so: try {|}
            //      With auto brace completion on, user types `{` and `Return` in a hurry.
            //      During typing, it is possible that shift was still down and not released after typing `{`.
            //      So we've got an unintentional `shift + enter` and also we have nothing to complete this, 
            //      so we put in a newline,
            //      which generates code like so : try { } 
            //                                     |
            //      which is not useful as : try {
            //                                  |
            //                               }
            //      To support this, we treat `shift + enter` like `enter` here.
            var afterOpenBrace = startToken.Kind() == SyntaxKind.OpenBraceToken
                              && endToken.Kind() == SyntaxKind.CloseBraceToken
                              && tokenToLeft == startToken
                              && endToken.Parent.IsKind(SyntaxKind.Block)
                              && FormattingRangeHelper.AreTwoTokensOnSameLine(startToken, endToken);

            return afterOpenBrace;
        }
开发者ID:jkotas,项目名称:roslyn,代码行数:33,代码来源:AutomaticLineEnderCommandHandler.cs

示例4: FormatAndApply

        protected override void FormatAndApply(Document document, int position, CancellationToken cancellationToken)
        {
            var root = document.GetSyntaxRootSynchronously(cancellationToken);

            var endToken = root.FindToken(position);
            if (endToken.IsMissing)
            {
                return;
            }

            var ranges = FormattingRangeHelper.FindAppropriateRange(endToken, useDefaultRange: false);
            if (ranges == null)
            {
                return;
            }

            var startToken = ranges.Value.Item1;
            if (startToken.IsMissing || startToken.Kind() == SyntaxKind.None)
            {
                return;
            }

            var options = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);

            var changes = Formatter.GetFormattedTextChanges(root, new TextSpan[] { TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End) }, document.Project.Solution.Workspace, options,
                rules: null, // use default
                cancellationToken: cancellationToken);

            document.ApplyTextChanges(changes.ToArray(), cancellationToken);
        }
开发者ID:jkotas,项目名称:roslyn,代码行数:30,代码来源:AutomaticLineEnderCommandHandler.cs

示例5: 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 root = document.GetSyntaxRootSynchronously(cancellationToken);
            var token = root.FindTokenOnLeftOfPosition(start);

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

示例6: GetDesiredIndentation

        public IndentationResult? GetDesiredIndentation(
            Document document, int lineNumber, CancellationToken cancellationToken)
        {
            var root = document.GetSyntaxRootSynchronously(cancellationToken);
            var sourceText = root.SyntaxTree.GetText(cancellationToken);
            var documentOptions = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);

            var lineToBeIndented = sourceText.Lines[lineNumber];

            var formattingRules = GetFormattingRules(document, lineToBeIndented.Start);

            // There are two important cases for indentation.  The first is when we're simply
            // trying to figure out the appropriate indentation on a blank line (i.e. after
            // hitting enter at the end of a line, or after moving to a blank line).  The 
            // second is when we're trying to figure out indentation for a non-blank line
            // (i.e. after hitting enter in the middle of a line, causing tokens to move to
            // the next line).  If we're in the latter case, we defer to the Formatting engine
            // as we need it to use all its rules to determine where the appropriate location is
            // for the following tokens to go.
            if (ShouldUseSmartTokenFormatterInsteadOfIndenter(formattingRules, root, lineToBeIndented, documentOptions, cancellationToken))
            {
                return null;
            }

            var indenter = GetIndenter(
                document.GetLanguageService<ISyntaxFactsService>(),
                root.SyntaxTree, lineToBeIndented, formattingRules,
                documentOptions, cancellationToken);

            return indenter.GetDesiredIndentation(document);
        }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:31,代码来源:AbstractIndentationService.cs

示例7: 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.GetSyntaxRootSynchronously(cancellationToken).SyntaxTree;
            var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();

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

示例8: GetOutliningSpans

        /// <summary>
        /// Keep in sync with <see cref="GetOutliningSpansAsync"/>
        /// </summary>
        public IList<OutliningSpan> GetOutliningSpans(
            Document document, CancellationToken cancellationToken)
        {
            try
            {
                var syntaxRoot = document.GetSyntaxRootSynchronously(cancellationToken);

                // change this to shared pool once RI
                var regions = new List<OutliningSpan>();
                RegionCollector.CollectOutliningSpans(document, syntaxRoot, _nodeOutlinerMap, _triviaOutlinerMap, regions, cancellationToken);
                return regions;
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:20,代码来源:AbstractOutliningService.cs

示例9: IsContext

        public static bool IsContext(Document document, int position, CancellationToken cancellationToken)
        {
            // First, check to see if the character to the left of the position is an open curly. If it is,
            // we shouldn't complete because the user may be trying to escape a curly.
            var text = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var index = position - 1;
            var openCurlyCount = 0;
            while (index >= 0)
            {
                if (text[index] == '{')
                {
                    openCurlyCount++;
                }
                else
                {
                    break;
                }

                index--;
            }

            if (openCurlyCount > 0 && openCurlyCount % 2 == 1)
            {
                return false;
            }

            // Next, check to see if we're typing in an interpolated string
            var root = document.GetSyntaxRootSynchronously(cancellationToken);
            var token = root.FindTokenOnLeftOfPosition(position);

            if (!token.Span.IntersectsWith(position))
            {
                return false;
            }

            return token.IsKind(
                SyntaxKind.InterpolatedStringStartToken,
                SyntaxKind.InterpolatedVerbatimStringStartToken,
                SyntaxKind.InterpolatedStringTextToken,
                SyntaxKind.InterpolatedStringEndToken);
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:41,代码来源:InterpolationCompletionSession.cs

示例10: GetDesiredIndentation

        public IndentationResult? GetDesiredIndentation(Document document, int lineNumber, CancellationToken cancellationToken)
        {
            var root = document.GetSyntaxRootSynchronously(cancellationToken);
            var sourceText = root.SyntaxTree.GetText(cancellationToken);

            var lineToBeIndented = sourceText.Lines[lineNumber];

            var formattingRules = GetFormattingRules(document, lineToBeIndented.Start);

            // enter on a token case.
            if (ShouldUseSmartTokenFormatterInsteadOfIndenter(formattingRules, root, lineToBeIndented, document.Options, cancellationToken))
            {
                return null;
            }

            var indenter = GetIndenter(
                document.GetLanguageService<ISyntaxFactsService>(),
                root.SyntaxTree, lineToBeIndented, formattingRules,
                document.Options, cancellationToken);

            return indenter.GetDesiredIndentation();
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:22,代码来源:AbstractIndentationService.cs

示例11: CreateChangedDocumentPreviewViewAsync

        public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, double zoomLevel, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            // Note: We don't use the original buffer that is associated with oldDocument
            // (and currently open in the editor) for oldBuffer below. This is because oldBuffer
            // will be used inside a projection buffer inside our inline diff preview below
            // and platform's implementation currently has a bug where projection buffers
            // are being leaked. This leak means that if we use the original buffer that is
            // currently visible in the editor here, the projection buffer span calculation
            // would be triggered every time user changes some code in this buffer (even though
            // the diff view would long have been dismissed by the time user edits the code)
            // resulting in crashes. Instead we create a new buffer from the same content.
            // TODO: We could use ITextBufferCloneService instead here to clone the original buffer.
            var oldBuffer = CreateNewBuffer(oldDocument, cancellationToken);
            var newBuffer = CreateNewBuffer(newDocument, cancellationToken);

            // Convert the diffs to be line based.  
            // Compute the diffs between the old text and the new.
            var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken);

            // Need to show the spans in the right that are different.
            // We also need to show the spans that are in conflict.
            var originalSpans = GetOriginalSpans(diffResult, cancellationToken);
            var changedSpans = GetChangedSpans(diffResult, cancellationToken);
            var description = default(string);
            var allSpans = default(NormalizedSpanCollection);

            if (newDocument.SupportsSyntaxTree)
            {
                var newRoot = newDocument.GetSyntaxRootSynchronously(cancellationToken);
                var conflictNodes = newRoot.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind);
                var conflictSpans = conflictNodes.Select(n => n.Span.ToSpan()).ToList();
                var conflictDescriptions = conflictNodes.SelectMany(n => n.GetAnnotations(ConflictAnnotation.Kind))
                                                        .Select(a => ConflictAnnotation.GetDescription(a))
                                                        .Distinct();

                var warningNodes = newRoot.GetAnnotatedNodesAndTokens(WarningAnnotation.Kind);
                var warningSpans = warningNodes.Select(n => n.Span.ToSpan()).ToList();
                var warningDescriptions = warningNodes.SelectMany(n => n.GetAnnotations(WarningAnnotation.Kind))
                                                        .Select(a => WarningAnnotation.GetDescription(a))
                                                        .Distinct();

                var suppressDiagnosticsNodes = newRoot.GetAnnotatedNodesAndTokens(SuppressDiagnosticsAnnotation.Kind);
                var suppressDiagnosticsSpans = suppressDiagnosticsNodes.Select(n => n.Span.ToSpan()).ToList();
                AttachAnnotationsToBuffer(newBuffer, conflictSpans, warningSpans, suppressDiagnosticsSpans);

                description = conflictSpans.Count == 0 && warningSpans.Count == 0
                    ? null
                    : string.Join(Environment.NewLine, conflictDescriptions.Concat(warningDescriptions));
                allSpans = new NormalizedSpanCollection(conflictSpans.Concat(warningSpans).Concat(changedSpans));
            }
            else
            {
                allSpans = new NormalizedSpanCollection(changedSpans);
            }

            var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken);
            var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, allSpans, cancellationToken);
            if (!originalLineSpans.Any())
            {
                // This means that we have no differences (likely because of conflicts).
                // In such cases, use the same spans for the left (old) buffer as the right (new) buffer.
                originalLineSpans = changedLineSpans;
            }

            // Create PreviewWorkspaces around the buffers to be displayed on the left and right
            // so that all IDE services (colorizer, squiggles etc.) light up in these buffers.
            var leftDocument = oldDocument.Project
                .RemoveDocument(oldDocument.Id)
                .AddDocument(oldDocument.Name, oldBuffer.AsTextContainer().CurrentText, oldDocument.Folders, oldDocument.FilePath);
            var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution);
            leftWorkspace.OpenDocument(leftDocument.Id);

            var rightWorkspace = new PreviewWorkspace(
                newDocument.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution);
            rightWorkspace.OpenDocument(newDocument.Id);

            return CreateChangedDocumentViewAsync(
                oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans,
                leftWorkspace, rightWorkspace, zoomLevel, cancellationToken);
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:82,代码来源:PreviewFactoryService.cs

示例12: GetSolutionWithFormattedInterfaceDocument

        private static Solution GetSolutionWithFormattedInterfaceDocument(Document unformattedInterfaceDocument, CancellationToken cancellationToken)
        {
            Solution solutionWithInterfaceDocument;
            var formattedRoot = Formatter.Format(unformattedInterfaceDocument.GetSyntaxRootSynchronously(cancellationToken),
                unformattedInterfaceDocument.Project.Solution.Workspace, cancellationToken: cancellationToken);
            var rootToSimplify = formattedRoot.WithAdditionalAnnotations(Simplifier.Annotation);
            var finalInterfaceDocument = Simplifier.ReduceAsync(unformattedInterfaceDocument.WithSyntaxRoot(rootToSimplify), cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);

            solutionWithInterfaceDocument = finalInterfaceDocument.Project.Solution;
            return solutionWithInterfaceDocument;
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:11,代码来源:AbstractExtractInterfaceService.cs


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