RoslynVisualStudioWorkspace.cs 8.0 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
        private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenterOpt;
32 33

        [ImportingConstructor]
34
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
35
        public RoslynVisualStudioWorkspace(
36
            ExportProvider exportProvider,
37
            [Import(AllowDefault = true)] Lazy<IStreamingFindUsagesPresenter> streamingPresenterOpt,
38
            [ImportMany] IEnumerable<IDocumentOptionsProviderFactory> documentOptionsProviderFactories,
39 40
            [Import(typeof(SVsServiceProvider))] IAsyncServiceProvider asyncServiceProvider)
            : base(exportProvider, asyncServiceProvider)
41
        {
42
            _streamingPresenterOpt = streamingPresenterOpt;
43 44 45

            foreach (var providerFactory in documentOptionsProviderFactories)
            {
46 47 48 49 50 51
                var optionsProvider = providerFactory.TryCreate(this);

                if (optionsProvider != null)
                {
                    Services.GetRequiredService<IOptionService>().RegisterDocumentOptionsProvider(optionsProvider);
                }
52
            }
53 54 55 56 57
        }

        internal override IInvisibleEditor OpenInvisibleEditor(DocumentId documentId)
        {
            var globalUndoService = this.Services.GetService<IGlobalUndoService>();
58
            var needsUndoDisabled = false;
59 60

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

76
            var document = this.CurrentSolution.GetTextDocument(documentId);
77 78 79 80

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

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

108 109
        public override bool TryGoToDefinition(
            ISymbol symbol, Project project, CancellationToken cancellationToken)
110
        {
111
            if (_streamingPresenterOpt == null)
112 113 114 115
            {
                return false;
            }

D
dotnet-bot 已提交
116
            if (!TryResolveSymbol(symbol, project, cancellationToken,
C
CyrusNajmabadi 已提交
117
                    out var searchSymbol, out var searchProject))
118 119 120 121 122
            {
                return false;
            }

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

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

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

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

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