|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using System.Collections.Immutable; |
| 6 | +using System.Security; |
| 7 | +using Microsoft.CodeAnalysis.Features.Workspaces; |
| 8 | +using Microsoft.CodeAnalysis.Host; |
| 9 | +using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.ProjectTelemetry; |
| 10 | +using Microsoft.CodeAnalysis.MetadataAsSource; |
| 11 | +using Microsoft.CodeAnalysis.MSBuild; |
| 12 | +using Microsoft.CodeAnalysis.Options; |
| 13 | +using Microsoft.CodeAnalysis.ProjectSystem; |
| 14 | +using Microsoft.CodeAnalysis.Shared.Extensions; |
| 15 | +using Microsoft.CodeAnalysis.Shared.TestHooks; |
| 16 | +using Microsoft.CodeAnalysis.Text; |
| 17 | +using Microsoft.CodeAnalysis.Workspaces.ProjectSystem; |
| 18 | +using Microsoft.CommonLanguageServerProtocol.Framework; |
| 19 | +using Microsoft.Extensions.Logging; |
| 20 | +using Microsoft.VisualStudio.Composition; |
| 21 | +using Roslyn.Utilities; |
| 22 | +using static Microsoft.CodeAnalysis.MSBuild.BuildHostProcessManager; |
| 23 | + |
| 24 | +namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; |
| 25 | + |
| 26 | +internal sealed class FileBasedProgramsProjectSystem : LanguageServerProjectLoader, ILspMiscellaneousFilesWorkspaceProvider |
| 27 | +{ |
| 28 | + private readonly ILspServices _lspServices; |
| 29 | + private readonly ILogger<FileBasedProgramsProjectSystem> _logger; |
| 30 | + private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; |
| 31 | + |
| 32 | + public FileBasedProgramsProjectSystem( |
| 33 | + ILspServices lspServices, |
| 34 | + IMetadataAsSourceFileService metadataAsSourceFileService, |
| 35 | + LanguageServerWorkspaceFactory workspaceFactory, |
| 36 | + IFileChangeWatcher fileChangeWatcher, |
| 37 | + IGlobalOptionService globalOptionService, |
| 38 | + ILoggerFactory loggerFactory, |
| 39 | + IAsynchronousOperationListenerProvider listenerProvider, |
| 40 | + ProjectLoadTelemetryReporter projectLoadTelemetry, |
| 41 | + ServerConfigurationFactory serverConfigurationFactory, |
| 42 | + BinlogNamer binlogNamer) |
| 43 | + : base( |
| 44 | + workspaceFactory.FileBasedProgramsProjectFactory, |
| 45 | + workspaceFactory.TargetFrameworkManager, |
| 46 | + workspaceFactory.ProjectSystemHostInfo, |
| 47 | + fileChangeWatcher, |
| 48 | + globalOptionService, |
| 49 | + loggerFactory, |
| 50 | + listenerProvider, |
| 51 | + projectLoadTelemetry, |
| 52 | + serverConfigurationFactory, |
| 53 | + binlogNamer) |
| 54 | + { |
| 55 | + _lspServices = lspServices; |
| 56 | + _logger = loggerFactory.CreateLogger<FileBasedProgramsProjectSystem>(); |
| 57 | + _metadataAsSourceFileService = metadataAsSourceFileService; |
| 58 | + } |
| 59 | + |
| 60 | + public Workspace Workspace => ProjectFactory.Workspace; |
| 61 | + |
| 62 | + public async Task<TextDocument?> AddMiscellaneousDocumentAsync(Uri uri, SourceText documentText, string languageId, ILspLogger logger) |
| 63 | + { |
| 64 | + var documentPath = ProtocolConversions.GetDocumentFilePathFromUri(uri); |
| 65 | + var container = documentText.Container; |
| 66 | + if (_metadataAsSourceFileService.TryAddDocumentToWorkspace(documentPath, container, out var documentId)) |
| 67 | + { |
| 68 | + var metadataWorkspace = _metadataAsSourceFileService.TryGetWorkspace(); |
| 69 | + Contract.ThrowIfNull(metadataWorkspace); |
| 70 | + var metadataDoc = metadataWorkspace.CurrentSolution.GetRequiredDocument(documentId); |
| 71 | + return metadataDoc; |
| 72 | + } |
| 73 | + |
| 74 | + var languageInfoProvider = _lspServices.GetRequiredService<ILanguageInfoProvider>(); |
| 75 | + if (!languageInfoProvider.TryGetLanguageInformation(uri, languageId, out var languageInformation)) |
| 76 | + { |
| 77 | + // Only log here since throwing here could take down the LSP server. |
| 78 | + logger.LogError($"Could not find language information for {uri} with absolute path {documentPath}"); |
| 79 | + return null; |
| 80 | + } |
| 81 | + |
| 82 | + if (!uri.IsFile || !GlobalOptionService.GetOption(LanguageServerProjectSystemOptionsStorage.EnableFileBasedPrograms)) |
| 83 | + { |
| 84 | + // For now, we cannot provide intellisense etc on files which are not on disk or are not C#. |
| 85 | + var sourceTextLoader = new SourceTextLoader(documentText, documentPath); |
| 86 | + var projectInfo = MiscellaneousFileUtilities.CreateMiscellaneousProjectInfoForDocument( |
| 87 | + Workspace, documentPath, sourceTextLoader, languageInformation, documentText.ChecksumAlgorithm, Workspace.CurrentSolution.Services, []); |
| 88 | + await ProjectFactory.ApplyChangeToWorkspaceAsync(ws => ws.OnProjectAdded(projectInfo), cancellationToken: default); |
| 89 | + |
| 90 | + var newSolution = Workspace.CurrentSolution; |
| 91 | + if (languageInformation.LanguageName == "Razor") |
| 92 | + { |
| 93 | + var docId = projectInfo.AdditionalDocuments.Single().Id; |
| 94 | + return newSolution.GetRequiredAdditionalDocument(docId); |
| 95 | + } |
| 96 | + |
| 97 | + var id = projectInfo.Documents.Single().Id; |
| 98 | + return newSolution.GetRequiredDocument(id); |
| 99 | + } |
| 100 | + |
| 101 | + // We have a file on disk. Light up the file-based program experience. |
| 102 | + // For Razor files we need to override the language name to C# as that's what code is generated |
| 103 | + var isRazor = languageInformation.LanguageName == "Razor"; |
| 104 | + var languageName = isRazor ? LanguageNames.CSharp : languageInformation.LanguageName; |
| 105 | + var documentFileInfo = new DocumentFileInfo(documentPath, logicalPath: documentPath, isLinked: false, isGenerated: false, folders: default); |
| 106 | + var projectFileInfo = new ProjectFileInfo() |
| 107 | + { |
| 108 | + Language = languageName, |
| 109 | + FilePath = VirtualProject.GetVirtualProjectPath(documentPath), |
| 110 | + CommandLineArgs = ["/langversion:preview", "/features:FileBasedProgram=true"], |
| 111 | + Documents = isRazor ? [] : [documentFileInfo], |
| 112 | + AdditionalDocuments = isRazor ? [documentFileInfo] : [], |
| 113 | + AnalyzerConfigDocuments = [], |
| 114 | + ProjectReferences = [], |
| 115 | + PackageReferences = [], |
| 116 | + ProjectCapabilities = [], |
| 117 | + ContentFilePaths = [], |
| 118 | + FileGlobs = [] |
| 119 | + }; |
| 120 | + |
| 121 | + var projectSet = AddLoadedProjectSet(documentPath); |
| 122 | + Project workspaceProject; |
| 123 | + using (await projectSet.Semaphore.DisposableWaitAsync()) |
| 124 | + { |
| 125 | + var loadedProject = await this.CreateAndTrackInitialProjectAsync_NoLock(projectSet, documentPath, language: languageName); |
| 126 | + await loadedProject.UpdateWithNewProjectInfoAsync(projectFileInfo, hasAllInformation: false, _logger); |
| 127 | + |
| 128 | + ProjectsToLoadAndReload.AddWork(new ProjectToLoad(documentPath, ProjectGuid: null, ReportTelemetry: true)); |
| 129 | + loadedProject.NeedsReload += (_, _) => ProjectsToLoadAndReload.AddWork(new ProjectToLoad(documentPath, ProjectGuid: null, ReportTelemetry: false)); |
| 130 | + workspaceProject = ProjectFactory.Workspace.CurrentSolution.GetRequiredProject(loadedProject.ProjectId); |
| 131 | + } |
| 132 | + |
| 133 | + var document = isRazor ? workspaceProject.AdditionalDocuments.Single() : workspaceProject.Documents.Single(); |
| 134 | + |
| 135 | + _ = Task.Run(async () => |
| 136 | + { |
| 137 | + await ProjectsToLoadAndReload.WaitUntilCurrentBatchCompletesAsync(); |
| 138 | + await ProjectInitializationHandler.SendProjectInitializationCompleteNotificationAsync(); |
| 139 | + }); |
| 140 | + |
| 141 | + Contract.ThrowIfFalse(document.FilePath == documentPath); |
| 142 | + return document; |
| 143 | + } |
| 144 | + |
| 145 | + public async ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri, bool removeFromMetadataWorkspace) |
| 146 | + { |
| 147 | + var documentPath = uri.ParsedUri is { } parsedUri ? ProtocolConversions.GetDocumentFilePathFromUri(parsedUri) : uri.UriString; |
| 148 | + await TryUnloadProjectSetAsync(documentPath); |
| 149 | + |
| 150 | + // also do an unload in case this was the non-file scenario |
| 151 | + if (removeFromMetadataWorkspace && uri.ParsedUri is not null && _metadataAsSourceFileService.TryRemoveDocumentFromWorkspace(ProtocolConversions.GetDocumentFilePathFromUri(uri.ParsedUri))) |
| 152 | + { |
| 153 | + return; |
| 154 | + } |
| 155 | + |
| 156 | + var matchingDocument = Workspace.CurrentSolution.GetDocumentIds(uri).SingleOrDefault(); |
| 157 | + if (matchingDocument != null) |
| 158 | + { |
| 159 | + var project = Workspace.CurrentSolution.GetRequiredProject(matchingDocument.ProjectId); |
| 160 | + Workspace.OnProjectRemoved(project.Id); |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + protected override async Task<(RemoteProjectFile? projectFile, bool hasAllInformation, BuildHostProcessKind preferred, BuildHostProcessKind actual)> TryLoadProjectAsync( |
| 165 | + BuildHostProcessManager buildHostProcessManager, string documentPath, CancellationToken cancellationToken) |
| 166 | + { |
| 167 | + const BuildHostProcessKind buildHostKind = BuildHostProcessKind.NetCore; |
| 168 | + var buildHost = await buildHostProcessManager.GetBuildHostAsync(buildHostKind, cancellationToken); |
| 169 | + Contract.ThrowIfFalse(Path.GetExtension(documentPath) == ".cs"); |
| 170 | + |
| 171 | + var fakeProjectPath = VirtualProject.GetVirtualProjectPath(documentPath); |
| 172 | + var loader = ProjectFactory.CreateFileTextLoader(documentPath); |
| 173 | + var textAndVersion = await loader.LoadTextAsync(new LoadTextOptions(SourceHashAlgorithms.Default), cancellationToken: default); |
| 174 | + var (contentToLoad, isFileBasedProgram) = VirtualProject.MakeVirtualProjectContent(documentPath, textAndVersion.Text); |
| 175 | + |
| 176 | + var loadedFile = await buildHost.LoadProjectAsync(fakeProjectPath, contentToLoad, languageName: LanguageNames.CSharp, cancellationToken); |
| 177 | + return (loadedFile, hasAllInformation: isFileBasedProgram, preferred: buildHostKind, actual: buildHostKind); |
| 178 | + } |
| 179 | +} |
0 commit comments