RoslynVisualStudioWorkspace.cs 8.1 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.Host.Mef;
14
using Microsoft.CodeAnalysis.Options;
C
CyrusNajmabadi 已提交
15
using Microsoft.CodeAnalysis.Shared.Extensions;
16
using Microsoft.VisualStudio.Composition;
17 18 19 20
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;
21
using Microsoft.VisualStudio.Shell;
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 32 33 34
        /// <remarks>
        /// Must be lazily constructed since the <see cref="IStreamingFindUsagesPresenter"/> implementation imports a
        /// backreference to <see cref="VisualStudioWorkspace"/>.
        /// </remarks>
35
        private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter;
36 37

        [ImportingConstructor]
38
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
39
        public RoslynVisualStudioWorkspace(
40
            ExportProvider exportProvider,
41
            Lazy<IStreamingFindUsagesPresenter> streamingPresenter,
42
            [ImportMany] IEnumerable<IDocumentOptionsProviderFactory> documentOptionsProviderFactories,
43 44
            [Import(typeof(SVsServiceProvider))] IAsyncServiceProvider asyncServiceProvider)
            : base(exportProvider, asyncServiceProvider)
45
        {
46
            _streamingPresenter = streamingPresenter;
47 48 49

            foreach (var providerFactory in documentOptionsProviderFactories)
            {
50 51 52 53 54 55
                var optionsProvider = providerFactory.TryCreate(this);

                if (optionsProvider != null)
                {
                    Services.GetRequiredService<IOptionService>().RegisterDocumentOptionsProvider(optionsProvider);
                }
56
            }
57 58 59 60 61
        }

        internal override IInvisibleEditor OpenInvisibleEditor(DocumentId documentId)
        {
            var globalUndoService = this.Services.GetService<IGlobalUndoService>();
62
            var needsUndoDisabled = false;
63 64

            // Do not save the file if is open and there is not a global undo transaction.
65
            var needsSave = globalUndoService.IsGlobalTransactionOpen(this) || !this.IsDocumentOpen(documentId);
66 67
            if (needsSave)
            {
68
                if (this.CurrentSolution.ContainsDocument(documentId))
69 70
                {
                    // Disable undo on generated documents
71
                    needsUndoDisabled = this.CurrentSolution.GetDocument(documentId).IsGeneratedCode(CancellationToken.None);
72 73 74 75 76 77 78
                }
                else
                {
                    // Enable undo on "additional documents" or if no document can be found.
                    needsUndoDisabled = false;
                }
            }
79

80
            var document = this.CurrentSolution.GetTextDocument(documentId);
81 82 83 84

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

85 86 87 88 89 90 91 92 93 94 95 96
        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);
97
            var symbolId = SymbolKey.Create(symbol, cancellationToken);
98 99 100 101 102 103 104 105 106 107 108 109 110 111
            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;
        }

112 113
        public override bool TryGoToDefinition(
            ISymbol symbol, Project project, CancellationToken cancellationToken)
114
        {
D
dotnet-bot 已提交
115
            if (!TryResolveSymbol(symbol, project, cancellationToken,
C
CyrusNajmabadi 已提交
116
                    out var searchSymbol, out var searchProject))
117 118 119 120 121
            {
                return false;
            }

            return GoToDefinitionHelpers.TryGoToDefinition(
D
dotnet-bot 已提交
122
                searchSymbol, searchProject,
123
                _streamingPresenter.Value, cancellationToken);
124 125 126 127
        }

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

133
        public override void DisplayReferencedSymbols(Solution solution, IEnumerable<ReferencedSymbol> referencedSymbols)
134
        {
135 136
            // Legacy API.  Previously used by ObjectBrowser to support 'FindRefs' off of an
            // object browser item.  Now ObjectBrowser goes through the streaming-FindRefs system.
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 189 190 191 192 193
        }

        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)
                {
194
                    var codeElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(syntaxNode);
195 196 197 198 199 200 201 202 203 204
                    if (codeElement != null)
                    {
                        return codeElement;
                    }
                }
            }

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