Exemplo n.º 1
0
 private static BraceMatchingResult?MatchBraces(SyntaxTreeBase syntaxTree, SourceLocation position, SyntaxKind leftKind, SyntaxKind rightKind)
 {
     return(((SyntaxNode)syntaxTree.Root).FindStartTokens(position)
            .Select(t => MatchBraces(t, position, leftKind, rightKind))
            .Where(r => r != null)
            .FirstOrDefault());
 }
        public static async Task <ISyntaxToken> GetTouchingTokenAsync(
            this SyntaxTreeBase syntaxTree,
            SourceLocation position,
            Predicate <ISyntaxToken> predicate,
            CancellationToken cancellationToken,
            bool findInsideTrivia = false)
        {
            Contract.ThrowIfNull(syntaxTree);

            if (position > syntaxTree.Root.FullSourceRange.End)
            {
                return(default(ISyntaxToken));
            }

            var root  = syntaxTree.Root;
            var token = root.FindToken(position, findInsideTrivia);

            if ((token.SourceRange.Contains(position) || token.SourceRange.End == position) && predicate(token))
            {
                return(token);
            }

            token = token.GetPreviousToken();

            if (token != default(ISyntaxToken) && token.SourceRange.End == position && predicate(token))
            {
                return(token);
            }

            // SyntaxKind = None
            return(default(ISyntaxToken));
        }
Exemplo n.º 3
0
 public BraceMatchingResult?FindBraces(SyntaxTreeBase syntaxTree, SourceLocation position, CancellationToken cancellationToken)
 {
     return(_matchingKinds
            .Select(k => MatchBraces(syntaxTree, position, k.Item1, k.Item2))
            .Where(r => r != null)
            .FirstOrDefault());
 }
Exemplo n.º 4
0
        public string Format(SyntaxTreeBase tree, TextSpan span, OptionSet options, CancellationToken cancellationToken)
        {
            var text  = tree.Text;
            var edits = Formatter.GetEdits((SyntaxTree)tree, (SyntaxNode)tree.Root, span, _optionsService.GetFormattingOptions(options));

            return(Formatter.ApplyEdits(text.ToString(), edits));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Computes a span for a given field symbol, expanding to the outer
        /// </summary>
        private static TextSpan GetVariableDeclarationSpan(SyntaxTreeBase tree, SyntaxNode node, SourceFileSpan nodeFileSpan)
        {
            int spanStart = nodeFileSpan.Span.Start;
            int spanEnd   = nodeFileSpan.Span.End;

            var fieldDeclaration = node.GetAncestor <VariableDeclarationStatementSyntax>();

            if (fieldDeclaration != null)
            {
                var variables = fieldDeclaration.Declaration.Variables;

                var fieldDeclarationFileSpan = tree.GetSourceFileSpan(fieldDeclaration.SourceRange);
                if (fieldDeclarationFileSpan.IsInRootFile)
                {
                    if (variables.FirstOrDefault() == node)
                    {
                        spanStart = fieldDeclarationFileSpan.Span.Start;
                    }

                    if (variables.LastOrDefault() == node)
                    {
                        spanEnd = fieldDeclarationFileSpan.Span.End;
                    }
                }
            }

            return(TextSpan.FromBounds(spanStart, spanEnd));
        }
Exemplo n.º 6
0
 internal static DocumentId GetDocumentIdForTree(SyntaxTreeBase tree)
 {
     using (s_syntaxTreeToIdMapLock.DisposableRead())
     {
         s_syntaxTreeToIdMap.TryGetValue(tree, out var id);
         return(id);
     }
 }
 public static void CheckForParseErrors(SyntaxTreeBase syntaxTree)
 {
     foreach (var diagnostic in syntaxTree.GetDiagnostics())
     {
         Debug.WriteLine(diagnostic.ToString());
     }
     Assert.Empty(syntaxTree.GetDiagnostics());
 }
 public static Task <ISyntaxToken> GetTouchingTokenAsync(
     this SyntaxTreeBase syntaxTree,
     SourceLocation position,
     CancellationToken cancellationToken,
     bool findInsideTrivia = false)
 {
     return(GetTouchingTokenAsync(syntaxTree, position, _ => true, cancellationToken, findInsideTrivia));
 }
        /// <summary>
        /// Gets the document in this solution with the specified syntax tree.
        /// </summary>
        public LogicalDocument GetLogicalDocument(SyntaxTreeBase syntaxTree)
        {
            if (syntaxTree != null)
            {
                // is this tree known to be associated with a document?
                return(LogicalDocument.GetDocumentIdForTree(syntaxTree));
            }

            return(null);
        }
Exemplo n.º 10
0
        public Task <IFormattingResult> FormatAsync(SyntaxTreeBase tree, SyntaxNodeBase node, IEnumerable <TextSpan> spans, OptionSet options, CancellationToken cancellationToken)
        {
            var edits = new List <TextChange>();

            foreach (var span in spans)
            {
                edits.AddRange(Formatter.GetEdits((SyntaxTree)tree, (SyntaxNode)node, span, _optionsService.GetFormattingOptions(options)));
            }

            return(Task.FromResult((IFormattingResult) new FormattingResult(edits)));
        }
Exemplo n.º 11
0
 private static void BindSyntaxTreeToId(SyntaxTreeBase tree, DocumentId id)
 {
     using (s_syntaxTreeToIdMapLock.DisposableWrite())
     {
         if (s_syntaxTreeToIdMap.TryGetValue(tree, out var existingId))
         {
             Contract.ThrowIfFalse(existingId == id);
         }
         else
         {
             s_syntaxTreeToIdMap.Add(tree, id);
         }
     }
 }
Exemplo n.º 12
0
 private void Clear()
 {
     if (_typingTimer != null)
     {
         _typingTimer.Stop();
         _typingTimer.Tick -= HandleTypingTimerTimeout;
         _typingTimer       = null;
     }
     if (_activeWpfTextView != null)
     {
         _activeWpfTextView.Selection.SelectionChanged -= HandleSelectionChanged;
         _activeWpfTextView.TextBuffer.Changed         -= HandleTextBufferChanged;
         _activeWpfTextView.LostAggregateFocus         -= HandleTextViewLostFocus;
         _activeWpfTextView = null;
     }
     _activeSyntaxTree = null;
     _activeDocument   = null;
     TreeView.Items.Clear();
 }
Exemplo n.º 13
0
        private IList <NavigationBarItem> GetMembersInTypes(
            SyntaxTreeBase tree,
            IEnumerable <INamespaceOrTypeSymbol> types,
            CancellationToken cancellationToken)
        {
            //using (Logger.LogBlock(FunctionId.NavigationBar_ItemService_GetMembersInTypes_CSharp, cancellationToken))
            {
                var items = new List <NavigationBarItem>();

                foreach (var type in types)
                {
                    var memberItems = new List <NavigationBarItem>();
                    foreach (var member in type.GetMembers())
                    {
                        if (member.Kind == SymbolKind.Struct || member.Kind == SymbolKind.Interface)
                        {
                            continue;
                        }

                        memberItems.AddRange(CreateItems(
                                                 member,
                                                 null,
                                                 tree,
                                                 cancellationToken));
                    }

                    memberItems.Sort((x, y) =>
                    {
                        var textComparison = x.Text.CompareTo(y.Text);
                        return(textComparison != 0 ? textComparison : x.Grayed.CompareTo(y.Grayed));
                    });

                    var typeItems = CreateItems(type, memberItems, tree, cancellationToken);

                    items.AddRange(typeItems);
                }

                items.Sort((x1, x2) => x1.Text.CompareTo(x2.Text));
                return(items);
            }
        }
        private async Task <QuickInfoItem> GetQuickInfoItemAsync(
            Document document,
            SyntaxTreeBase syntaxTree,
            ISyntaxToken token,
            SourceLocation sourceLocation,
            CancellationToken cancellationToken)
        {
            if (token != default(ISyntaxToken) &&
                token.SourceRange.Contains(sourceLocation))
            {
                var deferredContent = await BuildContentAsync(document, token, cancellationToken).ConfigureAwait(false);

                if (deferredContent != null)
                {
                    var rootSpan = syntaxTree.GetSourceFileSpan(token.SourceRange).Span;
                    return(new QuickInfoItem(rootSpan, deferredContent));
                }
            }

            return(null);
        }
        private static IEnumerable <INavigateToSearchResult> ConvertResult(
            ISymbol declaredSymbol, Document document, SyntaxTreeBase syntaxTree,
            NavigateToMatchKind matchKind)
        {
            var isCaseSensitive = false;
            var kind            = GetItemKind(declaredSymbol.Kind);

            foreach (var location in declaredSymbol.Locations)
            {
                var sourceFileSpan = syntaxTree.GetSourceFileSpan(location);

                if (sourceFileSpan.IsInRootFile)
                {
                    var navigableItem = NavigableItemFactory.GetItemFromDeclaredSymbol(
                        declaredSymbol, document, sourceFileSpan);

                    yield return(new SearchResult(
                                     document, declaredSymbol, kind, matchKind,
                                     isCaseSensitive, navigableItem));
                }
            }
        }
        /// <summary>
        /// Gets the document in this solution with the specified syntax tree.
        /// </summary>
        public Document GetDocument(SyntaxTreeBase syntaxTree)
        {
            if (syntaxTree != null)
            {
                // is this tree known to be associated with a document?
                var docId = Document.GetDocumentIdForTree(syntaxTree);
                if (docId != null)
                {
                    // does this solution even have the document?
                    var document = this.GetDocument(docId);
                    if (document != null)
                    {
                        // does this document really have the syntax tree?
                        if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree)
                        {
                            return(document);
                        }
                    }
                }
            }

            return(null);
        }
Exemplo n.º 17
0
        private async void RefreshSyntaxVisualizer()
        {
            if (!IsVisible || _activeWpfTextView == null)
            {
                return;
            }

            var textBuffer = _activeWpfTextView.TextBuffer;

            var currentSnapshot = textBuffer.CurrentSnapshot;
            var contentType     = currentSnapshot.ContentType;

            if (!contentType.IsOfType(ContentTypeNames.ShaderToolsContentType))
            {
                return;
            }

            var document = _activeDocument = currentSnapshot.GetOpenDocumentInCurrentContextWithChanges();

            if (document == null)
            {
                return;
            }

            try
            {
                _activeSyntaxTree = await System.Threading.Tasks.Task.Run(() => document.GetSyntaxTreeAsync(CancellationToken.None));
            }
            catch (Exception ex)
            {
                //Logger.Log("Failed to get syntax tree for syntax visualizer: " + ex);
                return;
            }

            DisplaySyntaxTree();
            NavigateFromSource();
        }
Exemplo n.º 18
0
 /// <summary>
 /// Get the current syntax tree for the document if the text is already loaded and the tree is already parsed.
 /// In almost all cases, you should call <see cref="GetSyntaxTreeAsync"/> to fetch the tree, which will parse the tree
 /// if it's not already parsed.
 /// </summary>
 public bool TryGetSyntaxTree(out SyntaxTreeBase syntaxTree)
 {
     return(_lazySyntaxTree.TryGetValue(out syntaxTree));
 }
Exemplo n.º 19
0
 //public abstract void AddLexicalClassifications(SourceText text, TextSpan textSpan, List<ClassifiedSpan> result, CancellationToken cancellationToken);
 public abstract void AddSyntacticClassifications(SyntaxTreeBase syntaxTree, TextSpan textSpan, List <ClassifiedSpan> result, CancellationToken cancellationToken);
Exemplo n.º 20
0
        private static IList <NavigationBarItem> CreateItems(ISymbol symbol, IList <NavigationBarItem> childItems, SyntaxTreeBase tree, CancellationToken cancellationToken)
        {
            var result = new List <NavigationBarItem>();

            if (symbol.Locations.Length == 0)
            {
                return(result);
            }

            var locationsLength = symbol.Kind == SymbolKind.Function
                ? symbol.Locations.Length
                : 1;

            for (var i = 0; i < locationsLength; i++)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(SpecializedCollections.EmptyList <NavigationBarItem>());
                }

                // TODO: This is a hack, it assumes too much about ISymbol's properties.
                var nameSourceRange = symbol.Locations[i];
                var node            = (SyntaxNode)symbol.DeclaringSyntaxNodes[i];

                var nameFileSpan = tree.GetSourceFileSpan(nameSourceRange);
                if (!nameFileSpan.IsInRootFile)
                {
                    continue;
                }

                var nodeFileSpan = node.GetTextSpanSafe();
                if (nodeFileSpan == null || !nodeFileSpan.Value.IsInRootFile)
                {
                    continue;
                }

                var nodeSpan = nodeFileSpan.Value.Span;
                if (symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.Variable)
                {
                    nodeSpan = GetVariableDeclarationSpan(tree, node, nodeFileSpan.Value);
                }

                result.Add(new NavigationBarSymbolItem(
                               symbol.ToDisplayString(SymbolDisplayFormat.NavigationBar),
                               symbol.GetGlyph(),
                               SpecializedCollections.SingletonList(nodeSpan),
                               nameFileSpan.Span,
                               childItems));
            }

            return(result);
        }
Exemplo n.º 21
0
 public CompilationBase CreateCompilation(SyntaxTreeBase syntaxTree)
 {
     return(new Compilation.Compilation((SyntaxTree)syntaxTree));
 }
Exemplo n.º 22
0
 internal static IList <TextChange> GetFormattedTextChanges(SyntaxTreeBase tree, SyntaxNodeBase node, IEnumerable <TextSpan> spans, Workspace workspace, OptionSet options, CancellationToken cancellationToken)
 {
     return(GetFormattedTextChangesAsync(tree, node, spans, workspace, options, cancellationToken).WaitAndGetResult(cancellationToken));
 }
Exemplo n.º 23
0
        internal static async Task <IList <TextChange> > GetFormattedTextChangesAsync(SyntaxTreeBase tree, SyntaxNodeBase node, IEnumerable <TextSpan> spans, Workspace workspace, OptionSet options, CancellationToken cancellationToken)
        {
            if (workspace == null)
            {
                throw new ArgumentNullException(nameof(workspace));
            }

            if (node == null)
            {
                throw new ArgumentNullException(nameof(node));
            }

            if (spans == null)
            {
                throw new ArgumentNullException(nameof(spans));
            }

            var languageFormatter = workspace.Services.GetLanguageServices(node.Language).GetService <ISyntaxFormattingService>();

            if (languageFormatter != null)
            {
                options = options ?? workspace.Options;
                return((await languageFormatter.FormatAsync(tree, node, spans, options, cancellationToken).ConfigureAwait(false)).GetTextChanges(cancellationToken));
            }
            else
            {
                return(SpecializedCollections.EmptyList <TextChange>());
            }
        }
Exemplo n.º 24
0
        private static MappedDiagnostic MapDiagnostic(SyntaxTreeBase syntaxTree, Diagnostic diagnostic, DiagnosticSource source, LogicalDocument logicalDocument)
        {
            var fileSpan = syntaxTree.GetSourceFileSpan(diagnostic.SourceRange);

            return(new MappedDiagnostic(diagnostic, source, fileSpan, logicalDocument));
        }
        public override void AddSyntacticClassifications(SyntaxTreeBase syntaxTree, TextSpan textSpan, List <ClassifiedSpan> result, CancellationToken cancellationToken)
        {
            var worker = new SyntaxTaggerWorker(result, cancellationToken);

            worker.ClassifySyntax((SyntaxTree)syntaxTree);
        }