Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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<LanguageServerWorkspaceFactory>();
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<LanguageServerWorkspaceFactory>();
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<LanguageServerWorkspaceFactory>(),
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.
Expand Down Expand Up @@ -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();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
// 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 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;

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)
Comment thread
dibarbet marked this conversation as resolved.
Resolved
{
var hostServices = GetLanguageServerHostServices();
using var firstWorkspace = new AdhocWorkspace(hostServices, WorkspaceKind.Host);
using var secondWorkspace = new AdhocWorkspace(hostServices, WorkspaceKind.Host);

Assert.Same(
firstWorkspace.Services.GetRequiredService<ISyntaxTreeCacheService>(),
secondWorkspace.Services.GetRequiredService<ISyntaxTreeCacheService>());

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);
Comment thread
dibarbet marked this conversation as resolved.
Resolved
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));
Comment thread
dibarbet marked this conversation as resolved.
Resolved
}

[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];
Comment thread
dibarbet marked this conversation as resolved.
Resolved

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()
{
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(
() => GetOrCreateTree(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 = 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 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());
_ = 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 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(),
(cache, text));
rootReference.AssertReleased();

var replacementRoot = GetOrCreateTree(cache, text).GetRoot();
var cachedReplacementRoot = GetOrCreateTree(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 csharpRoot = GetOrCreateTree(cache, text).GetRoot();
var visualBasicRoot = GetOrCreateVisualBasicTree(cache, text).GetRoot();
Comment thread
dibarbet marked this conversation as resolved.
Resolved

Assert.False(csharpRoot.IsIncrementallyIdenticalTo(visualBasicRoot));
}

private HostServices GetLanguageServerHostServices(bool isDaemon = true)
{
var serverConfiguration = ServerConfigurationWithoutDevKit with { IsDaemon = isDaemon };
var exportProvider = LanguageServerTestComposition.GetSharedExportProvider(serverConfiguration, LoggerFactory);
return exportProvider.GetExportedValue<HostServicesProvider>().HostServices;
}

private AdhocWorkspace CreateCacheWorkspace(out SyntaxTreeCacheService cache, bool isDaemon = true)
{
var workspace = new AdhocWorkspace(GetLanguageServerHostServices(isDaemon), WorkspaceKind.Host);
cache = (SyntaxTreeCacheService)workspace.Services.GetRequiredService<ISyntaxTreeCacheService>();
return workspace;
}

private static Document AddDocument(
AdhocWorkspace workspace,
string language,
SourceText text,
string filePath,
ParseOptions? parseOptions = null)
{
Comment thread
dibarbet marked this conversation as resolved.
Resolved
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));
}

private static SyntaxTree GetOrCreateTree(
Comment thread
dibarbet marked this conversation as resolved.
Resolved
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);
}

}
Loading
Loading