Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch Roslyn protocol types to System.Text.Json serialization #73207

Merged
merged 5 commits into from
May 15, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
Expand All @@ -19,8 +20,6 @@
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.Threading;
using Nerdbank.Streams;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Roslyn.LanguageServer.Protocol;
using StreamJsonRpc;

Expand Down Expand Up @@ -200,10 +199,9 @@ public Task OnServerInitializedAsync()
ILspServiceLoggerFactory lspLoggerFactory,
CancellationToken cancellationToken)
{
var jsonMessageFormatter = new JsonMessageFormatter();
VSInternalExtensionUtilities.AddVSInternalExtensionConverters(jsonMessageFormatter.JsonSerializer);
var messageFormatter = RoslynLanguageServer.CreateJsonMessageFormatter();

var jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream, jsonMessageFormatter))
var jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream, messageFormatter))
{
ExceptionStrategy = ExceptionProcessing.ISerializable,
};
Expand All @@ -215,7 +213,7 @@ public Task OnServerInitializedAsync()
var hostServices = VisualStudioMefHostServices.Create(_exportProvider);
var server = Create(
jsonRpc,
jsonMessageFormatter.JsonSerializer,
messageFormatter.JsonSerializerOptions,
languageClient,
serverKind,
logger,
Expand All @@ -227,7 +225,7 @@ public Task OnServerInitializedAsync()

public virtual AbstractLanguageServer<RequestContext> Create(
JsonRpc jsonRpc,
JsonSerializer jsonSerializer,
JsonSerializerOptions options,
ICapabilitiesProvider capabilitiesProvider,
WellKnownLspServerKinds serverKind,
AbstractLspLogger logger,
Expand All @@ -236,7 +234,7 @@ public Task OnServerInitializedAsync()
var server = new RoslynLanguageServer(
LspServiceProvider,
jsonRpc,
jsonSerializer,
options,
capabilitiesProvider,
logger,
hostServices,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -26,13 +28,11 @@
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CommonLanguageServerProtocol.Framework;
using Nerdbank.Streams;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Roslyn.LanguageServer.Protocol;
using Roslyn.Utilities;
using StreamJsonRpc;
using Xunit;
Expand All @@ -44,6 +44,8 @@ namespace Roslyn.Test.Utilities
[UseExportProvider]
public abstract partial class AbstractLanguageServerProtocolTests
{
private static readonly SystemTextJsonFormatter s_messageFormatter = RoslynLanguageServer.CreateJsonMessageFormatter();

private protected readonly AbstractLspLogger TestOutputLspLogger;
protected AbstractLanguageServerProtocolTests(ITestOutputHelper? testOutputHelper)
{
Expand Down Expand Up @@ -124,8 +126,8 @@ private protected static LSP.ClientCapabilities GetCapabilities(bool isVS)
/// <param name="actual">the actual object to be converted to JSON.</param>
public static void AssertJsonEquals<T1, T2>(T1 expected, T2 actual)
{
var expectedStr = JsonConvert.SerializeObject(expected);
var actualStr = JsonConvert.SerializeObject(actual);
var expectedStr = JsonSerializer.Serialize(expected, s_messageFormatter.JsonSerializerOptions);
var actualStr = JsonSerializer.Serialize(actual, s_messageFormatter.JsonSerializerOptions);
AssertEqualIgnoringWhitespace(expectedStr, actualStr);
}

Expand Down Expand Up @@ -269,7 +271,7 @@ private protected static LSP.MarkupContent CreateMarkupContent(LSP.MarkupKind ki
SortText = sortText,
InsertTextFormat = LSP.InsertTextFormat.Plaintext,
Kind = kind,
Data = JObject.FromObject(new CompletionResolveData(resultId, ProtocolConversions.DocumentToTextDocumentIdentifier(document))),
Data = JsonSerializer.SerializeToElement(new CompletionResolveData(resultId, ProtocolConversions.DocumentToTextDocumentIdentifier(document)), s_messageFormatter.JsonSerializerOptions),
Preselect = preselect,
VsResolveTextEditOnCommit = vsResolveTextEditOnCommit,
LabelDetails = labelDetails
Expand Down Expand Up @@ -512,13 +514,6 @@ private static LSP.DidCloseTextDocumentParams CreateDidCloseTextDocumentParams(U
}
};

internal static JsonMessageFormatter CreateJsonMessageFormatter()
{
var messageFormatter = new JsonMessageFormatter();
LSP.VSInternalExtensionUtilities.AddVSInternalExtensionConverters(messageFormatter.JsonSerializer);
return messageFormatter;
}

internal sealed class TestLspServer : IAsyncDisposable
{
public readonly EditorTestWorkspace TestWorkspace;
Expand All @@ -545,7 +540,7 @@ internal sealed class TestLspServer : IAsyncDisposable

LanguageServer = target;

_clientRpc = new JsonRpc(new HeaderDelimitedMessageHandler(clientStream, clientStream, CreateJsonMessageFormatter()), clientTarget)
_clientRpc = new JsonRpc(new HeaderDelimitedMessageHandler(clientStream, clientStream, RoslynLanguageServer.CreateJsonMessageFormatter()), clientTarget)
{
ExceptionStrategy = ExceptionProcessing.ISerializable,
};
Expand Down Expand Up @@ -607,13 +602,13 @@ private static RoslynLanguageServer CreateLanguageServer(Stream inputStream, Str
var capabilitiesProvider = workspace.ExportProvider.GetExportedValue<ExperimentalCapabilitiesProvider>();
var factory = workspace.ExportProvider.GetExportedValue<ILanguageServerFactory>();

var jsonMessageFormatter = CreateJsonMessageFormatter();
var jsonMessageFormatter = RoslynLanguageServer.CreateJsonMessageFormatter();
var jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream, jsonMessageFormatter))
{
ExceptionStrategy = ExceptionProcessing.ISerializable,
};

var languageServer = (RoslynLanguageServer)factory.Create(jsonRpc, jsonMessageFormatter.JsonSerializer, capabilitiesProvider, serverKind, logger, workspace.Services.HostServices);
var languageServer = (RoslynLanguageServer)factory.Create(jsonRpc, jsonMessageFormatter.JsonSerializerOptions, capabilitiesProvider, serverKind, logger, workspace.Services.HostServices);

jsonRpc.StartListening();
return languageServer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
// See the LICENSE file in the project root for more information.

using System.Collections.Concurrent;
using System.Text.Json;
using Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.FileWatching;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.LanguageServer.Protocol;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using StreamJsonRpc;
using Xunit.Abstractions;
using FileSystemWatcher = Roslyn.LanguageServer.Protocol.FileSystemWatcher;
Expand Down Expand Up @@ -115,8 +114,8 @@ private static async Task WaitForFileWatcherAsync(TestLspServer testLspServer)

private static FileSystemWatcher GetSingleFileWatcher(DynamicCapabilitiesRpcTarget dynamicCapabilities)
{
var registrationJson = Assert.IsType<JObject>(Assert.Single(dynamicCapabilities.Registrations).Value.RegisterOptions);
var registration = registrationJson.ToObject<DidChangeWatchedFilesRegistrationOptions>()!;
var registrationJson = Assert.IsType<JsonElement>(Assert.Single(dynamicCapabilities.Registrations).Value.RegisterOptions);
var registration = JsonSerializer.Deserialize<DidChangeWatchedFilesRegistrationOptions>(registrationJson, ProtocolConversions.LspJsonSerializerOptions)!;

return Assert.Single(registration.Watchers);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ private TestLspServer(ExportProvider exportProvider, ILogger logger)
var (clientStream, serverStream) = FullDuplexStream.CreatePair();
LanguageServerHost = new LanguageServerHost(serverStream, serverStream, exportProvider, logger);

_clientRpc = new JsonRpc(new HeaderDelimitedMessageHandler(clientStream, clientStream, new JsonMessageFormatter()))
var messageFormatter = LanguageServerHost.CreateJsonMessageFormatter();
_clientRpc = new JsonRpc(new HeaderDelimitedMessageHandler(clientStream, clientStream, messageFormatter))
{
AllowModificationWhileListening = true,
ExceptionStrategy = ExceptionProcessing.ISerializable,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// See the LICENSE file in the project root for more information.

using System.Composition;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CommonLanguageServerProtocol.Framework;
Expand Down Expand Up @@ -32,10 +32,9 @@ public ServiceBrokerConnectHandler(ServiceBrokerFactory serviceBrokerFactory)
return _serviceBrokerFactory.CreateAndConnectAsync(request.PipeName);
}

[DataContract]
private class NotificationParams
{
[DataMember(Name = "pipeName")]
[JsonPropertyName("pipeName")]
public required string PipeName { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,40 @@
// See the LICENSE file in the project root for more information.

using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.Text.Json.Serialization;

namespace Roslyn.LanguageServer.Protocol;

[DataContract]
internal class DidChangeWatchedFilesRegistrationOptions
{
[DataMember(Name = "watchers")]
[JsonPropertyName("watchers")]
public required FileSystemWatcher[] Watchers { get; set; }
}

[DataContract]
internal class FileSystemWatcher
{
[DataMember(Name = "globPattern")]
[JsonPropertyName("globPattern")]
public required RelativePattern GlobPattern { get; set; }

[DataMember(Name = "kind")]
[JsonPropertyName("kind")]
public WatchKind? Kind { get; set; }
}

[DataContract]
internal class RelativePattern
{
[DataMember(Name = "baseUri")]
[JsonPropertyName("baseUri")]
[JsonConverter(typeof(DocumentUriConverter))]
public required Uri BaseUri { get; set; }

[DataMember(Name = "pattern")]
[JsonPropertyName("pattern")]
public required string Pattern { get; set; }
}

// The LSP specification has a spelling error in the protocol, but Microsoft.VisualStudio.LanguageServer.Protocol
// didn't carry that error along. This corrects that.
[DataContract]
internal class UnregistrationParamsWithMisspelling
{
[DataMember(Name = "unregisterations")]
[JsonPropertyName("unregisterations")]
public required Unregistration[] Unregistrations { get; set; }
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// See the LICENSE file in the project root for more information.

using System.Composition;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CommonLanguageServerProtocol.Framework;
Expand Down Expand Up @@ -32,10 +32,9 @@ public OpenProjectHandler(LanguageServerProjectSystem projectSystem)
return _projectSystem.OpenProjectsAsync(request.Projects.SelectAsArray(p => p.LocalPath));
}

[DataContract]
private class NotificationParams
{
[DataMember(Name = "projects")]
[JsonPropertyName("projects")]
public required Uri[] Projects { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// Licensed to the .NET Foundation under one or more agreements.
// 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.Composition;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CommonLanguageServerProtocol.Framework;
Expand Down Expand Up @@ -31,10 +31,9 @@ public OpenSolutionHandler(LanguageServerProjectSystem projectSystem)
return _projectSystem.OpenSolutionAsync(request.Solution.LocalPath);
}

[DataContract]
private class NotificationParams
{
[DataMember(Name = "solution")]
[JsonPropertyName("solution")]
public required Uri Solution { get; set; }
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// See the LICENSE file in the project root for more information.

using System.Collections.Immutable;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using Microsoft.CodeAnalysis.LanguageServer.LanguageServer;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.PooledObjects;
Expand Down Expand Up @@ -133,7 +133,6 @@ internal static async Task RestoreProjectsAsync(ImmutableHashSet<string> project
await languageServerManager.SendRequestAsync(ProjectNeedsRestoreName, unresolvedParams, cancellationToken);
}

[DataContract]
private record UnresolvedDependenciesParams(
[property: DataMember(Name = "projectFilePaths")] string[] ProjectFilePaths);
[property: JsonPropertyName("projectFilePaths")] string[] ProjectFilePaths);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// 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.Serialization;
using System.Text.Json.Serialization;

namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.ProjectTelemetry;

Expand All @@ -12,17 +12,16 @@ namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.ProjectTelemetry;
/// except for SdkVersion, which is unused by the client in the O# version.
/// </summary>

[DataContract]
internal record ProjectLoadTelemetryEvent(
// The project guid (if it came from a solution), or a hash representing the file path and contents.
[property: DataMember(Name = "ProjectId")] string ProjectId,
[property: DataMember(Name = "SessionId")] string SessionId,
[property: DataMember(Name = "OutputKind")] int OutputKind,
[property: DataMember(Name = "ProjectCapabilities")] IEnumerable<string> ProjectCapabilities,
[property: DataMember(Name = "TargetFrameworks")] IEnumerable<string> TargetFrameworks,
[property: DataMember(Name = "References")] IEnumerable<string> References,
[property: DataMember(Name = "FileExtensions")] IEnumerable<string> FileExtensions,
[property: DataMember(Name = "FileCounts")] IEnumerable<int> FileCounts,
[property: DataMember(Name = "SdkStyleProject")] bool SdkStyleProject)
[property: JsonPropertyName("ProjectId")] string ProjectId,
[property: JsonPropertyName("SessionId")] string SessionId,
[property: JsonPropertyName("OutputKind")] int OutputKind,
[property: JsonPropertyName("ProjectCapabilities")] IEnumerable<string> ProjectCapabilities,
[property: JsonPropertyName("TargetFrameworks")] IEnumerable<string> TargetFrameworks,
[property: JsonPropertyName("References")] IEnumerable<string> References,
[property: JsonPropertyName("FileExtensions")] IEnumerable<string> FileExtensions,
[property: JsonPropertyName("FileCounts")] IEnumerable<int> FileCounts,
[property: JsonPropertyName("SdkStyleProject")] bool SdkStyleProject)
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// See the LICENSE file in the project root for more information.

using System.Composition;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer.LanguageServer;
Expand All @@ -18,26 +18,23 @@ internal class RazorDynamicFileInfoProvider : IDynamicFileInfoProvider
{
private const string ProvideRazorDynamicFileInfoMethodName = "razor/provideDynamicFileInfo";

[DataContract]
private class ProvideDynamicFileParams
{
[DataMember(Name = "razorFiles")]
[JsonPropertyName("razorFiles")]
public required Uri[] RazorFiles { get; set; }
}

[DataContract]
private class ProvideDynamicFileResponse
{
[DataMember(Name = "generatedFiles")]
[JsonPropertyName("generatedFiles")]
public required Uri[] GeneratedFiles { get; set; }
}

private const string RemoveRazorDynamicFileInfoMethodName = "razor/removeDynamicFileInfo";

[DataContract]
private class RemoveDynamicFileParams
{
[DataMember(Name = "razorFiles")]
[JsonPropertyName("razorFiles")]
public required Uri[] RazorFiles { get; set; }
}

Expand Down