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..640eec583242 --- /dev/null +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/HostWorkspace/SyntaxTreeCacheServiceTests.cs @@ -0,0 +1,259 @@ +// 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.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; + +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 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 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); + 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(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); + + 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 exportProvider = GetLanguageServerExportProvider(); + using var firstWorkspace = await CreateWorkspaceAsync( + exportProvider, LanguageNames.CSharp, SourceText.From(source), "first.cs", + CSharpParseOptions.Default.WithPreprocessorSymbols("FIRST")); + 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); + Assert.NotNull(firstTree); + Assert.NotNull(secondTree); + 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 NonDaemonDoesNotProvideCache() + { + using var workspace = new TestWorkspace(GetLanguageServerExportProvider(isDaemon: false), WorkspaceKind.Host); + Assert.Null(workspace.Services.GetService()); + } + + [Fact] + public async Task ConcurrentPublicationConvergesOnOneGreenRoot() + { + using var workspace = CreateCacheWorkspace(out var cache); + var text = SourceText.From("class C { }"); + + var trees = await Task.WhenAll( + Enumerable.Range(0, 16).Select(_ => Task.Run( + () => GetOrCreateCSharpTree(cache, text)))); + + var canonicalRoot = trees[0].GetRoot(); + Assert.All(trees, tree => Assert.True(canonicalRoot.IsIncrementallyIdenticalTo(tree.GetRoot()))); + } + + [Fact] + public void OlderLiveRootRemainsAvailableAfterNewerRootIsCollected() + { + using var workspace = CreateCacheWorkspace(out var cache); + var text = SourceText.From("class C { }"); + var firstTree = GetOrCreateCSharpTree(cache, text); + var firstRoot = firstTree.GetRoot(); + var secondRootReference = ObjectReference.CreateFromFactory( + static state => + { + var root = GetOrCreateCSharpTree(state.cache, state.text).GetRoot(); + Assert.True(state.expectedSharedRoot.IsIncrementallyIdenticalTo(root)); + return root; + }, + (cache, text, expectedSharedRoot: firstRoot)); + + secondRootReference.AssertReleased(); + + var thirdRoot = GetOrCreateCSharpTree(cache, text).GetRoot(); + Assert.True(firstRoot.IsIncrementallyIdenticalTo(thirdRoot)); + } + + [Fact] + public void PeriodicCleanupReleasesDeadKeys() + { + 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()); + _ = GetOrCreateCSharpTree(state.cache, state.text, options); + return options; + }, + (cache, text: SourceText.From("class First { }"))); + firstOptionsReference.AssertHeld(); + + cache.GetTestAccessor().TriggerCleanupOnNextAddedRoot(); + _ = GetOrCreateCSharpTree(cache, SourceText.From("class Second { }")); + + firstOptionsReference.AssertReleased(); + } + + [Fact] + public void DeadEntryIsReplaced() + { + using var workspace = CreateCacheWorkspace(out var cache); + var text = SourceText.From("class C { }"); + var rootReference = ObjectReference.CreateFromFactory( + static state => GetOrCreateCSharpTree(state.cache, state.text).GetRoot(), + (cache, text)); + rootReference.AssertReleased(); + + var replacementRoot = GetOrCreateCSharpTree(cache, text).GetRoot(); + var cachedReplacementRoot = GetOrCreateCSharpTree(cache, text).GetRoot(); + Assert.True(replacementRoot.IsIncrementallyIdenticalTo(cachedReplacementRoot)); + } + + [Fact] + public void DifferentLanguagesDoNotShareGreenNodes() + { + using var workspace = CreateCacheWorkspace(out var cache); + var text = SourceText.From("class C { }"); + var csharpTree = GetOrCreateCSharpTree(cache, text); + var visualBasicTree = GetOrCreateVisualBasicTree(cache, text); + + Assert.NotEqual(csharpTree.GetType(), visualBasicTree.GetType()); + Assert.False(csharpTree.GetRoot().IsIncrementallyIdenticalTo(visualBasicTree.GetRoot())); + } + + private ExportProvider GetLanguageServerExportProvider(bool isDaemon = true) + { + var serverConfiguration = ServerConfigurationWithoutDevKit with { IsDaemon = isDaemon }; + var exportProvider = s_composition.ExportProviderFactory.CreateExportProvider(); + exportProvider.GetExportedValue().InitializeConfiguration(serverConfiguration); + return exportProvider; + } + + private TestWorkspace CreateCacheWorkspace(out SyntaxTreeCacheService cache) + { + var workspace = new TestWorkspace(GetLanguageServerExportProvider(), WorkspaceKind.Host); + cache = (SyntaxTreeCacheService)workspace.Services.GetRequiredService(); + return workspace; + } + + private static async Task CreateWorkspaceAsync( + ExportProvider exportProvider, + string language, + SourceText text, + string filePath, + ParseOptions? parseOptions = null) + { + 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))); + } + + var documentId = DocumentId.CreateNewId(project.Id); + var loader = TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create(), filePath)); + await workspace.AddDocumentAsync(DocumentInfo.Create( + documentId, Path.GetFileName(filePath), loader: loader, filePath: filePath)); + return workspace; + } + + private static SyntaxTree GetOrCreateCSharpTree( + SyntaxTreeCacheService cache, + SourceText text, + CSharpParseOptions? options = null) + { + 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 SyntaxTree GetOrCreateVisualBasicTree( + SyntaxTreeCacheService cache, + SourceText text, + VisualBasicParseOptions? options = null) + { + 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/HostWorkspace/SyntaxTreeCacheService.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs new file mode 100644 index 000000000000..9d62f80bda72 --- /dev/null +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/SyntaxTreeCacheService.cs @@ -0,0 +1,187 @@ +// 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; +using Roslyn.Utilities; + +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. +/// +/// +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 ConcurrentDictionary _entries = []; + + private int _addedRoots; + + public SyntaxTree GetOrCreateSyntaxTree( + SourceText text, + ParseOptions options, + Func parseSyntaxTree, + Func createSyntaxTreeFromRoot, + TArg arg, + CancellationToken cancellationToken) + { + var key = new CacheKey(Checksum.From(text.GetContentHash()), options); + while (true) + { + var entry = _entries.GetOrAdd(key, static _ => new()); + var tree = entry.TryGetOrCreateSyntaxTree( + parseSyntaxTree, createSyntaxTreeFromRoot, arg, cancellationToken, out var added); + + if (tree is null) + { + _entries.TryRemove(new(key, entry)); + continue; + } + + if (added) + CleanupIfNeeded(); + + return tree; + } + } + + private void CleanupIfNeeded() + { + if (Interlocked.Increment(ref _addedRoots) % DefaultCleanupInterval == 0) + RemoveDeadEntries(); + } + + private void RemoveDeadEntries() + { + foreach (var (key, entry) in _entries) + { + if (entry.TryMarkRemovedIfEmpty()) + _entries.TryRemove(new(key, entry)); + } + } + + internal TestAccessor GetTestAccessor() => new(this); + + internal readonly struct TestAccessor(SyntaxTreeCacheService service) + { + public void TriggerCleanupOnNextAddedRoot() + => service._addedRoots = DefaultCleanupInterval - 1; + } + + private readonly record struct CacheKey(Checksum TextChecksum, ParseOptions Options); + + private sealed class CacheEntry + { + 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 (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; + } + + var parsedTree = parseSyntaxTree(arg, cancellationToken); + _roots.Add(new(parsedTree.GetRoot(cancellationToken))); + added = true; + return parsedTree; + } + } + + public bool TryMarkRemovedIfEmpty() + { + lock (_gate) + { + if (_removed || GetRootAndPruneDeadReferences() is not null) + return false; + + _removed = true; + return true; + } + } + + /// + /// Removes dead references and returns any remaining live root. + /// + /// + /// A remaining live root, or when all references are dead. + /// + private SyntaxNode? GetRootAndPruneDeadReferences() + { + 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--) + { + if (_roots[i].TryGetTarget(out var candidate)) + { + root ??= candidate; + } + else + { + _roots.RemoveAt(i); + } + } + + 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/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.cs b/src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.cs index 96c310b912ae..3db99b30993f 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(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/Core/Portable/Workspace/Host/SyntaxTreeFactory/AbstractSyntaxTreeFactoryService.cs b/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/AbstractSyntaxTreeFactoryService.cs index 94c103435fb2..41f818bb39b0 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/AbstractSyntaxTreeFactoryService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/AbstractSyntaxTreeFactoryService.cs @@ -13,10 +13,36 @@ namespace Microsoft.CodeAnalysis.Host; internal abstract partial class AbstractSyntaxTreeFactoryService : ISyntaxTreeFactoryService { + private readonly ISyntaxTreeCacheService _syntaxTreeCache; + + protected AbstractSyntaxTreeFactoryService(ISyntaxTreeCacheService syntaxTreeCache) + { + _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); + + 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 new file mode 100644 index 000000000000..ed17707d19ba --- /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 System; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Host; + +internal interface ISyntaxTreeCacheService : IWorkspaceService +{ + 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 0535d17e0539..f372fe8ac278 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(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