From bbf2fb7c5cdc3ce8a5b459464af85e33165eb730 Mon Sep 17 00:00:00 2001 From: David Barbet Date: Wed, 29 Jul 2026 18:47:51 -0700 Subject: [PATCH 1/5] WIP: Share syntax trees across LSP servers Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 5933d2c9-9c2d-4165-9afe-65237e606db3 --- .github/instructions/IDE.instructions.md | 14 + .github/memory/FILE_MAP.md | 2 +- .github/memory/testing/ide.md | 3 + .../Daemon/LanguageServerDaemonTests.cs | 73 ++++++ .../SyntaxTreeCacheServiceTests.cs | 239 ++++++++++++++++++ .../AbstractLanguageServerHostTests.cs | 32 ++- .../LanguageServerTestComposition.cs | 33 ++- .../HostWorkspace/SyntaxTreeCacheService.cs | 201 +++++++++++++++ .../LanguageServer/LspTestWorkspaces.cs | 40 ++- src/Tools/IdeCoreBenchmarks/Program.cs | 8 + .../CSharpSyntaxTreeFactoryService.cs | 22 +- .../CSharpSyntaxTreeFactoryServiceTests.cs | 29 +++ .../AbstractSyntaxTreeFactoryService.cs | 39 ++- .../ISyntaxTreeCacheService.cs | 20 ++ .../VisualBasicSyntaxTreeFactoryService.vb | 26 +- ...isualBasicSyntaxTreeFactoryServiceTests.vb | 29 +++ 16 files changed, 782 insertions(+), 28 deletions(-) create mode 100644 src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs create mode 100644 src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs create mode 100644 src/Workspaces/CSharpTest/CSharpSyntaxTreeFactoryServiceTests.cs create mode 100644 src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/ISyntaxTreeCacheService.cs create mode 100644 src/Workspaces/VisualBasicTest/VisualBasicSyntaxTreeFactoryServiceTests.vb diff --git a/.github/instructions/IDE.instructions.md b/.github/instructions/IDE.instructions.md index f6a1e030f6da..7bd8bdb4ce98 100644 --- a/.github/instructions/IDE.instructions.md +++ b/.github/instructions/IDE.instructions.md @@ -26,6 +26,12 @@ var csharpService = workspace.Services.GetLanguageServices(LanguageNames.CSharp) .GetRequiredService(); ``` +Syntax-tree creation flows through the language-specific `ISyntaxTreeFactoryService`. The C# and VB +implementations are language-service factories so they can consume the optional workspace-scoped +`ISyntaxTreeCacheService`. LanguageServer exports that cache at the Host layer to share immutable +syntax roots process-wide; cache hits still produce distinct `SyntaxTree` wrappers so document text, +paths, and identity remain workspace-specific. + ### MEF Export Patterns ```csharp // Workspace service (language-agnostic) @@ -36,6 +42,14 @@ internal class MyService : IMyService { } [ExportLanguageService(typeof(IMyService), LanguageNames.CSharp), Shared] internal class CSharpMyService : IMyService { } +// Language service requiring a workspace-scoped dependency +[ExportLanguageServiceFactory(typeof(IMyService), LanguageNames.CSharp), Shared] +internal class CSharpMyServiceFactory : ILanguageServiceFactory +{ + public ILanguageService CreateLanguageService(HostLanguageServices languageServices) + => new CSharpMyService(languageServices.WorkspaceServices.GetService()); +} + // Constructor — always include both attributes [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] diff --git a/.github/memory/FILE_MAP.md b/.github/memory/FILE_MAP.md index 413aab748cd6..492ce0f3bd4f 100644 --- a/.github/memory/FILE_MAP.md +++ b/.github/memory/FILE_MAP.md @@ -18,7 +18,7 @@ This file is a **top-level map only**. For per-area directory detail, read the m | `Compilers/` | compiler | C#/VB compilers (`Core`, `CSharp`, `VisualBasic`, `Server`). | | `Dependencies/` | compiler | High-performance pooled collections & threading. | | `ExpressionEvaluator/` | compiler | Debugger expression evaluator. | -| `Tools/` | compiler | Compiler tooling (BuildBoss, format tools). | +| `Tools/` | compiler / ide | Compiler and IDE tooling (BuildBoss, IdeCoreBenchmarks, format tools). | | `Workspaces/` | ide | Solution/Project/Document model, MSBuild loading, Remote (OOP). | | `Features/`, `EditorFeatures/` | ide | IDE feature logic and editor integration. | | `Analyzers/`, `CodeStyle/` | ide | IDE0xxx code-style analyzers & fixes. | diff --git a/.github/memory/testing/ide.md b/.github/memory/testing/ide.md index 7da57bf11ffd..ca2f45d4029f 100644 --- a/.github/memory/testing/ide.md +++ b/.github/memory/testing/ide.md @@ -26,6 +26,9 @@ public class MyTests - Use `[UseExportProvider]` for any test that depends on MEF services (a missing attribute typically surfaces as an unrelated-looking failure). +- LanguageServer daemon and host tests derive from `AbstractLanguageServerHostTests`. + Hosts that opt out of the shared test export-provider cache receive independently + owned providers, which the base class disposes with the host. - Analyzer tests inherit from `AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest_NoEditor` (and the VB equivalents). diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Daemon/LanguageServerDaemonTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Daemon/LanguageServerDaemonTests.cs index 6e1a7edb826d..a7d479504f92 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Daemon/LanguageServerDaemonTests.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Daemon/LanguageServerDaemonTests.cs @@ -157,6 +157,63 @@ static void CreateMetadataLifetimeReferences( } } + [Fact] + public async Task Daemon_SharesGreenSyntaxTreesAcrossServers() + { + const string source = "class SharedSyntaxTree { }"; + + await using var daemon = await CreateDaemonServerAsync(); + await using var second = await daemon.CreateClientAsync(); + + var secondFactory = second.GetRequiredLspService(); + var secondDocument = LoadProjectWithDocument( + secondFactory, + projectName: "Second", + source, + filePath: Path.Combine(Path.GetTempPath(), "second", $"{Guid.NewGuid():N}.cs")); + + SyntaxNode secondRoot; + await using (var first = await daemon.CreateClientAsync()) + { + var firstFactory = first.GetRequiredLspService(); + var firstDocument = LoadProjectWithDocument( + firstFactory, + projectName: "First", + source, + filePath: Path.Combine(Path.GetTempPath(), "first", $"{Guid.NewGuid():N}.cs")); + + var firstTree = await firstDocument.GetSyntaxTreeAsync(CancellationToken.None); + var secondTree = await secondDocument.GetSyntaxTreeAsync(CancellationToken.None); + Assert.NotNull(firstTree); + Assert.NotNull(secondTree); + + var firstRoot = await firstTree.GetRootAsync(CancellationToken.None); + secondRoot = await secondTree.GetRootAsync(CancellationToken.None); + + Assert.NotSame(firstFactory.HostWorkspace, secondFactory.HostWorkspace); + Assert.NotSame(firstTree, secondTree); + Assert.NotSame(firstRoot, secondRoot); + Assert.True(firstRoot.IsIncrementallyIdenticalTo(secondRoot)); + Assert.NotEqual(firstTree.FilePath, secondTree.FilePath); + Assert.NotEqual(firstDocument.Id, secondDocument.Id); + } + + await WaitForConditionAsync(() => daemon.GetStartedServers().Length == 1); + + await using var third = await daemon.CreateClientAsync(); + var thirdDocument = LoadProjectWithDocument( + third.GetRequiredLspService(), + projectName: "Third", + source, + filePath: Path.Combine(Path.GetTempPath(), "third", $"{Guid.NewGuid():N}.cs")); + var thirdTree = await thirdDocument.GetSyntaxTreeAsync(CancellationToken.None); + Assert.NotNull(thirdTree); + var thirdRoot = await thirdTree.GetRootAsync(CancellationToken.None); + + Assert.NotSame(secondRoot, thirdRoot); + Assert.True(secondRoot.IsIncrementallyIdenticalTo(thirdRoot)); + } + // If one client's server faults (e.g. the client process crashes and abruptly drops its connection), the daemon // tears down only that server. The daemon stays alive, the other client's server is untouched and still // functional, and the daemon keeps accepting new clients. @@ -370,4 +427,20 @@ private static DocumentUri LoadProjectWithDocument(LanguageServerWorkspaceFactor return ProtocolConversions.CreateAbsoluteDocumentUri(filePath); } + + private static Document LoadProjectWithDocument( + LanguageServerWorkspaceFactory workspaceFactory, + string projectName, + string source, + string filePath) + { + workspaceFactory.HostWorkspace.SetCurrentSolution( + solution => solution + .AddProject(projectName, projectName, LanguageNames.CSharp) + .AddDocument(Path.GetFileName(filePath), SourceText.From(source), filePath: filePath) + .Project.Solution, + WorkspaceChangeKind.ProjectAdded); + + return workspaceFactory.HostWorkspace.CurrentSolution.Projects.Single().Documents.Single(); + } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs new file mode 100644 index 000000000000..bc8f98223a83 --- /dev/null +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs @@ -0,0 +1,239 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.CompilerServices; +using System.Text; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; +using Microsoft.CodeAnalysis.Text; +using Xunit.Abstractions; + +namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.HostWorkspace; + +public sealed class SyntaxTreeCacheServiceTests(ITestOutputHelper testOutputHelper) + : AbstractLanguageServerHostTests(testOutputHelper) +{ + [Theory] + [InlineData(LanguageNames.CSharp, "class C { }", "first.cs", "second.cs")] + public async Task IdenticalDocumentsInDifferentWorkspacesShareGreenNodes( + string language, string source, string firstPath, string secondPath) + { + var hostServices = GetLanguageServerHostServices(); + using var firstWorkspace = new AdhocWorkspace(hostServices, WorkspaceKind.Host); + using var secondWorkspace = new AdhocWorkspace(hostServices, WorkspaceKind.Host); + + Assert.Same( + firstWorkspace.Services.GetRequiredService(), + secondWorkspace.Services.GetRequiredService()); + + var firstText = SourceText.From(source, Encoding.UTF8, SourceHashAlgorithm.Sha1); + var secondText = SourceText.From(source, Encoding.Unicode, SourceHashAlgorithm.Sha256); + var firstDocument = AddDocument(firstWorkspace, language, firstText, firstPath); + var secondDocument = AddDocument(secondWorkspace, language, secondText, secondPath); + + var firstTree = await firstDocument.GetSyntaxTreeAsync(CancellationToken.None); + var secondTree = await secondDocument.GetSyntaxTreeAsync(CancellationToken.None); + Assert.NotNull(firstTree); + Assert.NotNull(secondTree); + var firstRoot = await firstTree.GetRootAsync(CancellationToken.None); + var secondRoot = await secondTree.GetRootAsync(CancellationToken.None); + + Assert.NotSame(firstTree, secondTree); + Assert.NotSame(firstRoot, secondRoot); + Assert.True(firstRoot.IsIncrementallyIdenticalTo(secondRoot)); + Assert.Equal(firstPath, firstTree.FilePath); + Assert.Equal(secondPath, secondTree.FilePath); + Assert.Same(firstText, firstTree.GetText()); + Assert.Same(secondText, secondTree.GetText()); + Assert.NotEqual(firstDocument.Id, secondDocument.Id); + + var changedDocument = secondDocument.WithText(SourceText.From(source + "\r\nclass D { }")); + var changedTree = await changedDocument.GetSyntaxTreeAsync(CancellationToken.None); + Assert.NotNull(changedTree); + var changedRoot = await changedTree.GetRootAsync(CancellationToken.None); + Assert.False(firstRoot.IsIncrementallyIdenticalTo(changedRoot)); + Assert.Equal(source, firstRoot.ToFullString()); + } + + [Fact] + public async Task DifferentParseOptionsDoNotShareGreenNodes() + { + const string source = "class C { }"; + var hostServices = GetLanguageServerHostServices(); + using var firstWorkspace = new AdhocWorkspace(hostServices, WorkspaceKind.Host); + using var secondWorkspace = new AdhocWorkspace(hostServices, WorkspaceKind.Host); + + var firstDocument = AddDocument( + firstWorkspace, LanguageNames.CSharp, SourceText.From(source), "first.cs", + CSharpParseOptions.Default.WithPreprocessorSymbols("FIRST")); + var secondDocument = AddDocument( + secondWorkspace, LanguageNames.CSharp, SourceText.From(source), "second.cs", + CSharpParseOptions.Default.WithPreprocessorSymbols("SECOND")); + + var firstTree = await firstDocument.GetSyntaxTreeAsync(CancellationToken.None); + var secondTree = await secondDocument.GetSyntaxTreeAsync(CancellationToken.None); + Assert.NotNull(firstTree); + Assert.NotNull(secondTree); + var firstRoot = await firstTree.GetRootAsync(CancellationToken.None); + var secondRoot = await secondTree.GetRootAsync(CancellationToken.None); + + Assert.False(firstRoot.IsIncrementallyIdenticalTo(secondRoot)); + } + + [Fact] + public async Task ConcurrentPublicationConvergesOnOneRoot() + { + var cache = new SyntaxTreeCacheService(maximumEntryCount: 10); + var text = SourceText.From("class C { }"); + var key = cache.CreateKey(LanguageNames.CSharp, text, CSharpParseOptions.Default); + + var roots = await Task.WhenAll( + Enumerable.Range(0, 16).Select(_ => Task.Run( + () => cache.GetOrAddRoot(key, CSharpSyntaxTree.ParseText(text).GetRoot())))); + + var canonicalRoot = roots[0]; + Assert.All(roots, root => Assert.Same(canonicalRoot, root)); + Assert.Equal(1, cache.GetTestAccessor().EntryCount); + Assert.True(cache.GetTestAccessor().PublicationRaceCount > 0); + } + + [Fact] + public void DeadRootsDoNotConsumeCapacity() + { + var cache = new SyntaxTreeCacheService(maximumEntryCount: 1); + var firstText = SourceText.From("class First { }"); + var firstKey = cache.CreateKey(LanguageNames.CSharp, firstText, CSharpParseOptions.Default); + var weakRoot = AddRootWithoutRetainingIt(cache, firstKey, firstText); + + CollectGarbage(); + Assert.False(weakRoot.TryGetTarget(out _)); + + var secondText = SourceText.From("class Second { }"); + var secondKey = cache.CreateKey(LanguageNames.CSharp, secondText, CSharpParseOptions.Default); + var secondRoot = CSharpSyntaxTree.ParseText(secondText).GetRoot(); + + Assert.Same(secondRoot, cache.GetOrAddRoot(secondKey, secondRoot)); + Assert.False(cache.TryGetRoot(firstKey, out _)); + Assert.True(cache.TryGetRoot(secondKey, out var cachedSecondRoot)); + Assert.Same(secondRoot, cachedSecondRoot); + Assert.Equal(1, cache.GetTestAccessor().EntryCount); + } + + [Fact] + public void DeadLookupReleasesCapacity() + { + var cache = new SyntaxTreeCacheService(maximumEntryCount: 1); + var text = SourceText.From("class C { }"); + var key = cache.CreateKey(LanguageNames.CSharp, text, CSharpParseOptions.Default); + var weakRoot = AddRootWithoutRetainingIt(cache, key, text); + + CollectGarbage(); + Assert.False(weakRoot.TryGetTarget(out _)); + + Assert.False(cache.TryGetRoot(key, out _)); + Assert.Equal(0, cache.GetTestAccessor().EntryCount); + } + + [Fact] + public void LiveRootsEnforceCapacityLimit() + { + var cache = new SyntaxTreeCacheService(maximumEntryCount: 1); + var firstText = SourceText.From("class First { }"); + var secondText = SourceText.From("class Second { }"); + var firstKey = cache.CreateKey(LanguageNames.CSharp, firstText, CSharpParseOptions.Default); + var secondKey = cache.CreateKey(LanguageNames.CSharp, secondText, CSharpParseOptions.Default); + var firstRoot = CSharpSyntaxTree.ParseText(firstText).GetRoot(); + var secondRoot = CSharpSyntaxTree.ParseText(secondText).GetRoot(); + + Assert.Same(firstRoot, cache.GetOrAddRoot(firstKey, firstRoot)); + Assert.Same(secondRoot, cache.GetOrAddRoot(secondKey, secondRoot)); + + Assert.True(cache.TryGetRoot(firstKey, out var cachedFirstRoot)); + Assert.Same(firstRoot, cachedFirstRoot); + Assert.False(cache.TryGetRoot(secondKey, out _)); + Assert.Equal(1, cache.GetTestAccessor().EntryCount); + Assert.Equal(1, cache.GetTestAccessor().AdmissionBypassCount); + } + + [Fact] + public void SaturatedCacheDoesNotScanForEveryAdmission() + { + var cache = new SyntaxTreeCacheService(maximumEntryCount: 1); + var firstText = SourceText.From("class First { }"); + var firstKey = cache.CreateKey(LanguageNames.CSharp, firstText, CSharpParseOptions.Default); + var firstRoot = CSharpSyntaxTree.ParseText(firstText).GetRoot(); + Assert.Same(firstRoot, cache.GetOrAddRoot(firstKey, firstRoot)); + + for (var i = 0; i < 10; i++) + { + var text = SourceText.From($"class C{i} {{ }}"); + var key = cache.CreateKey(LanguageNames.CSharp, text, CSharpParseOptions.Default); + var root = CSharpSyntaxTree.ParseText(text).GetRoot(); + Assert.Same(root, cache.GetOrAddRoot(key, root)); + } + + var accessor = cache.GetTestAccessor(); + Assert.Equal(1, accessor.CleanupCount); + Assert.Equal(10, accessor.AdmissionBypassCount); + } + + [Fact] + public void CacheKeysIncludeLanguage() + { + var cache = new SyntaxTreeCacheService(maximumEntryCount: 2); + var text = SourceText.From("class C { }"); + var csharpKey = cache.CreateKey(LanguageNames.CSharp, text, CSharpParseOptions.Default); + var otherLanguageKey = cache.CreateKey("Other", text, CSharpParseOptions.Default); + var csharpRoot = CSharpSyntaxTree.ParseText(text).GetRoot(); + var otherRoot = CSharpSyntaxTree.ParseText(text).GetRoot(); + + Assert.Same(csharpRoot, cache.GetOrAddRoot(csharpKey, csharpRoot)); + Assert.Same(otherRoot, cache.GetOrAddRoot(otherLanguageKey, otherRoot)); + Assert.NotSame(csharpRoot, otherRoot); + } + + private HostServices GetLanguageServerHostServices() + { + var exportProvider = LanguageServerTestComposition.GetSharedExportProvider(ServerConfigurationWithoutDevKit, LoggerFactory); + return exportProvider.GetExportedValue().HostServices; + } + + private static Document AddDocument( + AdhocWorkspace workspace, + string language, + SourceText text, + string filePath, + ParseOptions? parseOptions = null) + { + var project = workspace.AddProject(Guid.NewGuid().ToString(), language); + if (parseOptions is not null) + { + Assert.True(workspace.TryApplyChanges(project.Solution.WithProjectParseOptions(project.Id, parseOptions))); + project = workspace.CurrentSolution.GetProject(project.Id); + Assert.NotNull(project); + } + + var documentId = DocumentId.CreateNewId(project.Id); + var loader = TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create(), filePath)); + return workspace.AddDocument(DocumentInfo.Create( + documentId, Path.GetFileName(filePath), loader: loader, filePath: filePath)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference AddRootWithoutRetainingIt( + SyntaxTreeCacheService cache, SyntaxTreeCacheKey key, SourceText text) + { + var root = CSharpSyntaxTree.ParseText(text).GetRoot(); + Assert.Same(root, cache.GetOrAddRoot(key, root)); + return new(root); + } + + private static void CollectGarbage() + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + } +} diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs index d6ca60fbc4ff..c53940c365ac 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs @@ -6,6 +6,7 @@ using Microsoft.CodeAnalysis.UnitTests; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.Composition; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO.Pipelines; @@ -34,6 +35,7 @@ public abstract class AbstractLanguageServerHostTests : IDisposable /// watch it created once it shuts down (see ). /// private readonly FileWatcherReleaseTracker _fileWatcherReleaseTracker; + private readonly List _ownedExportProviders = []; internal static ServerConfiguration DefaultServerConfiguration => new( LaunchDebugger: false, @@ -52,13 +54,22 @@ public abstract class AbstractLanguageServerHostTests : IDisposable internal static ServerConfiguration ServerConfigurationWithoutDevKit => DefaultServerConfiguration with { DevKitDependencyPath = null }; + protected virtual bool IncludeSyntaxTreeCache => true; + protected virtual bool UseSharedExportProviderCache => true; + private protected virtual Task CreateExportProviderAsync( ServerConfiguration serverConfiguration, ILoggerFactory loggerFactory, ExtensionAssemblyManager extensionManager, IAssemblyLoader assemblyLoader) { - var provider = LanguageServerTestComposition.GetSharedExportProvider(serverConfiguration, loggerFactory); + var provider = UseSharedExportProviderCache + ? LanguageServerTestComposition.GetSharedExportProvider(serverConfiguration, loggerFactory) + : LanguageServerTestComposition.CreateExportProviderForBenchmark(serverConfiguration, loggerFactory, IncludeSyntaxTreeCache); + + if (!UseSharedExportProviderCache) + _ownedExportProviders.Add(provider); + return Task.FromResult(provider); } @@ -113,11 +124,19 @@ internal static async Task WaitForConditionAsync(Func condition) public void Dispose() { - TempRoot.Dispose(); + try + { + TempRoot.Dispose(); - // The test's server(s) are disposed by the test body (via 'await using'), which releases their file watches on - // shutdown. Verify that actually happened so a watch-leaking test fails here rather than leaking into a later test. - _fileWatcherReleaseTracker.AssertWatchesReleased(); + // The test's server(s) are disposed by the test body (via 'await using'), which releases their file watches on + // shutdown. Verify that actually happened so a watch-leaking test fails here rather than leaking into a later test. + _fileWatcherReleaseTracker.AssertWatchesReleased(); + } + finally + { + foreach (var exportProvider in _ownedExportProviders) + exportProvider.Dispose(); + } } /// @@ -213,6 +232,9 @@ private void HandleWindowLogMessage(int type, string message, ITestOutputHelper internal T GetRequiredLspService() where T : class => GetServerForLspServices().GetLspServices().GetRequiredService(); + internal Workspace GetHostWorkspace() + => GetRequiredLspService().HostWorkspace; + internal async Task OpenProjectsAsync(ImmutableArray projectFilePaths, CancellationToken cancellationToken) { Contract.ThrowIfTrue(projectFilePaths.IsEmpty); diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs index c54c5cbdf74b..01af7418ada7 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Reflection; +using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; using Microsoft.CodeAnalysis.LanguageServer.Services; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.Extensions.Logging; @@ -25,16 +26,36 @@ public static Task CreateLanguageServerExportProviderAsync( public static ExportProvider GetSharedExportProvider(ServerConfiguration serverConfiguration, ILoggerFactory loggerFactory) { Contract.ThrowIfTrue(serverConfiguration.ExtensionAssemblyPaths.Any(), "Tests that require extension assemblies should use AbstractLanguageServerMefHost instead"); - var exportProvider = serverConfiguration.DevKitDependencyPath != null - ? s_devKit.ExportProviderFactory.CreateExportProvider() - : s_languageServer.ExportProviderFactory.CreateExportProvider(); + var composition = serverConfiguration.DevKitDependencyPath != null ? s_devKit : s_languageServer; + var exportProvider = composition.ExportProviderFactory.CreateExportProvider(); LanguageServerExportProviderBuilder.TestAccessor.InitializeManualExports(exportProvider, new ExtensionAssemblyManager([], [], []), loggerFactory, serverConfiguration); return exportProvider; } + public static ExportProvider CreateExportProviderForBenchmark( + ServerConfiguration serverConfiguration, + ILoggerFactory loggerFactory, + bool includeSyntaxTreeCache) + { + Contract.ThrowIfTrue(serverConfiguration.ExtensionAssemblyPaths.Any()); + Contract.ThrowIfTrue(serverConfiguration.DevKitDependencyPath is not null); + + var exportProviderFactory = includeSyntaxTreeCache + ? s_languageServerExportProviderFactory.Value + : s_languageServerWithoutSyntaxTreeCacheExportProviderFactory.Value; + var exportProvider = exportProviderFactory.CreateExportProvider(); + LanguageServerExportProviderBuilder.TestAccessor.InitializeManualExports( + exportProvider, new ExtensionAssemblyManager([], [], []), loggerFactory, serverConfiguration); + return exportProvider; + } + private static readonly TestComposition s_languageServer = CreateBaseComposition(); private static readonly TestComposition s_devKit = CreateDevKitComposition(); + private static readonly Lazy s_languageServerExportProviderFactory = + new(() => CreateExportProviderFactory(s_languageServer)); + private static readonly Lazy s_languageServerWithoutSyntaxTreeCacheExportProviderFactory = + new(() => CreateExportProviderFactory(s_languageServer.AddExcludedPartTypes(typeof(SyntaxTreeCacheService)))); private static TestComposition CreateBaseComposition() { @@ -49,4 +70,10 @@ private static TestComposition CreateDevKitComposition() var devKitDirectory = TestPaths.GetDevKitExtensionPath(); return s_languageServer.AddAssemblies(Assembly.LoadFrom(devKitDirectory)); } + + private static IExportProviderFactory CreateExportProviderFactory(TestComposition composition) + { + var configuration = composition.GetCompositionConfiguration(); + return RuntimeComposition.CreateRuntimeComposition(configuration).CreateExportProviderFactory(); + } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs new file mode 100644 index 000000000000..af6a78f40e46 --- /dev/null +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs @@ -0,0 +1,201 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Concurrent; +using System.Composition; +using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; + +[ExportWorkspaceService(typeof(ISyntaxTreeCacheService), ServiceLayer.Host), Shared] +internal sealed class SyntaxTreeCacheService : ISyntaxTreeCacheService +{ + // Accommodates several large solutions while placing a fixed upper bound on retained cache keys. + private const int DefaultMaximumEntryCount = 100_000; + private const int MinimumCleanupInterval = 256; + + private readonly ConcurrentDictionary> _roots = []; + private readonly int _maximumEntryCount; + private readonly int _cleanupInterval; + + private int _entryCount; + private int _publicationCount; + private int _admissionAttemptCount; + private int _cleanupInProgress; + private int _lookupCount; + private int _hitCount; + private int _deadRootCount; + private int _publicationRaceCount; + private int _admissionBypassCount; + private int _cleanupCount; + private int _refreshCount; + + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public SyntaxTreeCacheService() + : this(DefaultMaximumEntryCount) + { + } + + internal SyntaxTreeCacheService(int maximumEntryCount) + { + Contract.ThrowIfFalse(maximumEntryCount > 0); + _maximumEntryCount = maximumEntryCount; + _cleanupInterval = Math.Max(MinimumCleanupInterval, maximumEntryCount / 10); + } + + public SyntaxTreeCacheKey CreateKey(string language, SourceText text, ParseOptions options) + => new(language, Checksum.From(text.GetContentHash()), options); + + public bool TryGetRoot(SyntaxTreeCacheKey key, out SyntaxNode? root) + { + Interlocked.Increment(ref _lookupCount); + + if (_roots.TryGetValue(key, out var weakRoot) && + weakRoot.TryGetTarget(out root)) + { + Interlocked.Increment(ref _hitCount); + return true; + } + + if (weakRoot is not null) + { + Interlocked.Increment(ref _deadRootCount); + RemoveDeadEntry(key, weakRoot); + } + + root = null; + return false; + } + + public SyntaxNode GetOrAddRoot(SyntaxTreeCacheKey key, SyntaxNode root) + { + var newWeakRoot = new WeakReference(root); + + while (true) + { + if (_roots.TryGetValue(key, out var existingWeakRoot)) + { + if (existingWeakRoot.TryGetTarget(out var existingRoot)) + { + Interlocked.Increment(ref _publicationRaceCount); + return existingRoot; + } + + if (_roots.TryUpdate(key, newWeakRoot, existingWeakRoot)) + return root; + + continue; + } + + if (!TryReserveEntry()) + { + Interlocked.Increment(ref _admissionBypassCount); + return root; + } + + if (_roots.TryAdd(key, newWeakRoot)) + { + CleanupIfNeeded(); + return root; + } + + Interlocked.Decrement(ref _entryCount); + } + } + + public void RefreshRoot(SyntaxTreeCacheKey key, SyntaxNode root) + { + var newWeakRoot = new WeakReference(root); + + while (_roots.TryGetValue(key, out var existingWeakRoot)) + { + if (_roots.TryUpdate(key, newWeakRoot, existingWeakRoot)) + { + Interlocked.Increment(ref _refreshCount); + return; + } + } + + _ = GetOrAddRoot(key, root); + } + + private bool TryReserveEntry() + { + while (true) + { + var entryCount = Volatile.Read(ref _entryCount); + if (entryCount >= _maximumEntryCount) + { + CleanupForAdmission(); + entryCount = Volatile.Read(ref _entryCount); + if (entryCount >= _maximumEntryCount) + return false; + } + + if (Interlocked.CompareExchange(ref _entryCount, entryCount + 1, entryCount) == entryCount) + return true; + } + } + + private void CleanupIfNeeded() + { + if (Interlocked.Increment(ref _publicationCount) % _cleanupInterval == 0) + RemoveDeadEntries(); + } + + private void CleanupForAdmission() + { + var admissionAttemptCount = Interlocked.Increment(ref _admissionAttemptCount); + if (admissionAttemptCount == 1 || admissionAttemptCount % _cleanupInterval == 0) + RemoveDeadEntries(); + } + + private void RemoveDeadEntries() + { + if (Interlocked.CompareExchange(ref _cleanupInProgress, 1, 0) != 0) + return; + + try + { + Interlocked.Increment(ref _cleanupCount); + + foreach (var (key, weakRoot) in _roots) + { + if (!weakRoot.TryGetTarget(out _)) + RemoveDeadEntry(key, weakRoot); + } + } + finally + { + Volatile.Write(ref _cleanupInProgress, 0); + } + } + + private void RemoveDeadEntry(SyntaxTreeCacheKey key, WeakReference weakRoot) + { + if (((ICollection>>)_roots).Remove(new(key, weakRoot))) + Interlocked.Decrement(ref _entryCount); + } + + internal int EntryCount + => Volatile.Read(ref _entryCount); + + internal TestAccessor GetTestAccessor() + => new(this); + + internal readonly struct TestAccessor(SyntaxTreeCacheService service) + { + public int EntryCount => Volatile.Read(ref service._entryCount); + public int LookupCount => Volatile.Read(ref service._lookupCount); + public int HitCount => Volatile.Read(ref service._hitCount); + public int DeadRootCount => Volatile.Read(ref service._deadRootCount); + public int PublicationRaceCount => Volatile.Read(ref service._publicationRaceCount); + public int AdmissionBypassCount => Volatile.Read(ref service._admissionBypassCount); + public int CleanupCount => Volatile.Read(ref service._cleanupCount); + public int RefreshCount => Volatile.Read(ref service._refreshCount); + } +} diff --git a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/LspTestWorkspaces.cs b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/LspTestWorkspaces.cs index 391aeaf62c38..e2787a97b0c9 100644 --- a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/LspTestWorkspaces.cs +++ b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/LspTestWorkspaces.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Text; + namespace Microsoft.CodeAnalysis.LanguageServer.Test.Utilities; internal static class LspTestWorkspaces @@ -19,8 +21,14 @@ public static LspWorkspaceContent SimpleProject .WithLoadPath("Project.csproj") .WithRestore(); - public static LspWorkspaceContent CreateConsoleApplication(string projectName) - => LspWorkspaceContent.Empty + public static LspWorkspaceContent CreateConsoleApplication( + string projectName, + int sharedDocumentCount = 0, + int uniqueDocumentCount = 0, + int declarationsPerDocument = 1, + string? uniqueDocumentPrefix = null) + { + var content = LspWorkspaceContent.Empty .WithFile($"{projectName}.csproj", """ @@ -34,4 +42,32 @@ public static LspWorkspaceContent CreateConsoleApplication(string projectName) """) .WithLoadPath($"{projectName}.csproj") .WithRestore(); + + for (var i = 0; i < sharedDocumentCount; i++) + content = content.WithFile($"Shared{i:D4}.cs", CreateDocument("SharedWorkspace0", i, declarationsPerDocument)); + + for (var i = 0; i < uniqueDocumentCount; i++) + content = content.WithFile($"Unique{i:D4}.cs", CreateDocument(uniqueDocumentPrefix ?? projectName, i, declarationsPerDocument)); + + return content; + } + + private static string CreateDocument(string prefix, int documentIndex, int declarationsPerDocument) + { + var builder = new StringBuilder(); + builder.AppendLine("namespace BenchmarkDocuments;"); + + for (var declarationIndex = 0; declarationIndex < declarationsPerDocument; declarationIndex++) + { + builder.AppendLine($$""" + internal sealed class {{prefix}}Document{{documentIndex}}Type{{declarationIndex}} + { + public int Value { get; } = {{declarationIndex}}; + public string GetDescription() => "{{prefix}}-{{documentIndex}}-{{declarationIndex}}"; + } + """); + } + + return builder.ToString(); + } } diff --git a/src/Tools/IdeCoreBenchmarks/Program.cs b/src/Tools/IdeCoreBenchmarks/Program.cs index db7bb715c608..b70275ceea9c 100644 --- a/src/Tools/IdeCoreBenchmarks/Program.cs +++ b/src/Tools/IdeCoreBenchmarks/Program.cs @@ -43,6 +43,14 @@ public static string GetRoslynRootLocation([CallerFilePath] string sourceFilePat private static int Main(string[] args) { Environment.SetEnvironmentVariable(RoslynRootPathEnvVariableName, GetRoslynRootLocation()); +#if !NET472 + if (args is ["--retained-syntax-tree-cache-memory", var includeCache, var sharedDocumentCount]) + { + return LanguageServerDaemonBenchmarks.RunRetainedMemoryScenarioAsync( + bool.Parse(includeCache), int.Parse(sharedDocumentCount)).GetAwaiter().GetResult(); + } +#endif + // BenchmarkDotNet gives its generated runner a single output directory through global // MSBuild properties. If those properties flow into Roslyn's multi-targeted project graph, // different projects and target frameworks share output and intermediate paths, causing diff --git a/src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.cs b/src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.cs index 96c310b912ae..555d1611866f 100644 --- a/src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.cs +++ b/src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.cs @@ -15,14 +15,12 @@ namespace Microsoft.CodeAnalysis.CSharp; -[ExportLanguageService(typeof(ISyntaxTreeFactoryService), LanguageNames.CSharp), Shared] internal sealed partial class CSharpSyntaxTreeFactoryService : AbstractSyntaxTreeFactoryService { private static readonly CSharpParseOptions _parseOptionWithLatestLanguageVersion = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview); - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public CSharpSyntaxTreeFactoryService() + public CSharpSyntaxTreeFactoryService(ISyntaxTreeCacheService syntaxTreeCache) + : base(LanguageNames.CSharp, syntaxTreeCache) { } @@ -61,9 +59,19 @@ public override SyntaxTree CreateSyntaxTree(string filePath, ParseOptions option return new ParsedSyntaxTree(text, (CSharpSyntaxNode)root, (CSharpParseOptions)options, filePath, encoding, checksumAlgorithm); } - public override SyntaxTree ParseSyntaxTree(string filePath, ParseOptions options, SourceText text, CancellationToken cancellationToken) + protected override SyntaxTree ParseSyntaxTreeCore(string filePath, ParseOptions options, SourceText text, CancellationToken cancellationToken) + => SyntaxFactory.ParseSyntaxTree(text, options, filePath, cancellationToken: cancellationToken); +} + +[ExportLanguageServiceFactory(typeof(ISyntaxTreeFactoryService), LanguageNames.CSharp), Shared] +internal sealed class CSharpSyntaxTreeFactoryServiceFactory : ILanguageServiceFactory +{ + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public CSharpSyntaxTreeFactoryServiceFactory() { - options ??= GetDefaultParseOptions(); - return SyntaxFactory.ParseSyntaxTree(text, options, filePath, cancellationToken: cancellationToken); } + + public ILanguageService CreateLanguageService(HostLanguageServices languageServices) + => new CSharpSyntaxTreeFactoryService(languageServices.WorkspaceServices.GetService()); } diff --git a/src/Workspaces/CSharpTest/CSharpSyntaxTreeFactoryServiceTests.cs b/src/Workspaces/CSharpTest/CSharpSyntaxTreeFactoryServiceTests.cs new file mode 100644 index 000000000000..281956b277ff --- /dev/null +++ b/src/Workspaces/CSharpTest/CSharpSyntaxTreeFactoryServiceTests.cs @@ -0,0 +1,29 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Threading; +using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Test.Utilities; +using Microsoft.CodeAnalysis.Text; +using Xunit; + +namespace Microsoft.CodeAnalysis.CSharp.UnitTests; + +[UseExportProvider] +public sealed class CSharpSyntaxTreeFactoryServiceTests +{ + [Fact] + public void LanguageServiceFactoryCreatesSyntaxTreesWithoutCache() + { + using var workspace = new AdhocWorkspace(); + var service = workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(); + var text = SourceText.From("class C { }"); + + var tree = service.ParseSyntaxTree("test.cs", CSharpParseOptions.Default, text, CancellationToken.None); + + Assert.Equal("test.cs", tree.FilePath); + Assert.Same(text, tree.GetText()); + Assert.IsType(tree.GetRoot()); + } +} diff --git a/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/AbstractSyntaxTreeFactoryService.cs b/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/AbstractSyntaxTreeFactoryService.cs index 94c103435fb2..698265a1d38e 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/AbstractSyntaxTreeFactoryService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/AbstractSyntaxTreeFactoryService.cs @@ -13,10 +13,47 @@ namespace Microsoft.CodeAnalysis.Host; internal abstract partial class AbstractSyntaxTreeFactoryService : ISyntaxTreeFactoryService { + private readonly string _language; + private readonly ISyntaxTreeCacheService _syntaxTreeCache; + + protected AbstractSyntaxTreeFactoryService(string language, ISyntaxTreeCacheService syntaxTreeCache) + { + _language = language; + _syntaxTreeCache = syntaxTreeCache; + } + public abstract ParseOptions GetDefaultParseOptions(); public abstract ParseOptions GetDefaultParseOptionsWithLatestLanguageVersion(); public abstract bool OptionsDifferOnlyByPreprocessorDirectives(ParseOptions options1, ParseOptions options2); public abstract ParseOptions TryParsePdbParseOptions(IReadOnlyDictionary metadata); public abstract SyntaxTree CreateSyntaxTree(string filePath, ParseOptions options, SourceText text, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, SyntaxNode root); - public abstract SyntaxTree ParseSyntaxTree(string filePath, ParseOptions options, SourceText text, CancellationToken cancellationToken); + + public SyntaxTree ParseSyntaxTree(string filePath, ParseOptions options, SourceText text, CancellationToken cancellationToken) + { + options ??= GetDefaultParseOptions(); + + if (_syntaxTreeCache is null) + return ParseSyntaxTreeCore(filePath, options, text, cancellationToken); + + var key = _syntaxTreeCache.CreateKey(_language, text, options); + if (_syntaxTreeCache.TryGetRoot(key, out var cachedRoot)) + { + var cachedTree = CreateSyntaxTree(filePath, options, text, text.Encoding, text.ChecksumAlgorithm, cachedRoot); + _syntaxTreeCache.RefreshRoot(key, cachedTree.GetRoot(cancellationToken)); + return cachedTree; + } + + var parsedTree = ParseSyntaxTreeCore(filePath, options, text, cancellationToken); + var parsedRoot = parsedTree.GetRoot(cancellationToken); + var canonicalRoot = _syntaxTreeCache.GetOrAddRoot(key, parsedRoot); + + if (canonicalRoot == parsedRoot) + return parsedTree; + + var raceTree = CreateSyntaxTree(filePath, options, text, text.Encoding, text.ChecksumAlgorithm, canonicalRoot); + _syntaxTreeCache.RefreshRoot(key, raceTree.GetRoot(cancellationToken)); + return raceTree; + } + + protected abstract SyntaxTree ParseSyntaxTreeCore(string filePath, ParseOptions options, SourceText text, CancellationToken cancellationToken); } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/ISyntaxTreeCacheService.cs b/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/ISyntaxTreeCacheService.cs new file mode 100644 index 000000000000..6982bac76ae8 --- /dev/null +++ b/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/ISyntaxTreeCacheService.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Host; + +internal readonly record struct SyntaxTreeCacheKey(string Language, Checksum TextChecksum, ParseOptions Options); + +internal interface ISyntaxTreeCacheService : IWorkspaceService +{ + SyntaxTreeCacheKey CreateKey(string language, SourceText text, ParseOptions options); + + bool TryGetRoot(SyntaxTreeCacheKey key, out SyntaxNode? root); + + SyntaxNode GetOrAddRoot(SyntaxTreeCacheKey key, SyntaxNode root); + + void RefreshRoot(SyntaxTreeCacheKey key, SyntaxNode root); +} diff --git a/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicSyntaxTreeFactoryService.vb b/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicSyntaxTreeFactoryService.vb index 0535d17e0539..4c96f7552b7d 100644 --- a/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicSyntaxTreeFactoryService.vb +++ b/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicSyntaxTreeFactoryService.vb @@ -10,15 +10,13 @@ Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic - Partial Friend Class VisualBasicSyntaxTreeFactoryService Inherits AbstractSyntaxTreeFactoryService Private Shared ReadOnly _parseOptionsWithLatestLanguageVersion As VisualBasicParseOptions = VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest) - - - Public Sub New() + Public Sub New(syntaxTreeCache As ISyntaxTreeCacheService) + MyBase.New(LanguageNames.VisualBasic, syntaxTreeCache) End Sub Public Overloads Overrides Function GetDefaultParseOptions() As ParseOptions @@ -61,11 +59,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Return _parseOptionsWithLatestLanguageVersion End Function - Public Overrides Function ParseSyntaxTree(filePath As String, options As ParseOptions, text As SourceText, cancellationToken As CancellationToken) As SyntaxTree - If options Is Nothing Then - options = GetDefaultParseOptions() - End If - + Protected Overrides Function ParseSyntaxTreeCore(filePath As String, options As ParseOptions, text As SourceText, cancellationToken As CancellationToken) As SyntaxTree Return SyntaxFactory.ParseSyntaxTree(text, options, filePath, cancellationToken) End Function @@ -77,4 +71,18 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Return New ParsedSyntaxTree(text, DirectCast(root, VisualBasicSyntaxNode), DirectCast(options, VisualBasicParseOptions), filePath, encoding, checksumAlgorithm) End Function End Class + + + Friend Class VisualBasicSyntaxTreeFactoryServiceFactory + Implements ILanguageServiceFactory + + + + Public Sub New() + End Sub + + Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService + Return New VisualBasicSyntaxTreeFactoryService(languageServices.WorkspaceServices.GetService(Of ISyntaxTreeCacheService)()) + End Function + End Class End Namespace diff --git a/src/Workspaces/VisualBasicTest/VisualBasicSyntaxTreeFactoryServiceTests.vb b/src/Workspaces/VisualBasicTest/VisualBasicSyntaxTreeFactoryServiceTests.vb new file mode 100644 index 000000000000..45b13f8cec76 --- /dev/null +++ b/src/Workspaces/VisualBasicTest/VisualBasicSyntaxTreeFactoryServiceTests.vb @@ -0,0 +1,29 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. +' See the LICENSE file in the project root for more information. + +Imports System.Threading +Imports Microsoft.CodeAnalysis.Host +Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.Text +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Xunit + +Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests + + Public Class VisualBasicSyntaxTreeFactoryServiceTests + + Public Sub LanguageServiceFactoryCreatesSyntaxTrees() + Using workspace = New AdhocWorkspace() + Dim service = workspace.Services.GetLanguageServices(LanguageNames.VisualBasic).GetRequiredService(Of ISyntaxTreeFactoryService)() + Dim text = SourceText.From("Class C" & vbCrLf & "End Class") + + Dim tree = service.ParseSyntaxTree("test.vb", VisualBasicParseOptions.Default, text, CancellationToken.None) + + Assert.Equal("test.vb", tree.FilePath) + Assert.Same(text, tree.GetText()) + Assert.IsType(Of CompilationUnitSyntax)(tree.GetRoot()) + End Using + End Sub + End Class +End Namespace From 3a92f93bac9bf89cdf25749a47bf202fcd59a091 Mon Sep 17 00:00:00 2001 From: David Barbet Date: Tue, 4 Aug 2026 16:30:52 -0700 Subject: [PATCH 2/5] Refine shared syntax tree cache Simplify the cache to a single get-or-create operation, track all live red roots weakly, periodically prune dead entries, and key sharing by content plus parse options. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 1f56c314-c0d3-44d9-8630-c978f659a9ae --- .github/memory/FILE_MAP.md | 2 +- .github/memory/testing/ide.md | 3 - .../SyntaxTreeCacheServiceTests.cs | 189 +++++++------ .../AbstractLanguageServerHostTests.cs | 32 +-- .../LanguageServerTestComposition.cs | 33 +-- .../HostWorkspace/SyntaxTreeCacheService.cs | 254 ++++++++---------- .../LanguageServer/LspTestWorkspaces.cs | 40 +-- src/Tools/IdeCoreBenchmarks/Program.cs | 8 - .../CSharpSyntaxTreeFactoryService.cs | 2 +- .../AbstractSyntaxTreeFactoryService.cs | 31 +-- .../ISyntaxTreeCacheService.cs | 18 +- .../VisualBasicSyntaxTreeFactoryService.vb | 2 +- 12 files changed, 242 insertions(+), 372 deletions(-) diff --git a/.github/memory/FILE_MAP.md b/.github/memory/FILE_MAP.md index 492ce0f3bd4f..413aab748cd6 100644 --- a/.github/memory/FILE_MAP.md +++ b/.github/memory/FILE_MAP.md @@ -18,7 +18,7 @@ This file is a **top-level map only**. For per-area directory detail, read the m | `Compilers/` | compiler | C#/VB compilers (`Core`, `CSharp`, `VisualBasic`, `Server`). | | `Dependencies/` | compiler | High-performance pooled collections & threading. | | `ExpressionEvaluator/` | compiler | Debugger expression evaluator. | -| `Tools/` | compiler / ide | Compiler and IDE tooling (BuildBoss, IdeCoreBenchmarks, format tools). | +| `Tools/` | compiler | Compiler tooling (BuildBoss, format tools). | | `Workspaces/` | ide | Solution/Project/Document model, MSBuild loading, Remote (OOP). | | `Features/`, `EditorFeatures/` | ide | IDE feature logic and editor integration. | | `Analyzers/`, `CodeStyle/` | ide | IDE0xxx code-style analyzers & fixes. | diff --git a/.github/memory/testing/ide.md b/.github/memory/testing/ide.md index ca2f45d4029f..7da57bf11ffd 100644 --- a/.github/memory/testing/ide.md +++ b/.github/memory/testing/ide.md @@ -26,9 +26,6 @@ public class MyTests - Use `[UseExportProvider]` for any test that depends on MEF services (a missing attribute typically surfaces as an unrelated-looking failure). -- LanguageServer daemon and host tests derive from `AbstractLanguageServerHostTests`. - Hosts that opt out of the shared test export-provider cache receive independently - owned providers, which the base class disposes with the host. - Analyzer tests inherit from `AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest_NoEditor` (and the VB equivalents). diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs index bc8f98223a83..498a30891e01 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Runtime.CompilerServices; using System.Text; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; using Microsoft.CodeAnalysis.Text; +using Microsoft.CodeAnalysis.VisualBasic; +using Roslyn.Test.Utilities; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.HostWorkspace; @@ -83,115 +84,87 @@ public async Task DifferentParseOptionsDoNotShareGreenNodes() } [Fact] - public async Task ConcurrentPublicationConvergesOnOneRoot() + public async Task ConcurrentPublicationConvergesOnOneGreenRoot() { - var cache = new SyntaxTreeCacheService(maximumEntryCount: 10); + using var workspace = CreateCacheWorkspace(out var cache); var text = SourceText.From("class C { }"); - var key = cache.CreateKey(LanguageNames.CSharp, text, CSharpParseOptions.Default); - var roots = await Task.WhenAll( + var trees = await Task.WhenAll( Enumerable.Range(0, 16).Select(_ => Task.Run( - () => cache.GetOrAddRoot(key, CSharpSyntaxTree.ParseText(text).GetRoot())))); + () => GetOrCreateTree(cache, text)))); - var canonicalRoot = roots[0]; - Assert.All(roots, root => Assert.Same(canonicalRoot, root)); - Assert.Equal(1, cache.GetTestAccessor().EntryCount); - Assert.True(cache.GetTestAccessor().PublicationRaceCount > 0); + var canonicalRoot = trees[0].GetRoot(); + Assert.All(trees, tree => Assert.True(canonicalRoot.IsIncrementallyIdenticalTo(tree.GetRoot()))); } [Fact] - public void DeadRootsDoNotConsumeCapacity() + public void OlderLiveRootRemainsAvailableAfterNewerRootIsCollected() { - var cache = new SyntaxTreeCacheService(maximumEntryCount: 1); - var firstText = SourceText.From("class First { }"); - var firstKey = cache.CreateKey(LanguageNames.CSharp, firstText, CSharpParseOptions.Default); - var weakRoot = AddRootWithoutRetainingIt(cache, firstKey, firstText); - - CollectGarbage(); - Assert.False(weakRoot.TryGetTarget(out _)); - - var secondText = SourceText.From("class Second { }"); - var secondKey = cache.CreateKey(LanguageNames.CSharp, secondText, CSharpParseOptions.Default); - var secondRoot = CSharpSyntaxTree.ParseText(secondText).GetRoot(); - - Assert.Same(secondRoot, cache.GetOrAddRoot(secondKey, secondRoot)); - Assert.False(cache.TryGetRoot(firstKey, out _)); - Assert.True(cache.TryGetRoot(secondKey, out var cachedSecondRoot)); - Assert.Same(secondRoot, cachedSecondRoot); - Assert.Equal(1, cache.GetTestAccessor().EntryCount); - } - - [Fact] - public void DeadLookupReleasesCapacity() - { - var cache = new SyntaxTreeCacheService(maximumEntryCount: 1); + using var workspace = CreateCacheWorkspace(out var cache); var text = SourceText.From("class C { }"); - var key = cache.CreateKey(LanguageNames.CSharp, text, CSharpParseOptions.Default); - var weakRoot = AddRootWithoutRetainingIt(cache, key, text); - - CollectGarbage(); - Assert.False(weakRoot.TryGetTarget(out _)); - - Assert.False(cache.TryGetRoot(key, out _)); - Assert.Equal(0, cache.GetTestAccessor().EntryCount); + var firstTree = GetOrCreateTree(cache, text); + var firstRoot = firstTree.GetRoot(); + var secondRootReference = ObjectReference.CreateFromFactory( + static state => + { + var root = GetOrCreateTree(state.cache, state.text).GetRoot(); + Assert.True(state.expectedSharedRoot.IsIncrementallyIdenticalTo(root)); + return root; + }, + (cache, text, expectedSharedRoot: firstRoot)); + + secondRootReference.AssertReleased(); + + var thirdRoot = GetOrCreateTree(cache, text).GetRoot(); + Assert.True(firstRoot.IsIncrementallyIdenticalTo(thirdRoot)); } [Fact] - public void LiveRootsEnforceCapacityLimit() + public void PeriodicCleanupReleasesDeadKeys() { - var cache = new SyntaxTreeCacheService(maximumEntryCount: 1); - var firstText = SourceText.From("class First { }"); - var secondText = SourceText.From("class Second { }"); - var firstKey = cache.CreateKey(LanguageNames.CSharp, firstText, CSharpParseOptions.Default); - var secondKey = cache.CreateKey(LanguageNames.CSharp, secondText, CSharpParseOptions.Default); - var firstRoot = CSharpSyntaxTree.ParseText(firstText).GetRoot(); - var secondRoot = CSharpSyntaxTree.ParseText(secondText).GetRoot(); - - Assert.Same(firstRoot, cache.GetOrAddRoot(firstKey, firstRoot)); - Assert.Same(secondRoot, cache.GetOrAddRoot(secondKey, secondRoot)); - - Assert.True(cache.TryGetRoot(firstKey, out var cachedFirstRoot)); - Assert.Same(firstRoot, cachedFirstRoot); - Assert.False(cache.TryGetRoot(secondKey, out _)); - Assert.Equal(1, cache.GetTestAccessor().EntryCount); - Assert.Equal(1, cache.GetTestAccessor().AdmissionBypassCount); + using var workspace = CreateCacheWorkspace(out var cache); + var firstOptionsReference = ObjectReference.CreateFromFactory( + static state => + { + // The cache key strongly retains these unique options, so their lifetime lets this test observe + // whether periodic cleanup removed the entry after its weak roots died. + var options = CSharpParseOptions.Default.WithPreprocessorSymbols(Guid.NewGuid().ToString()); + _ = GetOrCreateTree(state.cache, state.text, options); + return options; + }, + (cache, text: SourceText.From("class First { }"))); + firstOptionsReference.AssertHeld(); + + cache.GetTestAccessor().TriggerCleanupOnNextAddedRoot(); + _ = GetOrCreateTree(cache, SourceText.From("class Second { }")); + + firstOptionsReference.AssertReleased(); } [Fact] - public void SaturatedCacheDoesNotScanForEveryAdmission() + public void DeadEntryIsReplaced() { - var cache = new SyntaxTreeCacheService(maximumEntryCount: 1); - var firstText = SourceText.From("class First { }"); - var firstKey = cache.CreateKey(LanguageNames.CSharp, firstText, CSharpParseOptions.Default); - var firstRoot = CSharpSyntaxTree.ParseText(firstText).GetRoot(); - Assert.Same(firstRoot, cache.GetOrAddRoot(firstKey, firstRoot)); - - for (var i = 0; i < 10; i++) - { - var text = SourceText.From($"class C{i} {{ }}"); - var key = cache.CreateKey(LanguageNames.CSharp, text, CSharpParseOptions.Default); - var root = CSharpSyntaxTree.ParseText(text).GetRoot(); - Assert.Same(root, cache.GetOrAddRoot(key, root)); - } - - var accessor = cache.GetTestAccessor(); - Assert.Equal(1, accessor.CleanupCount); - Assert.Equal(10, accessor.AdmissionBypassCount); + using var workspace = CreateCacheWorkspace(out var cache); + var text = SourceText.From("class C { }"); + var rootReference = ObjectReference.CreateFromFactory( + static state => GetOrCreateTree(state.cache, state.text).GetRoot(), + (cache, text)); + rootReference.AssertReleased(); + + var replacementRoot = GetOrCreateTree(cache, text).GetRoot(); + var cachedReplacementRoot = GetOrCreateTree(cache, text).GetRoot(); + Assert.True(replacementRoot.IsIncrementallyIdenticalTo(cachedReplacementRoot)); } [Fact] - public void CacheKeysIncludeLanguage() + public void DifferentLanguagesDoNotShareGreenNodes() { - var cache = new SyntaxTreeCacheService(maximumEntryCount: 2); + using var workspace = CreateCacheWorkspace(out var cache); var text = SourceText.From("class C { }"); - var csharpKey = cache.CreateKey(LanguageNames.CSharp, text, CSharpParseOptions.Default); - var otherLanguageKey = cache.CreateKey("Other", text, CSharpParseOptions.Default); - var csharpRoot = CSharpSyntaxTree.ParseText(text).GetRoot(); - var otherRoot = CSharpSyntaxTree.ParseText(text).GetRoot(); - - Assert.Same(csharpRoot, cache.GetOrAddRoot(csharpKey, csharpRoot)); - Assert.Same(otherRoot, cache.GetOrAddRoot(otherLanguageKey, otherRoot)); - Assert.NotSame(csharpRoot, otherRoot); + var csharpRoot = GetOrCreateTree(cache, text).GetRoot(); + var visualBasicRoot = GetOrCreateVisualBasicTree(cache, text).GetRoot(); + + Assert.False(csharpRoot.IsIncrementallyIdenticalTo(visualBasicRoot)); } private HostServices GetLanguageServerHostServices() @@ -200,6 +173,13 @@ private HostServices GetLanguageServerHostServices() return exportProvider.GetExportedValue().HostServices; } + private AdhocWorkspace CreateCacheWorkspace(out SyntaxTreeCacheService cache) + { + var workspace = new AdhocWorkspace(GetLanguageServerHostServices(), WorkspaceKind.Host); + cache = (SyntaxTreeCacheService)workspace.Services.GetRequiredService(); + return workspace; + } + private static Document AddDocument( AdhocWorkspace workspace, string language, @@ -221,19 +201,34 @@ private static Document AddDocument( documentId, Path.GetFileName(filePath), loader: loader, filePath: filePath)); } - [MethodImpl(MethodImplOptions.NoInlining)] - private static WeakReference AddRootWithoutRetainingIt( - SyntaxTreeCacheService cache, SyntaxTreeCacheKey key, SourceText text) + private static SyntaxTree GetOrCreateTree( + SyntaxTreeCacheService cache, + SourceText text, + CSharpParseOptions? options = null) { - var root = CSharpSyntaxTree.ParseText(text).GetRoot(); - Assert.Same(root, cache.GetOrAddRoot(key, root)); - return new(root); + options ??= CSharpParseOptions.Default; + return cache.GetOrCreateSyntaxTree( + text, + options, + static (state, _) => CSharpSyntaxTree.ParseText(state.text, state.options), + static (root, state) => CSharpSyntaxTree.Create((CSharpSyntaxNode)root, state.options), + (text, options), + CancellationToken.None); } - private static void CollectGarbage() + private static SyntaxTree GetOrCreateVisualBasicTree( + SyntaxTreeCacheService cache, + SourceText text, + VisualBasicParseOptions? options = null) { - GC.Collect(); - GC.WaitForPendingFinalizers(); - GC.Collect(); + options ??= VisualBasicParseOptions.Default; + return cache.GetOrCreateSyntaxTree( + text, + options, + static (state, _) => VisualBasicSyntaxTree.ParseText(state.text, state.options), + static (root, state) => VisualBasicSyntaxTree.Create((VisualBasicSyntaxNode)root, state.options), + (text, options), + CancellationToken.None); } + } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs index c53940c365ac..d6ca60fbc4ff 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/AbstractLanguageServerHostTests.cs @@ -6,7 +6,6 @@ using Microsoft.CodeAnalysis.UnitTests; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.Composition; -using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO.Pipelines; @@ -35,7 +34,6 @@ public abstract class AbstractLanguageServerHostTests : IDisposable /// watch it created once it shuts down (see ). /// private readonly FileWatcherReleaseTracker _fileWatcherReleaseTracker; - private readonly List _ownedExportProviders = []; internal static ServerConfiguration DefaultServerConfiguration => new( LaunchDebugger: false, @@ -54,22 +52,13 @@ public abstract class AbstractLanguageServerHostTests : IDisposable internal static ServerConfiguration ServerConfigurationWithoutDevKit => DefaultServerConfiguration with { DevKitDependencyPath = null }; - protected virtual bool IncludeSyntaxTreeCache => true; - protected virtual bool UseSharedExportProviderCache => true; - private protected virtual Task CreateExportProviderAsync( ServerConfiguration serverConfiguration, ILoggerFactory loggerFactory, ExtensionAssemblyManager extensionManager, IAssemblyLoader assemblyLoader) { - var provider = UseSharedExportProviderCache - ? LanguageServerTestComposition.GetSharedExportProvider(serverConfiguration, loggerFactory) - : LanguageServerTestComposition.CreateExportProviderForBenchmark(serverConfiguration, loggerFactory, IncludeSyntaxTreeCache); - - if (!UseSharedExportProviderCache) - _ownedExportProviders.Add(provider); - + var provider = LanguageServerTestComposition.GetSharedExportProvider(serverConfiguration, loggerFactory); return Task.FromResult(provider); } @@ -124,19 +113,11 @@ internal static async Task WaitForConditionAsync(Func condition) public void Dispose() { - try - { - TempRoot.Dispose(); + TempRoot.Dispose(); - // The test's server(s) are disposed by the test body (via 'await using'), which releases their file watches on - // shutdown. Verify that actually happened so a watch-leaking test fails here rather than leaking into a later test. - _fileWatcherReleaseTracker.AssertWatchesReleased(); - } - finally - { - foreach (var exportProvider in _ownedExportProviders) - exportProvider.Dispose(); - } + // The test's server(s) are disposed by the test body (via 'await using'), which releases their file watches on + // shutdown. Verify that actually happened so a watch-leaking test fails here rather than leaking into a later test. + _fileWatcherReleaseTracker.AssertWatchesReleased(); } /// @@ -232,9 +213,6 @@ private void HandleWindowLogMessage(int type, string message, ITestOutputHelper internal T GetRequiredLspService() where T : class => GetServerForLspServices().GetLspServices().GetRequiredService(); - internal Workspace GetHostWorkspace() - => GetRequiredLspService().HostWorkspace; - internal async Task OpenProjectsAsync(ImmutableArray projectFilePaths, CancellationToken cancellationToken) { Contract.ThrowIfTrue(projectFilePaths.IsEmpty); diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs index 01af7418ada7..c54c5cbdf74b 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/Utilities/LanguageServerTestComposition.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Reflection; -using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; using Microsoft.CodeAnalysis.LanguageServer.Services; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.Extensions.Logging; @@ -26,36 +25,16 @@ public static Task CreateLanguageServerExportProviderAsync( public static ExportProvider GetSharedExportProvider(ServerConfiguration serverConfiguration, ILoggerFactory loggerFactory) { Contract.ThrowIfTrue(serverConfiguration.ExtensionAssemblyPaths.Any(), "Tests that require extension assemblies should use AbstractLanguageServerMefHost instead"); - var composition = serverConfiguration.DevKitDependencyPath != null ? s_devKit : s_languageServer; - var exportProvider = composition.ExportProviderFactory.CreateExportProvider(); + var exportProvider = serverConfiguration.DevKitDependencyPath != null + ? s_devKit.ExportProviderFactory.CreateExportProvider() + : s_languageServer.ExportProviderFactory.CreateExportProvider(); LanguageServerExportProviderBuilder.TestAccessor.InitializeManualExports(exportProvider, new ExtensionAssemblyManager([], [], []), loggerFactory, serverConfiguration); return exportProvider; } - public static ExportProvider CreateExportProviderForBenchmark( - ServerConfiguration serverConfiguration, - ILoggerFactory loggerFactory, - bool includeSyntaxTreeCache) - { - Contract.ThrowIfTrue(serverConfiguration.ExtensionAssemblyPaths.Any()); - Contract.ThrowIfTrue(serverConfiguration.DevKitDependencyPath is not null); - - var exportProviderFactory = includeSyntaxTreeCache - ? s_languageServerExportProviderFactory.Value - : s_languageServerWithoutSyntaxTreeCacheExportProviderFactory.Value; - var exportProvider = exportProviderFactory.CreateExportProvider(); - LanguageServerExportProviderBuilder.TestAccessor.InitializeManualExports( - exportProvider, new ExtensionAssemblyManager([], [], []), loggerFactory, serverConfiguration); - return exportProvider; - } - private static readonly TestComposition s_languageServer = CreateBaseComposition(); private static readonly TestComposition s_devKit = CreateDevKitComposition(); - private static readonly Lazy s_languageServerExportProviderFactory = - new(() => CreateExportProviderFactory(s_languageServer)); - private static readonly Lazy s_languageServerWithoutSyntaxTreeCacheExportProviderFactory = - new(() => CreateExportProviderFactory(s_languageServer.AddExcludedPartTypes(typeof(SyntaxTreeCacheService)))); private static TestComposition CreateBaseComposition() { @@ -70,10 +49,4 @@ private static TestComposition CreateDevKitComposition() var devKitDirectory = TestPaths.GetDevKitExtensionPath(); return s_languageServer.AddAssemblies(Assembly.LoadFrom(devKitDirectory)); } - - private static IExportProviderFactory CreateExportProviderFactory(TestComposition composition) - { - var configuration = composition.GetCompositionConfiguration(); - return RuntimeComposition.CreateRuntimeComposition(configuration).CreateExportProviderFactory(); - } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs index af6a78f40e46..f03634401b18 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs @@ -4,153 +4,76 @@ using System.Collections.Concurrent; using System.Composition; +using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; +/// +/// Shares parsed syntax across workspaces by reusing immutable green syntax nodes. +/// +/// +/// The cache cannot store green nodes directly because their types are internal to the compiler assemblies. Instead, +/// it stores weak references to public red roots, which provide access to the green nodes they +/// wrap. A red root itself cannot be shared because it belongs to a specific containing the +/// caller's source text, file path, encoding, and checksum information. Cache hits therefore create a new syntax tree +/// and red root around the cached green node. +/// +/// Each cache key tracks all such red roots rather than only the most recently created root. Otherwise, unloading the +/// workspace that owns the newest root would make the cache miss even if an older root wrapping the same green node +/// were still alive. Weak references allow every workspace to determine the shared green node's lifetime without the +/// cache retaining any syntax tree. +/// +/// [ExportWorkspaceService(typeof(ISyntaxTreeCacheService), ServiceLayer.Host), Shared] internal sealed class SyntaxTreeCacheService : ISyntaxTreeCacheService { - // Accommodates several large solutions while placing a fixed upper bound on retained cache keys. - private const int DefaultMaximumEntryCount = 100_000; - private const int MinimumCleanupInterval = 256; + private const int DefaultCleanupInterval = 10_000; - private readonly ConcurrentDictionary> _roots = []; - private readonly int _maximumEntryCount; - private readonly int _cleanupInterval; + private readonly ConcurrentDictionary _entries = []; - private int _entryCount; - private int _publicationCount; - private int _admissionAttemptCount; + private int _addedRoots; private int _cleanupInProgress; - private int _lookupCount; - private int _hitCount; - private int _deadRootCount; - private int _publicationRaceCount; - private int _admissionBypassCount; - private int _cleanupCount; - private int _refreshCount; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SyntaxTreeCacheService() - : this(DefaultMaximumEntryCount) { } - internal SyntaxTreeCacheService(int maximumEntryCount) + public SyntaxTree GetOrCreateSyntaxTree( + SourceText text, + ParseOptions options, + Func parseSyntaxTree, + Func createSyntaxTreeFromRoot, + TArg arg, + CancellationToken cancellationToken) { - Contract.ThrowIfFalse(maximumEntryCount > 0); - _maximumEntryCount = maximumEntryCount; - _cleanupInterval = Math.Max(MinimumCleanupInterval, maximumEntryCount / 10); - } - - public SyntaxTreeCacheKey CreateKey(string language, SourceText text, ParseOptions options) - => new(language, Checksum.From(text.GetContentHash()), options); - - public bool TryGetRoot(SyntaxTreeCacheKey key, out SyntaxNode? root) - { - Interlocked.Increment(ref _lookupCount); - - if (_roots.TryGetValue(key, out var weakRoot) && - weakRoot.TryGetTarget(out root)) - { - Interlocked.Increment(ref _hitCount); - return true; - } - - if (weakRoot is not null) - { - Interlocked.Increment(ref _deadRootCount); - RemoveDeadEntry(key, weakRoot); - } - - root = null; - return false; - } - - public SyntaxNode GetOrAddRoot(SyntaxTreeCacheKey key, SyntaxNode root) - { - var newWeakRoot = new WeakReference(root); - + var key = new CacheKey(Checksum.From(text.GetContentHash()), options); while (true) { - if (_roots.TryGetValue(key, out var existingWeakRoot)) - { - if (existingWeakRoot.TryGetTarget(out var existingRoot)) - { - Interlocked.Increment(ref _publicationRaceCount); - return existingRoot; - } - - if (_roots.TryUpdate(key, newWeakRoot, existingWeakRoot)) - return root; + var entry = _entries.GetOrAdd(key, static _ => new()); + var tree = entry.TryGetOrCreateSyntaxTree( + parseSyntaxTree, createSyntaxTreeFromRoot, arg, cancellationToken, out var added); - continue; - } - - if (!TryReserveEntry()) + if (tree is null) { - Interlocked.Increment(ref _admissionBypassCount); - return root; + RemoveEntry(key, entry); + continue; } - if (_roots.TryAdd(key, newWeakRoot)) - { + if (added) CleanupIfNeeded(); - return root; - } - - Interlocked.Decrement(ref _entryCount); - } - } - - public void RefreshRoot(SyntaxTreeCacheKey key, SyntaxNode root) - { - var newWeakRoot = new WeakReference(root); - - while (_roots.TryGetValue(key, out var existingWeakRoot)) - { - if (_roots.TryUpdate(key, newWeakRoot, existingWeakRoot)) - { - Interlocked.Increment(ref _refreshCount); - return; - } - } - - _ = GetOrAddRoot(key, root); - } - - private bool TryReserveEntry() - { - while (true) - { - var entryCount = Volatile.Read(ref _entryCount); - if (entryCount >= _maximumEntryCount) - { - CleanupForAdmission(); - entryCount = Volatile.Read(ref _entryCount); - if (entryCount >= _maximumEntryCount) - return false; - } - if (Interlocked.CompareExchange(ref _entryCount, entryCount + 1, entryCount) == entryCount) - return true; + return tree; } } private void CleanupIfNeeded() { - if (Interlocked.Increment(ref _publicationCount) % _cleanupInterval == 0) - RemoveDeadEntries(); - } - - private void CleanupForAdmission() - { - var admissionAttemptCount = Interlocked.Increment(ref _admissionAttemptCount); - if (admissionAttemptCount == 1 || admissionAttemptCount % _cleanupInterval == 0) + if (Interlocked.Increment(ref _addedRoots) % DefaultCleanupInterval == 0) RemoveDeadEntries(); } @@ -161,12 +84,10 @@ private void RemoveDeadEntries() try { - Interlocked.Increment(ref _cleanupCount); - - foreach (var (key, weakRoot) in _roots) + foreach (var (key, entry) in _entries) { - if (!weakRoot.TryGetTarget(out _)) - RemoveDeadEntry(key, weakRoot); + if (entry.TryMarkRemovedIfEmpty()) + RemoveEntry(key, entry); } } finally @@ -175,27 +96,88 @@ private void RemoveDeadEntries() } } - private void RemoveDeadEntry(SyntaxTreeCacheKey key, WeakReference weakRoot) + private void RemoveEntry(CacheKey key, CacheEntry entry) + => ((ICollection>)_entries).Remove(new(key, entry)); + + internal TestAccessor GetTestAccessor() => new(this); + + internal readonly struct TestAccessor(SyntaxTreeCacheService service) { - if (((ICollection>>)_roots).Remove(new(key, weakRoot))) - Interlocked.Decrement(ref _entryCount); + public void TriggerCleanupOnNextAddedRoot() + => service._addedRoots = DefaultCleanupInterval - 1; } - internal int EntryCount - => Volatile.Read(ref _entryCount); - - internal TestAccessor GetTestAccessor() - => new(this); + private readonly record struct CacheKey(Checksum TextChecksum, ParseOptions Options); - internal readonly struct TestAccessor(SyntaxTreeCacheService service) + private sealed class CacheEntry { - public int EntryCount => Volatile.Read(ref service._entryCount); - public int LookupCount => Volatile.Read(ref service._lookupCount); - public int HitCount => Volatile.Read(ref service._hitCount); - public int DeadRootCount => Volatile.Read(ref service._deadRootCount); - public int PublicationRaceCount => Volatile.Read(ref service._publicationRaceCount); - public int AdmissionBypassCount => Volatile.Read(ref service._admissionBypassCount); - public int CleanupCount => Volatile.Read(ref service._cleanupCount); - public int RefreshCount => Volatile.Read(ref service._refreshCount); + private readonly object _gate = new(); + private readonly List> _roots = []; + private bool _removed; + + public SyntaxTree? TryGetOrCreateSyntaxTree( + Func parseSyntaxTree, + Func createSyntaxTreeFromRoot, + TArg arg, + CancellationToken cancellationToken, + out bool added) + { + lock (_gate) + { + added = false; + if (_removed) + return null; + + if (TryGetRootAndPruneDeadReferences(out var cachedRoot)) + { + var cachedTree = createSyntaxTreeFromRoot(cachedRoot, arg); + _roots.Add(new(cachedTree.GetRoot(cancellationToken))); + return cachedTree; + } + + var parsedTree = parseSyntaxTree(arg, cancellationToken); + _roots.Add(new(parsedTree.GetRoot(cancellationToken))); + added = true; + return parsedTree; + } + } + + public bool TryMarkRemovedIfEmpty() + { + lock (_gate) + { + if (_removed || TryGetRootAndPruneDeadReferences(out _)) + return false; + + _removed = true; + return true; + } + } + + /// + /// Removes dead references and returns any remaining live root. + /// + /// + /// when at least one live root remains; otherwise, . + /// + private bool TryGetRootAndPruneDeadReferences([NotNullWhen(true)] out SyntaxNode? root) + { + root = null; + + // Iterate backwards so removing an entry does not shift any indexes that remain to be inspected. + for (var i = _roots.Count - 1; i >= 0; i--) + { + if (_roots[i].TryGetTarget(out var candidate)) + { + root ??= candidate; + } + else + { + _roots.RemoveAt(i); + } + } + + return root is not null; + } } } diff --git a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/LspTestWorkspaces.cs b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/LspTestWorkspaces.cs index e2787a97b0c9..391aeaf62c38 100644 --- a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/LspTestWorkspaces.cs +++ b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/LspTestWorkspaces.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Text; - namespace Microsoft.CodeAnalysis.LanguageServer.Test.Utilities; internal static class LspTestWorkspaces @@ -21,14 +19,8 @@ public static LspWorkspaceContent SimpleProject .WithLoadPath("Project.csproj") .WithRestore(); - public static LspWorkspaceContent CreateConsoleApplication( - string projectName, - int sharedDocumentCount = 0, - int uniqueDocumentCount = 0, - int declarationsPerDocument = 1, - string? uniqueDocumentPrefix = null) - { - var content = LspWorkspaceContent.Empty + public static LspWorkspaceContent CreateConsoleApplication(string projectName) + => LspWorkspaceContent.Empty .WithFile($"{projectName}.csproj", """ @@ -42,32 +34,4 @@ public static LspWorkspaceContent CreateConsoleApplication( """) .WithLoadPath($"{projectName}.csproj") .WithRestore(); - - for (var i = 0; i < sharedDocumentCount; i++) - content = content.WithFile($"Shared{i:D4}.cs", CreateDocument("SharedWorkspace0", i, declarationsPerDocument)); - - for (var i = 0; i < uniqueDocumentCount; i++) - content = content.WithFile($"Unique{i:D4}.cs", CreateDocument(uniqueDocumentPrefix ?? projectName, i, declarationsPerDocument)); - - return content; - } - - private static string CreateDocument(string prefix, int documentIndex, int declarationsPerDocument) - { - var builder = new StringBuilder(); - builder.AppendLine("namespace BenchmarkDocuments;"); - - for (var declarationIndex = 0; declarationIndex < declarationsPerDocument; declarationIndex++) - { - builder.AppendLine($$""" - internal sealed class {{prefix}}Document{{documentIndex}}Type{{declarationIndex}} - { - public int Value { get; } = {{declarationIndex}}; - public string GetDescription() => "{{prefix}}-{{documentIndex}}-{{declarationIndex}}"; - } - """); - } - - return builder.ToString(); - } } diff --git a/src/Tools/IdeCoreBenchmarks/Program.cs b/src/Tools/IdeCoreBenchmarks/Program.cs index b70275ceea9c..db7bb715c608 100644 --- a/src/Tools/IdeCoreBenchmarks/Program.cs +++ b/src/Tools/IdeCoreBenchmarks/Program.cs @@ -43,14 +43,6 @@ public static string GetRoslynRootLocation([CallerFilePath] string sourceFilePat private static int Main(string[] args) { Environment.SetEnvironmentVariable(RoslynRootPathEnvVariableName, GetRoslynRootLocation()); -#if !NET472 - if (args is ["--retained-syntax-tree-cache-memory", var includeCache, var sharedDocumentCount]) - { - return LanguageServerDaemonBenchmarks.RunRetainedMemoryScenarioAsync( - bool.Parse(includeCache), int.Parse(sharedDocumentCount)).GetAwaiter().GetResult(); - } -#endif - // BenchmarkDotNet gives its generated runner a single output directory through global // MSBuild properties. If those properties flow into Roslyn's multi-targeted project graph, // different projects and target frameworks share output and intermediate paths, causing diff --git a/src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.cs b/src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.cs index 555d1611866f..3db99b30993f 100644 --- a/src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.cs +++ b/src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.cs @@ -20,7 +20,7 @@ internal sealed partial class CSharpSyntaxTreeFactoryService : AbstractSyntaxTre private static readonly CSharpParseOptions _parseOptionWithLatestLanguageVersion = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview); public CSharpSyntaxTreeFactoryService(ISyntaxTreeCacheService syntaxTreeCache) - : base(LanguageNames.CSharp, syntaxTreeCache) + : base(syntaxTreeCache) { } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/AbstractSyntaxTreeFactoryService.cs b/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/AbstractSyntaxTreeFactoryService.cs index 698265a1d38e..41f818bb39b0 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/AbstractSyntaxTreeFactoryService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/AbstractSyntaxTreeFactoryService.cs @@ -13,12 +13,10 @@ namespace Microsoft.CodeAnalysis.Host; internal abstract partial class AbstractSyntaxTreeFactoryService : ISyntaxTreeFactoryService { - private readonly string _language; private readonly ISyntaxTreeCacheService _syntaxTreeCache; - protected AbstractSyntaxTreeFactoryService(string language, ISyntaxTreeCacheService syntaxTreeCache) + protected AbstractSyntaxTreeFactoryService(ISyntaxTreeCacheService syntaxTreeCache) { - _language = language; _syntaxTreeCache = syntaxTreeCache; } @@ -35,24 +33,15 @@ public SyntaxTree ParseSyntaxTree(string filePath, ParseOptions options, SourceT if (_syntaxTreeCache is null) return ParseSyntaxTreeCore(filePath, options, text, cancellationToken); - var key = _syntaxTreeCache.CreateKey(_language, text, options); - if (_syntaxTreeCache.TryGetRoot(key, out var cachedRoot)) - { - var cachedTree = CreateSyntaxTree(filePath, options, text, text.Encoding, text.ChecksumAlgorithm, cachedRoot); - _syntaxTreeCache.RefreshRoot(key, cachedTree.GetRoot(cancellationToken)); - return cachedTree; - } - - var parsedTree = ParseSyntaxTreeCore(filePath, options, text, cancellationToken); - var parsedRoot = parsedTree.GetRoot(cancellationToken); - var canonicalRoot = _syntaxTreeCache.GetOrAddRoot(key, parsedRoot); - - if (canonicalRoot == parsedRoot) - return parsedTree; - - var raceTree = CreateSyntaxTree(filePath, options, text, text.Encoding, text.ChecksumAlgorithm, canonicalRoot); - _syntaxTreeCache.RefreshRoot(key, raceTree.GetRoot(cancellationToken)); - return raceTree; + return _syntaxTreeCache.GetOrCreateSyntaxTree( + text, + options, + static (state, cancellationToken) => state.service.ParseSyntaxTreeCore( + state.filePath, state.options, state.text, cancellationToken), + static (root, state) => state.service.CreateSyntaxTree( + state.filePath, state.options, state.text, state.text.Encoding, state.text.ChecksumAlgorithm, root), + (service: this, filePath, options, text), + cancellationToken); } protected abstract SyntaxTree ParseSyntaxTreeCore(string filePath, ParseOptions options, SourceText text, CancellationToken cancellationToken); diff --git a/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/ISyntaxTreeCacheService.cs b/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/ISyntaxTreeCacheService.cs index 6982bac76ae8..ed17707d19ba 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/ISyntaxTreeCacheService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/ISyntaxTreeCacheService.cs @@ -2,19 +2,19 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; +using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Host; -internal readonly record struct SyntaxTreeCacheKey(string Language, Checksum TextChecksum, ParseOptions Options); - internal interface ISyntaxTreeCacheService : IWorkspaceService { - SyntaxTreeCacheKey CreateKey(string language, SourceText text, ParseOptions options); - - bool TryGetRoot(SyntaxTreeCacheKey key, out SyntaxNode? root); - - SyntaxNode GetOrAddRoot(SyntaxTreeCacheKey key, SyntaxNode root); - - void RefreshRoot(SyntaxTreeCacheKey key, SyntaxNode root); + SyntaxTree GetOrCreateSyntaxTree( + SourceText text, + ParseOptions options, + Func parseSyntaxTree, + Func createSyntaxTreeFromRoot, + TArg arg, + CancellationToken cancellationToken); } diff --git a/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicSyntaxTreeFactoryService.vb b/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicSyntaxTreeFactoryService.vb index 4c96f7552b7d..f372fe8ac278 100644 --- a/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicSyntaxTreeFactoryService.vb +++ b/src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicSyntaxTreeFactoryService.vb @@ -16,7 +16,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Private Shared ReadOnly _parseOptionsWithLatestLanguageVersion As VisualBasicParseOptions = VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest) Public Sub New(syntaxTreeCache As ISyntaxTreeCacheService) - MyBase.New(LanguageNames.VisualBasic, syntaxTreeCache) + MyBase.New(syntaxTreeCache) End Sub Public Overloads Overrides Function GetDefaultParseOptions() As ParseOptions From b1c6b2e173cd89998b3724d9ad3632817c818383 Mon Sep 17 00:00:00 2001 From: David Barbet Date: Wed, 5 Aug 2026 16:22:53 -0700 Subject: [PATCH 3/5] Remove agent documentation changes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 1f56c314-c0d3-44d9-8630-c978f659a9ae --- .github/instructions/IDE.instructions.md | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/.github/instructions/IDE.instructions.md b/.github/instructions/IDE.instructions.md index 7bd8bdb4ce98..f6a1e030f6da 100644 --- a/.github/instructions/IDE.instructions.md +++ b/.github/instructions/IDE.instructions.md @@ -26,12 +26,6 @@ var csharpService = workspace.Services.GetLanguageServices(LanguageNames.CSharp) .GetRequiredService(); ``` -Syntax-tree creation flows through the language-specific `ISyntaxTreeFactoryService`. The C# and VB -implementations are language-service factories so they can consume the optional workspace-scoped -`ISyntaxTreeCacheService`. LanguageServer exports that cache at the Host layer to share immutable -syntax roots process-wide; cache hits still produce distinct `SyntaxTree` wrappers so document text, -paths, and identity remain workspace-specific. - ### MEF Export Patterns ```csharp // Workspace service (language-agnostic) @@ -42,14 +36,6 @@ internal class MyService : IMyService { } [ExportLanguageService(typeof(IMyService), LanguageNames.CSharp), Shared] internal class CSharpMyService : IMyService { } -// Language service requiring a workspace-scoped dependency -[ExportLanguageServiceFactory(typeof(IMyService), LanguageNames.CSharp), Shared] -internal class CSharpMyServiceFactory : ILanguageServiceFactory -{ - public ILanguageService CreateLanguageService(HostLanguageServices languageServices) - => new CSharpMyService(languageServices.WorkspaceServices.GetService()); -} - // Constructor — always include both attributes [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] From b9fb5d890956a79a7b41f30362b2c57a97ead44d Mon Sep 17 00:00:00 2001 From: David Barbet Date: Thu, 6 Aug 2026 11:25:14 -0700 Subject: [PATCH 4/5] skip cache in non-daemon mode --- .../SyntaxTreeCacheServiceTests.cs | 41 +++++++++++++++++-- .../HostWorkspace/SyntaxTreeCacheService.cs | 7 +++- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs index 498a30891e01..233313860280 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs @@ -83,6 +83,38 @@ public async Task DifferentParseOptionsDoNotShareGreenNodes() Assert.False(firstRoot.IsIncrementallyIdenticalTo(secondRoot)); } + [Fact] + public void NonDaemonBypassesCache() + { + using var workspace = CreateCacheWorkspace(out var cache, isDaemon: false); + var text = SourceText.From("class C { }"); + var options = CSharpParseOptions.Default; + var counts = new int[2]; + + SyntaxTree GetTree() + => cache.GetOrCreateSyntaxTree( + text, + options, + static (state, _) => + { + state.counts[0]++; + return CSharpSyntaxTree.ParseText(state.text, state.options); + }, + static (root, state) => + { + state.counts[1]++; + return CSharpSyntaxTree.Create((CSharpSyntaxNode)root, state.options); + }, + (text, options, counts), + CancellationToken.None); + + _ = GetTree(); + _ = GetTree(); + + Assert.Equal(2, counts[0]); + Assert.Equal(0, counts[1]); + } + [Fact] public async Task ConcurrentPublicationConvergesOnOneGreenRoot() { @@ -167,15 +199,16 @@ public void DifferentLanguagesDoNotShareGreenNodes() Assert.False(csharpRoot.IsIncrementallyIdenticalTo(visualBasicRoot)); } - private HostServices GetLanguageServerHostServices() + private HostServices GetLanguageServerHostServices(bool isDaemon = true) { - var exportProvider = LanguageServerTestComposition.GetSharedExportProvider(ServerConfigurationWithoutDevKit, LoggerFactory); + var serverConfiguration = ServerConfigurationWithoutDevKit with { IsDaemon = isDaemon }; + var exportProvider = LanguageServerTestComposition.GetSharedExportProvider(serverConfiguration, LoggerFactory); return exportProvider.GetExportedValue().HostServices; } - private AdhocWorkspace CreateCacheWorkspace(out SyntaxTreeCacheService cache) + private AdhocWorkspace CreateCacheWorkspace(out SyntaxTreeCacheService cache, bool isDaemon = true) { - var workspace = new AdhocWorkspace(GetLanguageServerHostServices(), WorkspaceKind.Host); + var workspace = new AdhocWorkspace(GetLanguageServerHostServices(isDaemon), WorkspaceKind.Host); cache = (SyntaxTreeCacheService)workspace.Services.GetRequiredService(); return workspace; } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs index f03634401b18..4dbd42507e4b 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs @@ -32,6 +32,7 @@ internal sealed class SyntaxTreeCacheService : ISyntaxTreeCacheService { private const int DefaultCleanupInterval = 10_000; + private readonly bool _isDaemon; private readonly ConcurrentDictionary _entries = []; private int _addedRoots; @@ -39,8 +40,9 @@ internal sealed class SyntaxTreeCacheService : ISyntaxTreeCacheService [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public SyntaxTreeCacheService() + public SyntaxTreeCacheService(ServerConfiguration serverConfiguration) { + _isDaemon = serverConfiguration.IsDaemon; } public SyntaxTree GetOrCreateSyntaxTree( @@ -51,6 +53,9 @@ public SyntaxTree GetOrCreateSyntaxTree( TArg arg, CancellationToken cancellationToken) { + if (!_isDaemon) + return parseSyntaxTree(arg, cancellationToken); + var key = new CacheKey(Checksum.From(text.GetContentHash()), options); while (true) { From 67f1bf0d4b082342e899c1e12122e5530c9098ab Mon Sep 17 00:00:00 2001 From: David Barbet Date: Fri, 7 Aug 2026 13:04:55 -0700 Subject: [PATCH 5/5] feedbacl --- .../SyntaxTreeCacheServiceTests.cs | 126 ++++++++---------- .../HostWorkspace/SyntaxTreeCacheService.cs | 73 +++++----- .../CSharpSyntaxTreeFactoryServiceTests.cs | 29 ---- 3 files changed, 95 insertions(+), 133 deletions(-) delete mode 100644 src/Workspaces/CSharpTest/CSharpSyntaxTreeFactoryServiceTests.cs diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs index 233313860280..640eec583242 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs @@ -3,11 +3,14 @@ // See the LICENSE file in the project root for more information. using System.Text; +using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; +using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; +using Microsoft.VisualStudio.Composition; using Roslyn.Test.Utilities; using Xunit.Abstractions; @@ -16,23 +19,28 @@ namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.HostWorkspace; public sealed class SyntaxTreeCacheServiceTests(ITestOutputHelper testOutputHelper) : AbstractLanguageServerHostTests(testOutputHelper) { + private static readonly TestComposition s_composition = FeaturesTestCompositions.Features.AddParts( + typeof(ServerConfigurationFactory), + typeof(SyntaxTreeCacheServiceFactory)); + [Theory] [InlineData(LanguageNames.CSharp, "class C { }", "first.cs", "second.cs")] + [InlineData(LanguageNames.VisualBasic, "Class C\nEnd Class", "first.vb", "second.vb")] public async Task IdenticalDocumentsInDifferentWorkspacesShareGreenNodes( string language, string source, string firstPath, string secondPath) { - var hostServices = GetLanguageServerHostServices(); - using var firstWorkspace = new AdhocWorkspace(hostServices, WorkspaceKind.Host); - using var secondWorkspace = new AdhocWorkspace(hostServices, WorkspaceKind.Host); + var exportProvider = GetLanguageServerExportProvider(); + var firstText = SourceText.From(source, Encoding.UTF8, SourceHashAlgorithm.Sha1); + var secondText = SourceText.From(source, Encoding.Unicode, SourceHashAlgorithm.Sha256); + using var firstWorkspace = await CreateWorkspaceAsync(exportProvider, language, firstText, firstPath); + using var secondWorkspace = await CreateWorkspaceAsync(exportProvider, language, secondText, secondPath); Assert.Same( firstWorkspace.Services.GetRequiredService(), secondWorkspace.Services.GetRequiredService()); - var firstText = SourceText.From(source, Encoding.UTF8, SourceHashAlgorithm.Sha1); - var secondText = SourceText.From(source, Encoding.Unicode, SourceHashAlgorithm.Sha256); - var firstDocument = AddDocument(firstWorkspace, language, firstText, firstPath); - var secondDocument = AddDocument(secondWorkspace, language, secondText, secondPath); + var firstDocument = firstWorkspace.CurrentSolution.Projects.Single().Documents.Single(); + var secondDocument = secondWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var firstTree = await firstDocument.GetSyntaxTreeAsync(CancellationToken.None); var secondTree = await secondDocument.GetSyntaxTreeAsync(CancellationToken.None); @@ -46,6 +54,8 @@ public async Task IdenticalDocumentsInDifferentWorkspacesShareGreenNodes( Assert.True(firstRoot.IsIncrementallyIdenticalTo(secondRoot)); Assert.Equal(firstPath, firstTree.FilePath); Assert.Equal(secondPath, secondTree.FilePath); + Assert.Same(Encoding.UTF8, firstTree.Encoding); + Assert.Same(Encoding.Unicode, secondTree.Encoding); Assert.Same(firstText, firstTree.GetText()); Assert.Same(secondText, secondTree.GetText()); Assert.NotEqual(firstDocument.Id, secondDocument.Id); @@ -62,16 +72,15 @@ public async Task IdenticalDocumentsInDifferentWorkspacesShareGreenNodes( public async Task DifferentParseOptionsDoNotShareGreenNodes() { const string source = "class C { }"; - var hostServices = GetLanguageServerHostServices(); - using var firstWorkspace = new AdhocWorkspace(hostServices, WorkspaceKind.Host); - using var secondWorkspace = new AdhocWorkspace(hostServices, WorkspaceKind.Host); - - var firstDocument = AddDocument( - firstWorkspace, LanguageNames.CSharp, SourceText.From(source), "first.cs", + var exportProvider = GetLanguageServerExportProvider(); + using var firstWorkspace = await CreateWorkspaceAsync( + exportProvider, LanguageNames.CSharp, SourceText.From(source), "first.cs", CSharpParseOptions.Default.WithPreprocessorSymbols("FIRST")); - var secondDocument = AddDocument( - secondWorkspace, LanguageNames.CSharp, SourceText.From(source), "second.cs", + using var secondWorkspace = await CreateWorkspaceAsync( + exportProvider, LanguageNames.CSharp, SourceText.From(source), "second.cs", CSharpParseOptions.Default.WithPreprocessorSymbols("SECOND")); + var firstDocument = firstWorkspace.CurrentSolution.Projects.Single().Documents.Single(); + var secondDocument = secondWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var firstTree = await firstDocument.GetSyntaxTreeAsync(CancellationToken.None); var secondTree = await secondDocument.GetSyntaxTreeAsync(CancellationToken.None); @@ -80,39 +89,15 @@ public async Task DifferentParseOptionsDoNotShareGreenNodes() var firstRoot = await firstTree.GetRootAsync(CancellationToken.None); var secondRoot = await secondTree.GetRootAsync(CancellationToken.None); + // This could eventually share trees when the differing parse options do not affect the parsed result. Assert.False(firstRoot.IsIncrementallyIdenticalTo(secondRoot)); } [Fact] - public void NonDaemonBypassesCache() + public void NonDaemonDoesNotProvideCache() { - using var workspace = CreateCacheWorkspace(out var cache, isDaemon: false); - var text = SourceText.From("class C { }"); - var options = CSharpParseOptions.Default; - var counts = new int[2]; - - SyntaxTree GetTree() - => cache.GetOrCreateSyntaxTree( - text, - options, - static (state, _) => - { - state.counts[0]++; - return CSharpSyntaxTree.ParseText(state.text, state.options); - }, - static (root, state) => - { - state.counts[1]++; - return CSharpSyntaxTree.Create((CSharpSyntaxNode)root, state.options); - }, - (text, options, counts), - CancellationToken.None); - - _ = GetTree(); - _ = GetTree(); - - Assert.Equal(2, counts[0]); - Assert.Equal(0, counts[1]); + using var workspace = new TestWorkspace(GetLanguageServerExportProvider(isDaemon: false), WorkspaceKind.Host); + Assert.Null(workspace.Services.GetService()); } [Fact] @@ -123,7 +108,7 @@ public async Task ConcurrentPublicationConvergesOnOneGreenRoot() var trees = await Task.WhenAll( Enumerable.Range(0, 16).Select(_ => Task.Run( - () => GetOrCreateTree(cache, text)))); + () => GetOrCreateCSharpTree(cache, text)))); var canonicalRoot = trees[0].GetRoot(); Assert.All(trees, tree => Assert.True(canonicalRoot.IsIncrementallyIdenticalTo(tree.GetRoot()))); @@ -134,12 +119,12 @@ public void OlderLiveRootRemainsAvailableAfterNewerRootIsCollected() { using var workspace = CreateCacheWorkspace(out var cache); var text = SourceText.From("class C { }"); - var firstTree = GetOrCreateTree(cache, text); + var firstTree = GetOrCreateCSharpTree(cache, text); var firstRoot = firstTree.GetRoot(); var secondRootReference = ObjectReference.CreateFromFactory( static state => { - var root = GetOrCreateTree(state.cache, state.text).GetRoot(); + var root = GetOrCreateCSharpTree(state.cache, state.text).GetRoot(); Assert.True(state.expectedSharedRoot.IsIncrementallyIdenticalTo(root)); return root; }, @@ -147,7 +132,7 @@ public void OlderLiveRootRemainsAvailableAfterNewerRootIsCollected() secondRootReference.AssertReleased(); - var thirdRoot = GetOrCreateTree(cache, text).GetRoot(); + var thirdRoot = GetOrCreateCSharpTree(cache, text).GetRoot(); Assert.True(firstRoot.IsIncrementallyIdenticalTo(thirdRoot)); } @@ -161,14 +146,14 @@ public void PeriodicCleanupReleasesDeadKeys() // The cache key strongly retains these unique options, so their lifetime lets this test observe // whether periodic cleanup removed the entry after its weak roots died. var options = CSharpParseOptions.Default.WithPreprocessorSymbols(Guid.NewGuid().ToString()); - _ = GetOrCreateTree(state.cache, state.text, options); + _ = GetOrCreateCSharpTree(state.cache, state.text, options); return options; }, (cache, text: SourceText.From("class First { }"))); firstOptionsReference.AssertHeld(); cache.GetTestAccessor().TriggerCleanupOnNextAddedRoot(); - _ = GetOrCreateTree(cache, SourceText.From("class Second { }")); + _ = GetOrCreateCSharpTree(cache, SourceText.From("class Second { }")); firstOptionsReference.AssertReleased(); } @@ -179,12 +164,12 @@ public void DeadEntryIsReplaced() using var workspace = CreateCacheWorkspace(out var cache); var text = SourceText.From("class C { }"); var rootReference = ObjectReference.CreateFromFactory( - static state => GetOrCreateTree(state.cache, state.text).GetRoot(), + static state => GetOrCreateCSharpTree(state.cache, state.text).GetRoot(), (cache, text)); rootReference.AssertReleased(); - var replacementRoot = GetOrCreateTree(cache, text).GetRoot(); - var cachedReplacementRoot = GetOrCreateTree(cache, text).GetRoot(); + var replacementRoot = GetOrCreateCSharpTree(cache, text).GetRoot(); + var cachedReplacementRoot = GetOrCreateCSharpTree(cache, text).GetRoot(); Assert.True(replacementRoot.IsIncrementallyIdenticalTo(cachedReplacementRoot)); } @@ -193,48 +178,55 @@ public void DifferentLanguagesDoNotShareGreenNodes() { using var workspace = CreateCacheWorkspace(out var cache); var text = SourceText.From("class C { }"); - var csharpRoot = GetOrCreateTree(cache, text).GetRoot(); - var visualBasicRoot = GetOrCreateVisualBasicTree(cache, text).GetRoot(); + var csharpTree = GetOrCreateCSharpTree(cache, text); + var visualBasicTree = GetOrCreateVisualBasicTree(cache, text); - Assert.False(csharpRoot.IsIncrementallyIdenticalTo(visualBasicRoot)); + Assert.NotEqual(csharpTree.GetType(), visualBasicTree.GetType()); + Assert.False(csharpTree.GetRoot().IsIncrementallyIdenticalTo(visualBasicTree.GetRoot())); } - private HostServices GetLanguageServerHostServices(bool isDaemon = true) + private ExportProvider GetLanguageServerExportProvider(bool isDaemon = true) { var serverConfiguration = ServerConfigurationWithoutDevKit with { IsDaemon = isDaemon }; - var exportProvider = LanguageServerTestComposition.GetSharedExportProvider(serverConfiguration, LoggerFactory); - return exportProvider.GetExportedValue().HostServices; + var exportProvider = s_composition.ExportProviderFactory.CreateExportProvider(); + exportProvider.GetExportedValue().InitializeConfiguration(serverConfiguration); + return exportProvider; } - private AdhocWorkspace CreateCacheWorkspace(out SyntaxTreeCacheService cache, bool isDaemon = true) + private TestWorkspace CreateCacheWorkspace(out SyntaxTreeCacheService cache) { - var workspace = new AdhocWorkspace(GetLanguageServerHostServices(isDaemon), WorkspaceKind.Host); + var workspace = new TestWorkspace(GetLanguageServerExportProvider(), WorkspaceKind.Host); cache = (SyntaxTreeCacheService)workspace.Services.GetRequiredService(); return workspace; } - private static Document AddDocument( - AdhocWorkspace workspace, + private static async Task CreateWorkspaceAsync( + ExportProvider exportProvider, string language, SourceText text, string filePath, ParseOptions? parseOptions = null) { - var project = workspace.AddProject(Guid.NewGuid().ToString(), language); + var workspace = TestWorkspace.Create( + new XElement("Workspace", + new XElement("Project", new XAttribute("Language", language))), + exportProvider, + workspaceKind: WorkspaceKind.Host); + + var project = workspace.CurrentSolution.Projects.Single(); if (parseOptions is not null) { Assert.True(workspace.TryApplyChanges(project.Solution.WithProjectParseOptions(project.Id, parseOptions))); - project = workspace.CurrentSolution.GetProject(project.Id); - Assert.NotNull(project); } var documentId = DocumentId.CreateNewId(project.Id); var loader = TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create(), filePath)); - return workspace.AddDocument(DocumentInfo.Create( + await workspace.AddDocumentAsync(DocumentInfo.Create( documentId, Path.GetFileName(filePath), loader: loader, filePath: filePath)); + return workspace; } - private static SyntaxTree GetOrCreateTree( + private static SyntaxTree GetOrCreateCSharpTree( SyntaxTreeCacheService cache, SourceText text, CSharpParseOptions? options = null) diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs index 4dbd42507e4b..9d62f80bda72 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs @@ -4,10 +4,10 @@ using System.Collections.Concurrent; using System.Composition; -using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; @@ -27,23 +27,16 @@ namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace; /// cache retaining any syntax tree. /// /// -[ExportWorkspaceService(typeof(ISyntaxTreeCacheService), ServiceLayer.Host), Shared] internal sealed class SyntaxTreeCacheService : ISyntaxTreeCacheService { + /// + /// An arbitrary initial threshold that can be tuned based on observed cache behavior. + /// private const int DefaultCleanupInterval = 10_000; - private readonly bool _isDaemon; private readonly ConcurrentDictionary _entries = []; private int _addedRoots; - private int _cleanupInProgress; - - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public SyntaxTreeCacheService(ServerConfiguration serverConfiguration) - { - _isDaemon = serverConfiguration.IsDaemon; - } public SyntaxTree GetOrCreateSyntaxTree( SourceText text, @@ -53,9 +46,6 @@ public SyntaxTree GetOrCreateSyntaxTree( TArg arg, CancellationToken cancellationToken) { - if (!_isDaemon) - return parseSyntaxTree(arg, cancellationToken); - var key = new CacheKey(Checksum.From(text.GetContentHash()), options); while (true) { @@ -65,7 +55,7 @@ public SyntaxTree GetOrCreateSyntaxTree( if (tree is null) { - RemoveEntry(key, entry); + _entries.TryRemove(new(key, entry)); continue; } @@ -84,26 +74,13 @@ private void CleanupIfNeeded() private void RemoveDeadEntries() { - if (Interlocked.CompareExchange(ref _cleanupInProgress, 1, 0) != 0) - return; - - try - { - foreach (var (key, entry) in _entries) - { - if (entry.TryMarkRemovedIfEmpty()) - RemoveEntry(key, entry); - } - } - finally + foreach (var (key, entry) in _entries) { - Volatile.Write(ref _cleanupInProgress, 0); + if (entry.TryMarkRemovedIfEmpty()) + _entries.TryRemove(new(key, entry)); } } - private void RemoveEntry(CacheKey key, CacheEntry entry) - => ((ICollection>)_entries).Remove(new(key, entry)); - internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor(SyntaxTreeCacheService service) @@ -133,10 +110,11 @@ private sealed class CacheEntry if (_removed) return null; - if (TryGetRootAndPruneDeadReferences(out var cachedRoot)) + if (GetRootAndPruneDeadReferences() is { } cachedRoot) { var cachedTree = createSyntaxTreeFromRoot(cachedRoot, arg); _roots.Add(new(cachedTree.GetRoot(cancellationToken))); + // Do not set added: cleanup is based on cache growth, not additional users of an existing entry. return cachedTree; } @@ -151,7 +129,7 @@ public bool TryMarkRemovedIfEmpty() { lock (_gate) { - if (_removed || TryGetRootAndPruneDeadReferences(out _)) + if (_removed || GetRootAndPruneDeadReferences() is not null) return false; _removed = true; @@ -163,11 +141,13 @@ public bool TryMarkRemovedIfEmpty() /// Removes dead references and returns any remaining live root. /// /// - /// when at least one live root remains; otherwise, . + /// A remaining live root, or when all references are dead. /// - private bool TryGetRootAndPruneDeadReferences([NotNullWhen(true)] out SyntaxNode? root) + private SyntaxNode? GetRootAndPruneDeadReferences() { - root = null; + Contract.ThrowIfFalse(Monitor.IsEntered(_gate)); + + SyntaxNode? root = null; // Iterate backwards so removing an entry does not shift any indexes that remain to be inspected. for (var i = _roots.Count - 1; i >= 0; i--) @@ -182,7 +162,26 @@ private bool TryGetRootAndPruneDeadReferences([NotNullWhen(true)] out SyntaxNode } } - return root is not null; + return root; } } } + +[ExportWorkspaceServiceFactory(typeof(ISyntaxTreeCacheService), ServiceLayer.Host), Shared] +internal sealed class SyntaxTreeCacheServiceFactory : IWorkspaceServiceFactory +{ + private readonly SyntaxTreeCacheService? _service; + + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public SyntaxTreeCacheServiceFactory(ServerConfiguration serverConfiguration) + { + if (serverConfiguration.IsDaemon) + _service = new(); + } + + // Although the return type is non-nullable, IWorkspaceServiceFactory explicitly permits null when the service + // is not applicable to the workspace. + public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) + => _service!; +} diff --git a/src/Workspaces/CSharpTest/CSharpSyntaxTreeFactoryServiceTests.cs b/src/Workspaces/CSharpTest/CSharpSyntaxTreeFactoryServiceTests.cs deleted file mode 100644 index 281956b277ff..000000000000 --- a/src/Workspaces/CSharpTest/CSharpSyntaxTreeFactoryServiceTests.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Threading; -using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Test.Utilities; -using Microsoft.CodeAnalysis.Text; -using Xunit; - -namespace Microsoft.CodeAnalysis.CSharp.UnitTests; - -[UseExportProvider] -public sealed class CSharpSyntaxTreeFactoryServiceTests -{ - [Fact] - public void LanguageServiceFactoryCreatesSyntaxTreesWithoutCache() - { - using var workspace = new AdhocWorkspace(); - var service = workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(); - var text = SourceText.From("class C { }"); - - var tree = service.ParseSyntaxTree("test.cs", CSharpParseOptions.Default, text, CancellationToken.None); - - Assert.Equal("test.cs", tree.FilePath); - Assert.Same(text, tree.GetText()); - Assert.IsType(tree.GetRoot()); - } -}