RoslynVisualStudioWorkspace.cs 7.8 KB
Newer Older
S
Sam Harwell 已提交
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
2 3 4 5 6 7 8

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
9
using Microsoft.CodeAnalysis.Editor.GoToDefinition;
10 11 12
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Undo;
using Microsoft.CodeAnalysis.FindSymbols;
13
using Microsoft.CodeAnalysis.Options;
C
CyrusNajmabadi 已提交
14
using Microsoft.CodeAnalysis.Shared.Extensions;
15
using Microsoft.VisualStudio.Composition;
16 17 18 19
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
20 21
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
22
using Roslyn.Utilities;
23
using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider;
24 25 26 27 28 29 30

namespace Microsoft.VisualStudio.LanguageServices
{
    [Export(typeof(VisualStudioWorkspace))]
    [Export(typeof(VisualStudioWorkspaceImpl))]
    internal class RoslynVisualStudioWorkspace : VisualStudioWorkspaceImpl
    {
31
        private readonly IEnumerable<Lazy<IStreamingFindUsagesPresenter>> _streamingPresenters;
32 33 34

        [ImportingConstructor]
        private RoslynVisualStudioWorkspace(
35
            ExportProvider exportProvider,
36
            [ImportMany] IEnumerable<Lazy<IStreamingFindUsagesPresenter>> streamingPresenters,
37
            [ImportMany] IEnumerable<IDocumentOptionsProviderFactory> documentOptionsProviderFactories,
38 39
            [Import(typeof(SVsServiceProvider))] IAsyncServiceProvider asyncServiceProvider)
            : base(exportProvider, asyncServiceProvider)
40
        {
41
            _streamingPresenters = streamingPresenters;
42 43 44 45 46

            foreach (var providerFactory in documentOptionsProviderFactories)
            {
                Services.GetRequiredService<IOptionService>().RegisterDocumentOptionsProvider(providerFactory.Create(this));
            }
47 48 49 50 51
        }

        internal override IInvisibleEditor OpenInvisibleEditor(DocumentId documentId)
        {
            var globalUndoService = this.Services.GetService<IGlobalUndoService>();
52
            var needsUndoDisabled = false;
53 54

            // Do not save the file if is open and there is not a global undo transaction.
55
            var needsSave = globalUndoService.IsGlobalTransactionOpen(this) || !this.IsDocumentOpen(documentId);
56 57
            if (needsSave)
            {
58
                if (this.CurrentSolution.ContainsDocument(documentId))
59 60
                {
                    // Disable undo on generated documents
61
                    needsUndoDisabled = this.CurrentSolution.GetDocument(documentId).IsGeneratedCode(CancellationToken.None);
62 63 64 65 66 67 68
                }
                else
                {
                    // Enable undo on "additional documents" or if no document can be found.
                    needsUndoDisabled = false;
                }
            }
69

70 71 72 73 74
            var document = this.CurrentSolution.GetDocument(documentId) ?? this.CurrentSolution.GetAdditionalDocument(documentId);

            return new InvisibleEditor(ServiceProvider.GlobalProvider, document.FilePath, GetHierarchy(documentId.ProjectId), needsSave, needsUndoDisabled);
        }

75 76 77 78 79 80 81 82 83 84 85 86
        private static bool TryResolveSymbol(ISymbol symbol, Project project, CancellationToken cancellationToken, out ISymbol resolvedSymbol, out Project resolvedProject)
        {
            resolvedSymbol = null;
            resolvedProject = null;

            var currentProject = project.Solution.Workspace.CurrentSolution.GetProject(project.Id);
            if (currentProject == null)
            {
                return false;
            }

            var originalCompilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
87
            var symbolId = SymbolKey.Create(symbol, cancellationToken);
88 89 90 91 92 93 94 95 96 97 98 99 100 101
            var currentCompilation = currentProject.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var symbolInfo = symbolId.Resolve(currentCompilation, cancellationToken: cancellationToken);

            if (symbolInfo.Symbol == null)
            {
                return false;
            }

            resolvedSymbol = symbolInfo.Symbol;
            resolvedProject = currentProject;

            return true;
        }

102 103
        public override bool TryGoToDefinition(
            ISymbol symbol, Project project, CancellationToken cancellationToken)
104
        {
105
            if (!_streamingPresenters.Any())
106 107 108 109
            {
                return false;
            }

D
dotnet-bot 已提交
110
            if (!TryResolveSymbol(symbol, project, cancellationToken,
C
CyrusNajmabadi 已提交
111
                    out var searchSymbol, out var searchProject))
112 113 114 115 116
            {
                return false;
            }

            return GoToDefinitionHelpers.TryGoToDefinition(
D
dotnet-bot 已提交
117
                searchSymbol, searchProject,
118
                _streamingPresenters, cancellationToken);
119 120 121 122
        }

        public override bool TryFindAllReferences(ISymbol symbol, Project project, CancellationToken cancellationToken)
        {
123 124
            // Legacy API.  Previously used by ObjectBrowser to support 'FindRefs' off of an
            // object browser item.  Now ObjectBrowser goes through the streaming-FindRefs system.
125
            return false;
126 127
        }

128
        public override void DisplayReferencedSymbols(Solution solution, IEnumerable<ReferencedSymbol> referencedSymbols)
129
        {
130 131
            // Legacy API.  Previously used by ObjectBrowser to support 'FindRefs' off of an
            // object browser item.  Now ObjectBrowser goes through the streaming-FindRefs system.
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
        }

        internal override object GetBrowseObject(SymbolListItem symbolListItem)
        {
            var compilation = symbolListItem.GetCompilation(this);
            if (compilation == null)
            {
                return null;
            }

            var symbol = symbolListItem.ResolveSymbol(compilation);
            var sourceLocation = symbol.Locations.Where(l => l.IsInSource).FirstOrDefault();

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

            var projectId = symbolListItem.ProjectId;
            if (projectId == null)
            {
                return null;
            }

            var project = this.CurrentSolution.GetProject(projectId);
            if (project == null)
            {
                return null;
            }

            var codeModelService = project.LanguageServices.GetService<ICodeModelService>();
            if (codeModelService == null)
            {
                return null;
            }

            var tree = sourceLocation.SourceTree;
            var document = project.GetDocument(tree);

            var vsFileCodeModel = this.GetFileCodeModel(document.Id);

            var fileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(vsFileCodeModel);
            if (fileCodeModel != null)
            {
                var syntaxNode = tree.GetRoot().FindNode(sourceLocation.SourceSpan);
                while (syntaxNode != null)
                {
                    if (!codeModelService.TryGetNodeKey(syntaxNode).IsEmpty)
                    {
                        break;
                    }

                    syntaxNode = syntaxNode.Parent;
                }

                if (syntaxNode != null)
                {
189
                    var codeElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(syntaxNode);
190 191 192 193 194 195 196 197 198 199
                    if (codeElement != null)
                    {
                        return codeElement;
                    }
                }
            }

            return null;
        }
    }
S
Sam Harwell 已提交
200
}