diff --git a/.build/Build.cs b/.build/Build.cs index f98da474f..51e58f460 100644 --- a/.build/Build.cs +++ b/.build/Build.cs @@ -6,7 +6,6 @@ using Nuke.Common.Tools.DotNet; using Nuke.Common.Tools.GitVersion; using Nuke.Common.Tools.MSBuild; -using Rocket.Surgery.Nuke; using Rocket.Surgery.Nuke.DotNetCore; [PublicAPI] @@ -37,7 +36,10 @@ public partial class Solution : NukeBuild, /// - Microsoft VisualStudio https://nuke.build/visualstudio /// - Microsoft VSCode https://nuke.build/vscode /// - public static int Main() => Execute(x => x.Default); + public static int Main() + { + return Execute(x => x.Default); + } [OptionalGitRepository] public GitRepository? GitRepository { get; } diff --git a/.lintstagedrc.js b/.lintstagedrc.js index 8403c0104..0e6af2f49 100644 --- a/.lintstagedrc.js +++ b/.lintstagedrc.js @@ -19,10 +19,8 @@ function cleanupcode(filenames) { module.exports = { '*.cs': filenames => { - return [`echo "'${filenames.join(`' '`)}'" | dotnet format --include -`].concat(cleanupcode(filenames)); + return [`echo "'${filenames.join(`' '`)}'" | dotnet format --include -`]; //.concat(cleanupcode(filenames)); }, - '*.{csproj,targets,props,xml}': filenames => - forEachChunk(filenames, chunk => [`prettier --write '${chunk.join(`' '`)}'`]), - '*.{js,ts,jsx,tsx,json,yml,yaml}': filenames => - forEachChunk(filenames, chunk => [`prettier --write '${chunk.join(`' '`)}'`]), + '*.{csproj,targets,props,xml}': filenames => forEachChunk(filenames, chunk => [`prettier --write '${chunk.join(`' '`)}'`]), + '*.{js,ts,jsx,tsx,json,yml,yaml}': filenames => forEachChunk(filenames, chunk => [`prettier --write '${chunk.join(`' '`)}'`]), }; diff --git a/Directory.Build.targets b/Directory.Build.targets index 765e8a870..6078ba62b 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -35,15 +35,15 @@ - - + + - + diff --git a/sample/SampleServer/Program.cs b/sample/SampleServer/Program.cs index d86b96a49..999932d2a 100644 --- a/sample/SampleServer/Program.cs +++ b/sample/SampleServer/Program.cs @@ -8,11 +8,16 @@ using OmniSharp.Extensions.LanguageServer.Server; using Serilog; +// ReSharper disable UnusedParameter.Local + namespace SampleServer { internal class Program { - private static void Main(string[] args) => MainAsync(args).Wait(); + private static void Main(string[] args) + { + MainAsync(args).Wait(); + } private static async Task MainAsync(string[] args) { @@ -51,9 +56,11 @@ private static async Task MainAsync(string[] args) .WithHandler() .WithServices(x => x.AddLogging(b => b.SetMinimumLevel(LogLevel.Trace))) .WithServices( - services => { + services => + { services.AddSingleton( - provider => { + provider => + { var loggerFactory = provider.GetService(); var logger = loggerFactory.CreateLogger(); @@ -63,20 +70,24 @@ private static async Task MainAsync(string[] args) } ); services.AddSingleton( - new ConfigurationItem { + new ConfigurationItem + { Section = "typescript", } ).AddSingleton( - new ConfigurationItem { + new ConfigurationItem + { Section = "terminal", } ); } ) .OnInitialize( - async (server, request, token) => { + async (server, request, token) => + { var manager = server.WorkDoneManager.For( - request, new WorkDoneProgressBegin { + request, new WorkDoneProgressBegin + { Title = "Server is starting...", Percentage = 10, } @@ -86,7 +97,8 @@ private static async Task MainAsync(string[] args) await Task.Delay(2000).ConfigureAwait(false); manager.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 20, Message = "loading in progress" } @@ -94,9 +106,11 @@ private static async Task MainAsync(string[] args) } ) .OnInitialized( - async (server, request, response, token) => { + async (server, request, response, token) => + { workDone.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 40, Message = "loading almost done", } @@ -105,7 +119,8 @@ private static async Task MainAsync(string[] args) await Task.Delay(2000).ConfigureAwait(false); workDone.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Message = "loading done", Percentage = 100, } @@ -114,8 +129,10 @@ private static async Task MainAsync(string[] args) } ) .OnStarted( - async (languageServer, token) => { - using var manager = await languageServer.WorkDoneManager.Create(new WorkDoneProgressBegin { Title = "Doing some work..." }).ConfigureAwait(false); + async (languageServer, token) => + { + using var manager = await languageServer.WorkDoneManager.Create(new WorkDoneProgressBegin { Title = "Doing some work..." }) + .ConfigureAwait(false); manager.OnNext(new WorkDoneProgressReport { Message = "doing things..." }); await Task.Delay(10000).ConfigureAwait(false); @@ -125,9 +142,11 @@ private static async Task MainAsync(string[] args) var logger = languageServer.Services.GetService>(); var configuration = await languageServer.Configuration.GetConfiguration( - new ConfigurationItem { + new ConfigurationItem + { Section = "typescript", - }, new ConfigurationItem { + }, new ConfigurationItem + { Section = "terminal", } ).ConfigureAwait(false); @@ -138,7 +157,7 @@ private static async Task MainAsync(string[] args) baseConfig.Add(config.Key, config.Value); } - logger.LogInformation("Base Config: {Config}", baseConfig); + logger.LogInformation("Base Config: {@Config}", baseConfig); var scopedConfig = new JObject(); foreach (var config in configuration.AsEnumerable()) @@ -146,7 +165,7 @@ private static async Task MainAsync(string[] args) scopedConfig.Add(config.Key, config.Value); } - logger.LogInformation("Scoped Config: {Config}", scopedConfig); + logger.LogInformation("Scoped Config: {@Config}", scopedConfig); } ) ).ConfigureAwait(false); @@ -165,6 +184,9 @@ public Foo(ILogger logger) _logger = logger; } - public void SayFoo() => _logger.LogInformation("Fooooo!"); + public void SayFoo() + { + _logger.LogInformation("Fooooo!"); + } } } diff --git a/sample/SampleServer/SemanticTokensHandler.cs b/sample/SampleServer/SemanticTokensHandler.cs index 6f1a5db36..a95635c3d 100644 --- a/sample/SampleServer/SemanticTokensHandler.cs +++ b/sample/SampleServer/SemanticTokensHandler.cs @@ -9,7 +9,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace SampleServer { @@ -18,8 +17,10 @@ public class SemanticTokensHandler : SemanticTokensHandlerBase { private readonly ILogger _logger; - public SemanticTokensHandler(ILogger logger) => + public SemanticTokensHandler(ILogger logger) + { _logger = logger; + } public override async Task Handle( SemanticTokensParams request, CancellationToken cancellationToken @@ -57,7 +58,7 @@ CancellationToken cancellationToken var content = await File.ReadAllTextAsync(DocumentUri.GetFileSystemPath(identifier), cancellationToken).ConfigureAwait(false); await Task.Yield(); - foreach (var (line, text) in content.Split('\n').Select((text, line) => (line, text))) + foreach (var (line, text) in content.Split('\n').Select((text, line) => ( line, text ))) { var parts = text.TrimEnd().Split(';', ' ', '.', '"', '(', ')'); var index = 0; @@ -73,8 +74,10 @@ CancellationToken cancellationToken } protected override Task - GetSemanticTokensDocument(ITextDocumentIdentifierParams @params, CancellationToken cancellationToken) => - Task.FromResult(new SemanticTokensDocument(RegistrationOptions.Legend)); + GetSemanticTokensDocument(ITextDocumentIdentifierParams @params, CancellationToken cancellationToken) + { + return Task.FromResult(new SemanticTokensDocument(RegistrationOptions.Legend)); + } private IEnumerable RotateEnum(IEnumerable values) @@ -86,17 +89,25 @@ private IEnumerable RotateEnum(IEnumerable values) } } - protected override SemanticTokensRegistrationOptions CreateRegistrationOptions(SemanticTokensCapability capability, ClientCapabilities clientCapabilities) => new SemanticTokensRegistrationOptions { - DocumentSelector = DocumentSelector.ForLanguage("csharp"), - Legend = new SemanticTokensLegend() { - TokenModifiers = capability.TokenModifiers, - TokenTypes = capability.TokenTypes - }, - Full = new SemanticTokensCapabilityRequestFull { - Delta = true - }, - Range = true - }; + protected override SemanticTokensRegistrationOptions CreateRegistrationOptions( + SemanticTokensCapability capability, ClientCapabilities clientCapabilities + ) + { + return new SemanticTokensRegistrationOptions + { + DocumentSelector = DocumentSelector.ForLanguage("csharp"), + Legend = new SemanticTokensLegend + { + TokenModifiers = capability.TokenModifiers, + TokenTypes = capability.TokenTypes + }, + Full = new SemanticTokensCapabilityRequestFull + { + Delta = true + }, + Range = true + }; + } } #pragma warning restore 618 } diff --git a/src/Client/LanguageClient.cs b/src/Client/LanguageClient.cs index 0d5ba8b19..633634784 100644 --- a/src/Client/LanguageClient.cs +++ b/src/Client/LanguageClient.cs @@ -25,6 +25,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; using OmniSharp.Extensions.LanguageServer.Shared; + // ReSharper disable SuspiciousTypeConversion.Global namespace OmniSharp.Extensions.LanguageServer.Client @@ -64,12 +65,21 @@ public class LanguageClient : JsonRpcServerBase, ILanguageClient private readonly int? _concurrency; private readonly IResolverContext _resolverContext; - internal static IContainer CreateContainer(LanguageClientOptions options, IServiceProvider? outerServiceProvider) => - JsonRpcServerContainer.Create(outerServiceProvider) - .AddLanguageClientInternals(options, outerServiceProvider); + internal static IContainer CreateContainer(LanguageClientOptions options, IServiceProvider? outerServiceProvider) + { + return JsonRpcServerContainer.Create(outerServiceProvider) + .AddLanguageClientInternals(options, outerServiceProvider); + } - public static LanguageClient Create(LanguageClientOptions options) => Create(options, null); - public static LanguageClient Create(Action optionsAction) => Create(optionsAction, null); + public static LanguageClient Create(LanguageClientOptions options) + { + return Create(options, null); + } + + public static LanguageClient Create(Action optionsAction) + { + return Create(optionsAction, null); + } public static LanguageClient Create(Action optionsAction, IServiceProvider? outerServiceProvider) { @@ -78,28 +88,53 @@ public static LanguageClient Create(Action optionsAction, return Create(options, outerServiceProvider); } - public static LanguageClient Create(LanguageClientOptions options, IServiceProvider? outerServiceProvider) => - CreateContainer(options, outerServiceProvider).Resolve(); + public static LanguageClient Create(LanguageClientOptions options, IServiceProvider? outerServiceProvider) + { + return CreateContainer(options, outerServiceProvider).Resolve(); + } - public static Task From(LanguageClientOptions options) => From(options, null, CancellationToken.None); - public static Task From(Action optionsAction) => From(optionsAction, null, CancellationToken.None); - public static Task From(LanguageClientOptions options, CancellationToken cancellationToken) => From(options, null, cancellationToken); - public static Task From(Action optionsAction, CancellationToken cancellationToken) => From(optionsAction, null, cancellationToken); + public static Task From(LanguageClientOptions options) + { + return From(options, null, CancellationToken.None); + } - public static Task From(LanguageClientOptions options, IServiceProvider? outerServiceProvider) => - From(options, outerServiceProvider, CancellationToken.None); + public static Task From(Action optionsAction) + { + return From(optionsAction, null, CancellationToken.None); + } - public static Task From(Action optionsAction, IServiceProvider? outerServiceProvider) => - From(optionsAction, outerServiceProvider, CancellationToken.None); + public static Task From(LanguageClientOptions options, CancellationToken cancellationToken) + { + return From(options, null, cancellationToken); + } - public static Task From(Action optionsAction, IServiceProvider? outerServiceProvider, CancellationToken cancellationToken) + public static Task From(Action optionsAction, CancellationToken cancellationToken) + { + return From(optionsAction, null, cancellationToken); + } + + public static Task From(LanguageClientOptions options, IServiceProvider? outerServiceProvider) + { + return From(options, outerServiceProvider, CancellationToken.None); + } + + public static Task From(Action optionsAction, IServiceProvider? outerServiceProvider) + { + return From(optionsAction, outerServiceProvider, CancellationToken.None); + } + + public static Task From( + Action optionsAction, IServiceProvider? outerServiceProvider, CancellationToken cancellationToken + ) { var options = new LanguageClientOptions(); optionsAction(options); return From(options, outerServiceProvider, cancellationToken); } - public static async Task From(LanguageClientOptions options, IServiceProvider? outerServiceProvider, CancellationToken cancellationToken) + public static async Task From( + LanguageClientOptions options, IServiceProvider? outerServiceProvider, CancellationToken cancellationToken + ) { var server = Create(options, outerServiceProvider); await server.Initialize(cancellationToken).ConfigureAwait(false); @@ -113,7 +148,10 @@ public static async Task From(LanguageClientOptions options, ISe /// /// /// - public static LanguageClient PreInit(Action optionsAction) => Create(optionsAction); + public static LanguageClient PreInit(Action optionsAction) + { + return Create(optionsAction); + } /// /// Create the server without connecting to the client @@ -122,7 +160,10 @@ public static async Task From(LanguageClientOptions options, ISe /// /// /// - public static LanguageClient PreInit(LanguageClientOptions options) => Create(options); + public static LanguageClient PreInit(LanguageClientOptions options) + { + return Create(options); + } internal LanguageClient( Connection connection, @@ -219,7 +260,8 @@ public InitializeResult ServerSettings public async Task Initialize(CancellationToken token) { - var @params = new InitializeParams { + var @params = new InitializeParams + { Trace = _trace, ClientInfo = _clientInfo, Capabilities = _clientCapabilities, @@ -232,7 +274,8 @@ public async Task Initialize(CancellationToken token) var capabilitiesObject = new JObject(); foreach (var capability in _capabilities) { - var keys = capability.GetType().GetCustomAttribute()?.Keys.Select(key => char.ToLower(key[0]) + key.Substring(1)).ToArray(); + var keys = capability.GetType().GetCustomAttribute()?.Keys.Select(key => char.ToLower(key[0]) + key.Substring(1)) + .ToArray(); if (keys != null) { var value = capabilitiesObject; @@ -247,6 +290,7 @@ public async Task Initialize(CancellationToken token) value[key] = value = new JObject(); } } + var lastKey = keys[keys.Length - 1]; value[lastKey] = JToken.FromObject(capability, _serializer.JsonSerializer); } @@ -399,8 +443,10 @@ private Supports UseOrTryAndFindCapability(Supports supports) where T : public IObservable Start => _initializeComplete.AsObservable(); - bool IResponseRouter.TryGetRequest(long id, [NotNullWhen(true)] out string method, [NotNullWhen(true)] out TaskCompletionSource pendingTask) => - _responseRouter.TryGetRequest(id, out method, out pendingTask); + bool IResponseRouter.TryGetRequest(long id, [NotNullWhen(true)] out string? method, [NotNullWhen(true)] out TaskCompletionSource? pendingTask) + { + return _responseRouter.TryGetRequest(id, out method, out pendingTask); + } public Task WasStarted => _initializeComplete.ToTask(_scheduler); @@ -423,6 +469,9 @@ public IDisposable Register(Action registryAction) return result; } - object IServiceProvider.GetService(Type serviceType) => Services.GetService(serviceType); + object IServiceProvider.GetService(Type serviceType) + { + return Services.GetService(serviceType); + } } } diff --git a/src/Client/LanguageClientServiceCollectionExtensions.cs b/src/Client/LanguageClientServiceCollectionExtensions.cs index ff5a021c5..a0e3c8b3c 100644 --- a/src/Client/LanguageClientServiceCollectionExtensions.cs +++ b/src/Client/LanguageClientServiceCollectionExtensions.cs @@ -25,7 +25,7 @@ internal static IContainer AddLanguageClientInternals(this IContainer container, container.RegisterInstance(options.ClientCapabilities); container.RegisterMany( - reuse: Reuse.Singleton, + Reuse.Singleton, nonPublicServiceTypes: true, ifAlreadyRegistered: IfAlreadyRegistered.Keep ); @@ -41,14 +41,24 @@ internal static IContainer AddLanguageClientInternals(this IContainer container, #pragma warning restore 4014 } - container.RegisterMany(serviceTypeCondition: type => type.Name.Contains(nameof(TextDocumentLanguageClient)), reuse: Reuse.Singleton); - container.RegisterMany(serviceTypeCondition: type => type.Name.Contains(nameof(ClientLanguageClient)), reuse: Reuse.Singleton); - container.RegisterMany(serviceTypeCondition: type => type.Name.Contains(nameof(GeneralLanguageClient)), reuse: Reuse.Singleton); - container.RegisterMany(serviceTypeCondition: type => type.Name.Contains(nameof(WindowLanguageClient)), reuse: Reuse.Singleton); - container.RegisterMany(serviceTypeCondition: type => type.Name.Contains(nameof(WorkspaceLanguageClient)), reuse: Reuse.Singleton); + container.RegisterMany( + serviceTypeCondition: type => type.Name.Contains(nameof(TextDocumentLanguageClient)), reuse: Reuse.Singleton + ); + container.RegisterMany( + serviceTypeCondition: type => type.Name.Contains(nameof(ClientLanguageClient)), reuse: Reuse.Singleton + ); + container.RegisterMany( + serviceTypeCondition: type => type.Name.Contains(nameof(GeneralLanguageClient)), reuse: Reuse.Singleton + ); + container.RegisterMany( + serviceTypeCondition: type => type.Name.Contains(nameof(WindowLanguageClient)), reuse: Reuse.Singleton + ); + container.RegisterMany( + serviceTypeCondition: type => type.Name.Contains(nameof(WorkspaceLanguageClient)), reuse: Reuse.Singleton + ); container.RegisterMany( - serviceTypeCondition: type => type.IsClass || !type.Name.Contains("Proxy") && typeof(DefaultLanguageClientFacade).GetInterfaces() - .Except(typeof(DefaultLanguageClientFacade).BaseType!.GetInterfaces()).Any(z => type == z), + serviceTypeCondition: type => type.IsClass || ( !type.Name.Contains("Proxy") && typeof(DefaultLanguageClientFacade).GetInterfaces() + .Except(typeof(DefaultLanguageClientFacade).BaseType!.GetInterfaces()).Any(z => type == z) ), reuse: Reuse.Singleton ); container.RegisterInstance>(new ValueOptionsFactory(options)); @@ -60,7 +70,8 @@ internal static IContainer AddLanguageClientInternals(this IContainer container, ); container.RegisterInstance( - options.ClientInfo ?? new ClientInfo { + options.ClientInfo ?? new ClientInfo + { Name = Assembly.GetEntryAssembly()?.GetName().ToString() ?? string.Empty, Version = Assembly.GetEntryAssembly()?.GetCustomAttribute() ?.InformationalVersion ?? @@ -69,9 +80,11 @@ internal static IContainer AddLanguageClientInternals(this IContainer container, } ); - var providedConfiguration = options.Services.FirstOrDefault(z => z.ServiceType == typeof(IConfiguration) && z.ImplementationInstance is IConfiguration); + var providedConfiguration = + options.Services.FirstOrDefault(z => z.ServiceType == typeof(IConfiguration) && z.ImplementationInstance is IConfiguration); container.RegisterDelegate( - _ => { + _ => + { var builder = options.ConfigurationBuilder; var outerConfiguration = outerServiceProvider?.GetService(); if (outerConfiguration != null) @@ -103,10 +116,14 @@ internal static IContainer AddLanguageClientInternals(this IContainer container, return container; } - public static IServiceCollection AddLanguageClient(this IServiceCollection services, Action? configureOptions = null) => - AddLanguageClient(services, Options.DefaultName, configureOptions); + public static IServiceCollection AddLanguageClient(this IServiceCollection services, Action? configureOptions = null) + { + return AddLanguageClient(services, Options.DefaultName, configureOptions); + } - public static IServiceCollection AddLanguageClient(this IServiceCollection services, string name, Action? configureOptions = null) + public static IServiceCollection AddLanguageClient( + this IServiceCollection services, string name, Action? configureOptions = null + ) { // If we get called multiple times we're going to remove the default server // and force consumers to use the resolver. diff --git a/src/Dap.Client/DebugAdapterClient.cs b/src/Dap.Client/DebugAdapterClient.cs index 3141c0605..209c110c0 100644 --- a/src/Dap.Client/DebugAdapterClient.cs +++ b/src/Dap.Client/DebugAdapterClient.cs @@ -16,6 +16,7 @@ using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; using OmniSharp.Extensions.DebugAdapter.Shared; using OmniSharp.Extensions.JsonRpc; + // ReSharper disable SuspiciousTypeConversion.Global namespace OmniSharp.Extensions.DebugAdapter.Client @@ -39,12 +40,21 @@ public class DebugAdapterClient : JsonRpcServerBase, IDebugAdapterClient, IDebug private readonly ISubject _initializedComplete = new AsyncSubject(); private readonly int? _concurrency; - internal static IContainer CreateContainer(DebugAdapterClientOptions options, IServiceProvider? outerServiceProvider) => - JsonRpcServerContainer.Create(outerServiceProvider) - .AddDebugAdapterClientInternals(options, outerServiceProvider); + internal static IContainer CreateContainer(DebugAdapterClientOptions options, IServiceProvider? outerServiceProvider) + { + return JsonRpcServerContainer.Create(outerServiceProvider) + .AddDebugAdapterClientInternals(options, outerServiceProvider); + } - public static DebugAdapterClient Create(DebugAdapterClientOptions options) => Create(options, null); - public static DebugAdapterClient Create(Action optionsAction) => Create(optionsAction, null); + public static DebugAdapterClient Create(DebugAdapterClientOptions options) + { + return Create(options, null); + } + + public static DebugAdapterClient Create(Action optionsAction) + { + return Create(optionsAction, null); + } public static DebugAdapterClient Create(Action optionsAction, IServiceProvider? outerServiceProvider) { @@ -53,30 +63,53 @@ public static DebugAdapterClient Create(Action option return Create(options, outerServiceProvider); } - public static DebugAdapterClient Create(DebugAdapterClientOptions options, IServiceProvider? outerServiceProvider) => - CreateContainer(options, outerServiceProvider).Resolve(); + public static DebugAdapterClient Create(DebugAdapterClientOptions options, IServiceProvider? outerServiceProvider) + { + return CreateContainer(options, outerServiceProvider).Resolve(); + } + + public static Task From(DebugAdapterClientOptions options) + { + return From(options, null, CancellationToken.None); + } + + public static Task From(Action optionsAction) + { + return From(optionsAction, null, CancellationToken.None); + } - public static Task From(DebugAdapterClientOptions options) => From(options, null, CancellationToken.None); - public static Task From(Action optionsAction) => From(optionsAction, null, CancellationToken.None); - public static Task From(DebugAdapterClientOptions options, CancellationToken cancellationToken) => From(options, null, cancellationToken); + public static Task From(DebugAdapterClientOptions options, CancellationToken cancellationToken) + { + return From(options, null, cancellationToken); + } - public static Task From(Action optionsAction, CancellationToken cancellationToken) => - From(optionsAction, null, cancellationToken); + public static Task From(Action optionsAction, CancellationToken cancellationToken) + { + return From(optionsAction, null, cancellationToken); + } - public static Task From(DebugAdapterClientOptions options, IServiceProvider? outerServiceProvider) => - From(options, outerServiceProvider, CancellationToken.None); + public static Task From(DebugAdapterClientOptions options, IServiceProvider? outerServiceProvider) + { + return From(options, outerServiceProvider, CancellationToken.None); + } - public static Task From(Action optionsAction, IServiceProvider? outerServiceProvider) => - From(optionsAction, outerServiceProvider, CancellationToken.None); + public static Task From(Action optionsAction, IServiceProvider? outerServiceProvider) + { + return From(optionsAction, outerServiceProvider, CancellationToken.None); + } - public static Task From(Action optionsAction, IServiceProvider? outerServiceProvider, CancellationToken cancellationToken) + public static Task From( + Action optionsAction, IServiceProvider? outerServiceProvider, CancellationToken cancellationToken + ) { var options = new DebugAdapterClientOptions(); optionsAction(options); return From(options, outerServiceProvider, cancellationToken); } - public static async Task From(DebugAdapterClientOptions options, IServiceProvider? outerServiceProvider, CancellationToken cancellationToken) + public static async Task From( + DebugAdapterClientOptions options, IServiceProvider? outerServiceProvider, CancellationToken cancellationToken + ) { var server = Create(options, outerServiceProvider); await server.Initialize(cancellationToken).ConfigureAwait(false); @@ -179,9 +212,11 @@ Task IRequestHandler.Handle(InitializedEvent reque private void RegisterCapabilities(InitializeRequestArguments capabilities) { capabilities.SupportsRunInTerminalRequest = capabilities.SupportsRunInTerminalRequest || _collection.ContainsHandler(typeof(IRunInTerminalHandler)); - capabilities.SupportsProgressReporting = capabilities.SupportsProgressReporting || _collection.ContainsHandler(typeof(IProgressStartHandler)) && - _collection.ContainsHandler(typeof(IProgressUpdateHandler)) && - _collection.ContainsHandler(typeof(IProgressEndHandler)); + capabilities.SupportsProgressReporting = capabilities.SupportsProgressReporting || ( + _collection.ContainsHandler(typeof(IProgressStartHandler)) && + _collection.ContainsHandler(typeof(IProgressUpdateHandler)) && + _collection.ContainsHandler(typeof(IProgressEndHandler)) + ); } public InitializeRequestArguments ClientSettings @@ -204,6 +239,9 @@ public void Dispose() _connection.Dispose(); } - object IServiceProvider.GetService(Type serviceType) => _serviceProvider.GetService(serviceType); + object IServiceProvider.GetService(Type serviceType) + { + return _serviceProvider.GetService(serviceType); + } } } diff --git a/src/Dap.Client/DebugAdapterClientOptions.cs b/src/Dap.Client/DebugAdapterClientOptions.cs index 0f11dceee..56ce0c978 100644 --- a/src/Dap.Client/DebugAdapterClientOptions.cs +++ b/src/Dap.Client/DebugAdapterClientOptions.cs @@ -1,13 +1,11 @@ using System; using System.Threading; using System.Threading.Tasks; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.DebugAdapter.Protocol.Client; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.DebugAdapter.Shared; using OmniSharp.Extensions.JsonRpc; @@ -35,108 +33,199 @@ public DebugAdapterClientOptions() public bool SupportsProgressReporting { get; set; } public bool SupportsInvalidatedEvent { get; set; } - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions? options) => - AddHandler(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler( + string method, IJsonRpcHandler handler, JsonRpcHandlerOptions? options + ) + { + return AddHandler(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry. - AddHandler(string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions? options) => AddHandler(method, handlerFunc, options); + AddHandler(string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions? options) + { + return AddHandler(method, handlerFunc, options); + } - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandlers(params IJsonRpcHandler[] handlers) => AddHandlers(handlers); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandlers(params IJsonRpcHandler[] handlers) + { + return AddHandlers(handlers); + } - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions? options) => - AddHandler(handlerFunc, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler( + JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions? options + ) + { + return AddHandler(handlerFunc, options); + } - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptions? options) => - AddHandler(handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptions? options) + { + return AddHandler(handler, options); + } - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerOptions? options) => AddHandler(options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerOptions? options) + { + return AddHandler(options); + } - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerOptions? options) => - AddHandler(method, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerOptions? options) + { + return AddHandler(method, options); + } - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(Type type, JsonRpcHandlerOptions? options) => AddHandler(type, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(Type type, JsonRpcHandlerOptions? options) + { + return AddHandler(type, options); + } - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, Type type, JsonRpcHandlerOptions? options) => - AddHandler(method, type, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, Type type, JsonRpcHandlerOptions? options) + { + return AddHandler(method, type, options); + } - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandlerLink(string fromMethod, string toMethod) => - AddHandlerLink(fromMethod, toMethod); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandlerLink(string fromMethod, string toMethod) + { + return AddHandlerLink(fromMethod, toMethod); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonRequest( string method, Func> handler, JsonRpcHandlerOptions? options - ) => OnJsonRequest(method, handler, options); + ) + { + return OnJsonRequest(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonRequest( string method, Func> handler, JsonRpcHandlerOptions? options - ) => OnJsonRequest(method, handler, options); + ) + { + return OnJsonRequest(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( string method, Func> handler, JsonRpcHandlerOptions? options - ) => OnRequest(method, handler, options); + ) + { + return OnRequest(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( string method, Func> handler, JsonRpcHandlerOptions? options - ) => OnRequest(method, handler, options); + ) + { + return OnRequest(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( string method, Func> handler, JsonRpcHandlerOptions? options - ) => OnRequest(method, handler, options); + ) + { + return OnRequest(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( string method, Func> handler, JsonRpcHandlerOptions? options - ) => OnRequest(method, handler, options); + ) + { + return OnRequest(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( string method, Func handler, JsonRpcHandlerOptions? options - ) => OnRequest(method, handler, options); + ) + { + return OnRequest(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( string method, Func handler, JsonRpcHandlerOptions? options - ) => OnRequest(method, handler, options); + ) + { + return OnRequest(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( string method, Func handler, JsonRpcHandlerOptions? options - ) => OnRequest(method, handler, options); + ) + { + return OnRequest(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnNotification( string method, Action handler, JsonRpcHandlerOptions? options - ) => OnNotification(method, handler, options); + ) + { + return OnNotification(method, handler, options); + } - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions? options) => - OnJsonNotification(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification( + string method, Action handler, JsonRpcHandlerOptions? options + ) + { + return OnJsonNotification(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification( string method, Func handler, JsonRpcHandlerOptions? options - ) => OnJsonNotification(method, handler, options); + ) + { + return OnJsonNotification(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification( string method, Func handler, JsonRpcHandlerOptions? options - ) => OnJsonNotification(method, handler, options); + ) + { + return OnJsonNotification(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification( string method, Action handler, JsonRpcHandlerOptions? options - ) => OnJsonNotification(method, handler, options); + ) + { + return OnJsonNotification(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnNotification( string method, Action handler, JsonRpcHandlerOptions? options - ) => OnNotification(method, handler, options); + ) + { + return OnNotification(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnNotification( string method, Func handler, JsonRpcHandlerOptions? options - ) => OnNotification(method, handler, options); + ) + { + return OnNotification(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnNotification( string method, Func handler, JsonRpcHandlerOptions? options - ) => OnNotification(method, handler, options); + ) + { + return OnNotification(method, handler, options); + } - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, JsonRpcHandlerOptions? options) => - OnNotification(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnNotification( + string method, Action handler, JsonRpcHandlerOptions? options + ) + { + return OnNotification(method, handler, options); + } IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnNotification( string method, Func handler, JsonRpcHandlerOptions? options - ) => OnNotification(method, handler, options); + ) + { + return OnNotification(method, handler, options); + } - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, JsonRpcHandlerOptions? options) => - OnNotification(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnNotification( + string method, Func handler, JsonRpcHandlerOptions? options + ) + { + return OnNotification(method, handler, options); + } } } diff --git a/src/Dap.Client/DebugAdapterClientServiceCollectionExtensions.cs b/src/Dap.Client/DebugAdapterClientServiceCollectionExtensions.cs index a823d45d9..d4bffec16 100644 --- a/src/Dap.Client/DebugAdapterClientServiceCollectionExtensions.cs +++ b/src/Dap.Client/DebugAdapterClientServiceCollectionExtensions.cs @@ -15,7 +15,9 @@ namespace OmniSharp.Extensions.DebugAdapter.Client { public static class DebugAdapterClientServiceCollectionExtensions { - internal static IContainer AddDebugAdapterClientInternals(this IContainer container, DebugAdapterClientOptions options, IServiceProvider? outerServiceProvider) + internal static IContainer AddDebugAdapterClientInternals( + this IContainer container, DebugAdapterClientOptions options, IServiceProvider? outerServiceProvider + ) { container = container.AddDebugAdapterProtocolInternals(options); @@ -31,9 +33,10 @@ internal static IContainer AddDebugAdapterClientInternals(this IContainer contai container.RegisterInstance>(new ValueOptionsFactory(options)); container.RegisterInstance( - new InitializeRequestArguments { + new InitializeRequestArguments + { Locale = options.Locale, - AdapterId = options.AdapterId!, + AdapterId = options.AdapterId, ClientId = options.ClientId, ClientName = options.ClientName, PathFormat = options.PathFormat, @@ -55,14 +58,17 @@ internal static IContainer AddDebugAdapterClientInternals(this IContainer contai setup: Setup.With(condition: req => req.IsResolutionRoot || req.Container.Resolve().Started) ); container.RegisterMany( - serviceTypeCondition: type => type.IsClass || !type.Name.Contains("Proxy") && typeof(DefaultDebugAdapterClientFacade).GetInterfaces().Except(typeof(DefaultDebugAdapterClientFacade).BaseType!.GetInterfaces()).Any(z => type == z), + serviceTypeCondition: type => type.IsClass || ( !type.Name.Contains("Proxy") && typeof(DefaultDebugAdapterClientFacade).GetInterfaces() + .Except(typeof(DefaultDebugAdapterClientFacade).BaseType!.GetInterfaces()).Any(z => type == z) ), reuse: Reuse.Singleton ); // container. - var providedConfiguration = options.Services.FirstOrDefault(z => z.ServiceType == typeof(IConfiguration) && z.ImplementationInstance is IConfiguration); + var providedConfiguration = + options.Services.FirstOrDefault(z => z.ServiceType == typeof(IConfiguration) && z.ImplementationInstance is IConfiguration); container.RegisterDelegate( - _ => { + _ => + { var builder = new ConfigurationBuilder(); if (outerServiceProvider != null) { @@ -75,7 +81,7 @@ internal static IContainer AddDebugAdapterClientInternals(this IContainer contai if (providedConfiguration != null) { - builder.CustomAddConfiguration((providedConfiguration.ImplementationInstance as IConfiguration)!); + builder.CustomAddConfiguration(( providedConfiguration.ImplementationInstance as IConfiguration )!); } return builder.Build(); @@ -86,10 +92,14 @@ internal static IContainer AddDebugAdapterClientInternals(this IContainer contai return container; } - public static IServiceCollection AddDebugAdapterClient(this IServiceCollection services, Action? configureOptions = null) => - AddDebugAdapterClient(services, Options.DefaultName, configureOptions); + public static IServiceCollection AddDebugAdapterClient(this IServiceCollection services, Action? configureOptions = null) + { + return AddDebugAdapterClient(services, Options.DefaultName, configureOptions); + } - public static IServiceCollection AddDebugAdapterClient(this IServiceCollection services, string name, Action? configureOptions = null) + public static IServiceCollection AddDebugAdapterClient( + this IServiceCollection services, string name, Action? configureOptions = null + ) { // If we get called multiple times we're going to remove the default server // and force consumers to use the resolver. @@ -100,15 +110,21 @@ public static IServiceCollection AddDebugAdapterClient(this IServiceCollection s services.RemoveAll(); services.AddSingleton( _ => - throw new NotSupportedException("DebugAdapterClient has been registered multiple times, you must use DebugAdapterClientResolver instead") + throw new NotSupportedException( + "DebugAdapterClient has been registered multiple times, you must use DebugAdapterClientResolver instead" + ) ); services.AddSingleton( _ => - throw new NotSupportedException("DebugAdapterClient has been registered multiple times, you must use DebugAdapterClientResolver instead") + throw new NotSupportedException( + "DebugAdapterClient has been registered multiple times, you must use DebugAdapterClientResolver instead" + ) ); services.AddSingleton( _ => - throw new NotSupportedException("DebugAdapterClient has been registered multiple times, you must use DebugAdapterClientResolver instead") + throw new NotSupportedException( + "DebugAdapterClient has been registered multiple times, you must use DebugAdapterClientResolver instead" + ) ); } diff --git a/src/Dap.Protocol/DebugAdapterConverters/DapRpcErrorConverter.cs b/src/Dap.Protocol/DebugAdapterConverters/DapRpcErrorConverter.cs index d26bf9fd6..da99d76b2 100644 --- a/src/Dap.Protocol/DebugAdapterConverters/DapRpcErrorConverter.cs +++ b/src/Dap.Protocol/DebugAdapterConverters/DapRpcErrorConverter.cs @@ -48,9 +48,12 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist object? requestId = null; if (obj.TryGetValue("id", out var id)) { - var idString = id.Type == JTokenType.String ? (string) id : null; - var idLong = id.Type == JTokenType.Integer ? (long?) id : null; - requestId = idString ?? ( idLong.HasValue ? (object?) idLong.Value : null ); + requestId = id switch + { + { Type: JTokenType.String } => id.Value(), + { Type: JTokenType.Integer } => id.Value(), + _ => null + }; } ErrorMessage? data = null; diff --git a/src/Dap.Protocol/Feature/Events/BreakpointFeature.cs b/src/Dap.Protocol/Feature/Events/BreakpointFeature.cs index 19f04b79c..de76a5862 100644 --- a/src/Dap.Protocol/Feature/Events/BreakpointFeature.cs +++ b/src/Dap.Protocol/Feature/Events/BreakpointFeature.cs @@ -80,11 +80,9 @@ namespace Events { [Parallel] [Method(EventNames.Breakpoint, Direction.ServerToClient)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record BreakpointEvent : IRequest { /// @@ -96,7 +94,7 @@ public record BreakpointEvent : IRequest /// /// The 'id' attribute is used to find the target breakpoint and the other attributes are used as the new values. /// - public Breakpoint Breakpoint { get; init; } + public Breakpoint Breakpoint { get; init; } = null!; } diff --git a/src/Dap.Protocol/Feature/Events/CapabilitiesFeature.cs b/src/Dap.Protocol/Feature/Events/CapabilitiesFeature.cs index 28d81b0da..7d34b09b3 100644 --- a/src/Dap.Protocol/Feature/Events/CapabilitiesFeature.cs +++ b/src/Dap.Protocol/Feature/Events/CapabilitiesFeature.cs @@ -105,7 +105,8 @@ public record Capabilities public Container? SupportedChecksumAlgorithms { get; set; } /// - /// The debug adapter supports the 'restart' request. In this case a client should not implement 'restart' by terminating and relaunching the adapter but by calling the + /// The debug adapter supports the 'restart' request. In this case a client should not implement 'restart' by terminating and relaunching the adapter but by + /// calling the /// RestartRequest. /// [Optional] @@ -136,7 +137,8 @@ public record Capabilities public bool SupportTerminateDebuggee { get; set; } /// - /// The debug adapter supports the delayed loading of parts of the stack, which requires that both the 'startFrame' and 'levels' arguments and the 'totalFrames' result of the + /// The debug adapter supports the delayed loading of parts of the stack, which requires that both the 'startFrame' and 'levels' arguments and the 'totalFrames' + /// result of the /// 'StackTrace' request are supported. /// [Optional] @@ -233,17 +235,15 @@ namespace Events { [Parallel] [Method(EventNames.Capabilities, Direction.ServerToClient)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record CapabilitiesEvent : IRequest { /// /// The set of updated capabilities. /// - public Capabilities Capabilities { get; init; } + public Capabilities Capabilities { get; init; } = null!; } } } diff --git a/src/Dap.Protocol/Feature/Events/InitializedFeature.cs b/src/Dap.Protocol/Feature/Events/InitializedFeature.cs index e301e0d79..35fa55a40 100644 --- a/src/Dap.Protocol/Feature/Events/InitializedFeature.cs +++ b/src/Dap.Protocol/Feature/Events/InitializedFeature.cs @@ -9,13 +9,9 @@ namespace Events { [Parallel] [Method(EventNames.Initialized, Direction.ServerToClient)] - [ - GenerateHandler(Name = "DebugAdapterInitialized"), - GenerateHandlerMethods, - GenerateRequestMethods - ] - public record InitializedEvent : IRequest - { - } + [GenerateHandler(Name = "DebugAdapterInitialized")] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public record InitializedEvent : IRequest; } } diff --git a/src/Dap.Protocol/Feature/Events/LoadedSourceFeature.cs b/src/Dap.Protocol/Feature/Events/LoadedSourceFeature.cs index 9b86f9598..f916d033d 100644 --- a/src/Dap.Protocol/Feature/Events/LoadedSourceFeature.cs +++ b/src/Dap.Protocol/Feature/Events/LoadedSourceFeature.cs @@ -10,11 +10,9 @@ namespace Events { [Parallel] [Method(EventNames.LoadedSource, Direction.ServerToClient)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record LoadedSourceEvent : IRequest { /// @@ -25,7 +23,7 @@ public record LoadedSourceEvent : IRequest /// /// The new, changed, or removed source. /// - public Source Source { get; init; } + public Source Source { get; init; } = null!; } [StringEnum] diff --git a/src/Dap.Protocol/Feature/Events/ModuleFeature.cs b/src/Dap.Protocol/Feature/Events/ModuleFeature.cs index ce15fe09b..828af7c13 100644 --- a/src/Dap.Protocol/Feature/Events/ModuleFeature.cs +++ b/src/Dap.Protocol/Feature/Events/ModuleFeature.cs @@ -1,7 +1,7 @@ using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; -using OmniSharp.Extensions.DebugAdapter.Protocol.Models; // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.DebugAdapter.Protocol @@ -10,11 +10,9 @@ namespace Events { [Parallel] [Method(EventNames.Module, Direction.ServerToClient)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record ModuleEvent : IRequest { /// @@ -25,7 +23,7 @@ public record ModuleEvent : IRequest /// /// The new, changed, or removed module. In case of 'removed' only the module id is used. /// - public Module Module { get; init; } + public Module Module { get; init; } = null!; } [StringEnum] diff --git a/src/Dap.Protocol/Feature/Events/OutputFeature.cs b/src/Dap.Protocol/Feature/Events/OutputFeature.cs index f56e4e70c..0a5635579 100644 --- a/src/Dap.Protocol/Feature/Events/OutputFeature.cs +++ b/src/Dap.Protocol/Feature/Events/OutputFeature.cs @@ -12,11 +12,9 @@ namespace Events { [Parallel] [Method(EventNames.Output, Direction.ServerToClient)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record OutputEvent : IRequest { /// @@ -29,13 +27,13 @@ public record OutputEvent : IRequest /// /// The output to report. /// - public string Output { get; init; } + public string Output { get; init; } = null!; /// /// Support for keeping an output log organized by grouping related messages. /// Values: /// 'start': Start a new group in expanded mode. Subsequent output events are - /// members of the group and should be shown indented. + /// members of the group and should be shown indented. /// The 'output' attribute becomes the name of the group and is not indented. /// 'startCollapsed': Start a new group in collapsed mode. Subsequent output /// events are members of the group and should be shown indented (as soon as diff --git a/src/Dap.Protocol/Feature/Events/ProcessFeature.cs b/src/Dap.Protocol/Feature/Events/ProcessFeature.cs index 11fa7fc16..fb5128ac6 100644 --- a/src/Dap.Protocol/Feature/Events/ProcessFeature.cs +++ b/src/Dap.Protocol/Feature/Events/ProcessFeature.cs @@ -10,17 +10,15 @@ namespace Events { [Parallel] [Method(EventNames.Process, Direction.ServerToClient)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record ProcessEvent : IRequest { /// /// The logical name of the process. This is usually the full path to process's executable file. Example: /home/example/myproj/program.js. /// - public string Name { get; init; } + public string Name { get; init; } = null!; /// /// The system process id of the debugged process. This property will be missing for non-system processes. diff --git a/src/Dap.Protocol/Feature/Events/ProgressFeature.cs b/src/Dap.Protocol/Feature/Events/ProgressFeature.cs index 16ebd60a5..aca27ceaf 100644 --- a/src/Dap.Protocol/Feature/Events/ProgressFeature.cs +++ b/src/Dap.Protocol/Feature/Events/ProgressFeature.cs @@ -14,7 +14,7 @@ public abstract record ProgressEvent /// /// The ID that was introduced in the initial 'progressStart' event. /// - public ProgressToken ProgressId { get; init; } + public ProgressToken ProgressId { get; init; } = null!; /// /// Optional, more detailed progress message. If omitted, the previous message (if any) is used. @@ -25,17 +25,15 @@ public abstract record ProgressEvent [Serial] [Method(EventNames.ProgressStart, Direction.ServerToClient)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record ProgressStartEvent : ProgressEvent, IRequest { /// /// Mandatory (short) title of the progress reporting. Shown in the UI to describe the long running operation. /// - public string Title { get; init; } + public string Title { get; init; } = null!; /// /// The request ID that this progress report is related to. If specified a debug adapter is expected to emit @@ -62,11 +60,9 @@ public record ProgressStartEvent : ProgressEvent, IRequest [Serial] [Method(EventNames.ProgressUpdate, Direction.ServerToClient)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record ProgressUpdateEvent : ProgressEvent, IRequest { /// @@ -78,13 +74,9 @@ public record ProgressUpdateEvent : ProgressEvent, IRequest [Serial] [Method(EventNames.ProgressEnd, Direction.ServerToClient)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] - public record ProgressEndEvent : ProgressEvent, IRequest - { - } + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public record ProgressEndEvent : ProgressEvent, IRequest; } } diff --git a/src/Dap.Protocol/Feature/Requests/AttachFeature.cs b/src/Dap.Protocol/Feature/Requests/AttachFeature.cs index 2dd02d4d9..a91dc0445 100644 --- a/src/Dap.Protocol/Feature/Requests/AttachFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/AttachFeature.cs @@ -13,11 +13,9 @@ namespace Requests { [Parallel] [Method(RequestNames.Attach, Direction.ClientToServer)] - [ - GenerateHandler(Name = "Attach", AllowDerivedRequests = true), - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler(Name = "Attach", AllowDerivedRequests = true)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record AttachRequestArguments : IRequest { /// @@ -32,8 +30,6 @@ public record AttachRequestArguments : IRequest [JsonExtensionData] public IDictionary ExtensionData { get; init; } = new Dictionary(); } - public record AttachResponse - { - } + public record AttachResponse; } } diff --git a/src/Dap.Protocol/Feature/Requests/BreakpointLocationsFeature.cs b/src/Dap.Protocol/Feature/Requests/BreakpointLocationsFeature.cs index 491f0d8dc..f89850a07 100644 --- a/src/Dap.Protocol/Feature/Requests/BreakpointLocationsFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/BreakpointLocationsFeature.cs @@ -11,17 +11,15 @@ namespace Requests { [Parallel] [Method(RequestNames.BreakpointLocations, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record BreakpointLocationsArguments : IRequest { /// /// The source location of the breakpoints; either 'source.path' or 'source.reference' must be specified. /// - public Source Source { get; init; } + public Source Source { get; init; } = null!; /// /// Start line of range to search possible breakpoint locations in. If only the line is specified, the request returns all possible locations in that line. @@ -41,7 +39,8 @@ public record BreakpointLocationsArguments : IRequest - /// Optional end column of range to search possible breakpoint locations in. If no end column is given, then it is assumed to be in the last column of the end line. + /// Optional end column of range to search possible breakpoint locations in. If no end column is given, then it is assumed to be in the last column of the end + /// line. /// [Optional] public int? EndColumn { get; init; } @@ -52,7 +51,7 @@ public record BreakpointLocationsResponse /// /// Sorted set of possible breakpoint locations. /// - public Container Breakpoints { get; init; } + public Container Breakpoints { get; init; } = null!; } } diff --git a/src/Dap.Protocol/Feature/Requests/CompletionsFeature.cs b/src/Dap.Protocol/Feature/Requests/CompletionsFeature.cs index 6eb1ec66a..3298033c5 100644 --- a/src/Dap.Protocol/Feature/Requests/CompletionsFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/CompletionsFeature.cs @@ -13,11 +13,9 @@ namespace Requests { [Parallel] [Method(RequestNames.Completions, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record CompletionsArguments : IRequest { /// @@ -29,7 +27,7 @@ public record CompletionsArguments : IRequest /// /// One or more source lines.Typically this is the text a user has typed into the debug console before he asked for completion. /// - public string Text { get; init; } + public string Text { get; init; } = null!; /// /// The character position for which to determine the completion proposals. @@ -48,7 +46,7 @@ public record CompletionsResponse /// /// The possible completions for . /// - public Container Targets { get; init; } + public Container Targets { get; init; } = null!; } } @@ -62,7 +60,7 @@ public record CompletionItem /// /// The label of this completion item. By default this is also the text that is inserted when selecting this completion. /// - public string Label { get; init; } + public string Label { get; init; } = null!; /// /// If text is not falsy then it is inserted instead of the label. @@ -113,7 +111,8 @@ public record CompletionItem [JsonConverter(typeof(StringEnumConverter))] public enum CompletionItemType { - Method, Function, Constructor, Field, Variable, Class, Interface, Module, Property, Unit, Value, Enum, Keyword, Snippet, Text, Color, File, Reference, CustomColor + Method, Function, Constructor, Field, Variable, Class, Interface, Module, Property, Unit, Value, Enum, Keyword, Snippet, Text, Color, File, + Reference, CustomColor } } } diff --git a/src/Dap.Protocol/Feature/Requests/ConfigurationDoneFeature.cs b/src/Dap.Protocol/Feature/Requests/ConfigurationDoneFeature.cs index 3ccd14f6c..f67e050e6 100644 --- a/src/Dap.Protocol/Feature/Requests/ConfigurationDoneFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/ConfigurationDoneFeature.cs @@ -9,17 +9,11 @@ namespace Requests { [Parallel] [Method(RequestNames.ConfigurationDone, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] - public record ConfigurationDoneArguments : IRequest - { - } + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public record ConfigurationDoneArguments : IRequest; - public record ConfigurationDoneResponse - { - } + public record ConfigurationDoneResponse; } } diff --git a/src/Dap.Protocol/Feature/Requests/DataBreakpointInfoFeature.cs b/src/Dap.Protocol/Feature/Requests/DataBreakpointInfoFeature.cs index d1b02bbf1..30972e614 100644 --- a/src/Dap.Protocol/Feature/Requests/DataBreakpointInfoFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/DataBreakpointInfoFeature.cs @@ -11,11 +11,9 @@ namespace Requests { [Parallel] [Method(RequestNames.DataBreakpointInfo, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record DataBreakpointInfoArguments : IRequest { /// @@ -27,7 +25,7 @@ public record DataBreakpointInfoArguments : IRequest /// /// The name of the Variable's child to obtain data breakpoint information for. If variableReference isn’t provided, this can be an expression. /// - public string Name { get; init; } + public string Name { get; init; } = null!; } public record DataBreakpointInfoResponse @@ -35,12 +33,12 @@ public record DataBreakpointInfoResponse /// /// An identifier for the data on which a data breakpoint can be registered with the setDataBreakpoints request or null if no data breakpoint is available. /// - public string DataId { get; init; } + public string DataId { get; init; } = null!; /// /// UI string that describes on what data the breakpoint is set on or why a data breakpoint is not available. /// - public string Description { get; init; } + public string Description { get; init; } = null!; /// /// Optional attribute listing the available access types for a potential data breakpoint.A UI frontend could surface this information. diff --git a/src/Dap.Protocol/Feature/Requests/DisassembleFeature.cs b/src/Dap.Protocol/Feature/Requests/DisassembleFeature.cs index 32ff4087b..e28e68d2f 100644 --- a/src/Dap.Protocol/Feature/Requests/DisassembleFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/DisassembleFeature.cs @@ -11,17 +11,15 @@ namespace Requests { [Parallel] [Method(RequestNames.Disassemble, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record DisassembleArguments : IRequest { /// /// Memory reference to the base location containing the instructions to disassemble. /// - public string MemoryReference { get; init; } + public string MemoryReference { get; init; } = null!; /// /// Optional offset(in bytes) to be applied to the reference location before disassembling.Can be negative. @@ -37,7 +35,8 @@ public record DisassembleArguments : IRequest public long? InstructionOffset { get; init; } /// - /// Number of instructions to disassemble starting at the specified location and offset.An adapter must return exactly this number of instructions - any unavailable instructions + /// Number of instructions to disassemble starting at the specified location and offset.An adapter must return exactly this number of instructions - any + /// unavailable instructions /// should be replaced with an implementation-defined 'invalid instruction' value. /// public long InstructionCount { get; init; } @@ -54,7 +53,7 @@ public record DisassembleResponse /// /// The list of disassembled instructions. /// - public Container Instructions { get; init; } + public Container Instructions { get; init; } = null!; } } @@ -69,7 +68,7 @@ public record DisassembledInstruction /// /// The address of the instruction. Treated as a hex value if prefixed with '0x', or as a decimal value otherwise. /// - public string Address { get; init; } + public string Address { get; init; } = null!; /// /// Optional raw bytes representing the instruction and its operands, in an implementation-defined format. @@ -80,7 +79,7 @@ public record DisassembledInstruction /// /// Text representing the instruction and its operands, in an implementation-defined format. /// - public string Instruction { get; init; } + public string Instruction { get; init; } = null!; /// /// Name of the symbol that corresponds with the location of this instruction, if any. @@ -89,7 +88,8 @@ public record DisassembledInstruction public string? Symbol { get; init; } /// - /// Source location that corresponds to this instruction, if any. Should always be set (if available) on the first instruction returned, but can be omitted afterwards if this + /// Source location that corresponds to this instruction, if any. Should always be set (if available) on the first instruction returned, but can be omitted + /// afterwards if this /// instruction maps to the same source file as the previous instruction. /// [Optional] diff --git a/src/Dap.Protocol/Feature/Requests/DisconnectFeature.cs b/src/Dap.Protocol/Feature/Requests/DisconnectFeature.cs index 0da05095b..3da9dc03c 100644 --- a/src/Dap.Protocol/Feature/Requests/DisconnectFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/DisconnectFeature.cs @@ -10,11 +10,9 @@ namespace Requests { [Parallel] [Method(RequestNames.Disconnect, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record DisconnectArguments : IRequest { /// @@ -32,8 +30,6 @@ public record DisconnectArguments : IRequest public bool TerminateDebuggee { get; init; } } - public record DisconnectResponse - { - } + public record DisconnectResponse; } } diff --git a/src/Dap.Protocol/Feature/Requests/EvaluateFeature.cs b/src/Dap.Protocol/Feature/Requests/EvaluateFeature.cs index e6b6848af..9d4820f90 100644 --- a/src/Dap.Protocol/Feature/Requests/EvaluateFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/EvaluateFeature.cs @@ -11,17 +11,15 @@ namespace Requests { [Parallel] [Method(RequestNames.Evaluate, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record EvaluateArguments : IRequest { /// /// The expression to evaluate. /// - public string Expression { get; init; } + public string Expression { get; init; } = null!; /// /// Evaluate the expression in the scope of this stack frame. If not specified, the expression is evaluated in the global scope. @@ -61,7 +59,7 @@ public record EvaluateResponse /// /// The result of the evaluate request. /// - public string Result { get; init; } + public string Result { get; init; } = null!; /// /// The optional type of the evaluate result. @@ -95,7 +93,8 @@ public record EvaluateResponse public long? IndexedVariables { get; init; } /// - /// Memory reference to a location appropriate for this result.For pointer type eval results, this is generally a reference to the memory address contained in the pointer. + /// Memory reference to a location appropriate for this result.For pointer type eval results, this is generally a reference to the memory address contained in the + /// pointer. /// [Optional] public string? MemoryReference { get; init; } diff --git a/src/Dap.Protocol/Feature/Requests/ExceptionInfoFeature.cs b/src/Dap.Protocol/Feature/Requests/ExceptionInfoFeature.cs index c734e3c03..8a664d585 100644 --- a/src/Dap.Protocol/Feature/Requests/ExceptionInfoFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/ExceptionInfoFeature.cs @@ -11,11 +11,9 @@ namespace Requests { [Parallel] [Method(RequestNames.ExceptionInfo, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record ExceptionInfoArguments : IRequest { /// @@ -29,7 +27,7 @@ public record ExceptionInfoResponse /// /// ID of the exception that was thrown. /// - public string ExceptionId { get; init; } + public string ExceptionId { get; init; } = null!; /// /// Descriptive text for the exception provided by the debug adapter. diff --git a/src/Dap.Protocol/Feature/Requests/GotoFeature.cs b/src/Dap.Protocol/Feature/Requests/GotoFeature.cs index 1c9c48a0b..24898294e 100644 --- a/src/Dap.Protocol/Feature/Requests/GotoFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/GotoFeature.cs @@ -9,11 +9,9 @@ namespace Requests { [Parallel] [Method(RequestNames.Goto, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record GotoArguments : IRequest { /// @@ -27,8 +25,6 @@ public record GotoArguments : IRequest public long TargetId { get; init; } } - public record GotoResponse - { - } + public record GotoResponse; } } diff --git a/src/Dap.Protocol/Feature/Requests/GotoTargetsFeature.cs b/src/Dap.Protocol/Feature/Requests/GotoTargetsFeature.cs index 472d7bc76..2fbf84ef2 100644 --- a/src/Dap.Protocol/Feature/Requests/GotoTargetsFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/GotoTargetsFeature.cs @@ -11,17 +11,15 @@ namespace Requests { [Parallel] [Method(RequestNames.GotoTargets, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record GotoTargetsArguments : IRequest { /// /// The source location for which the goto targets are determined. /// - public Source Source { get; init; } + public Source Source { get; init; } = null!; /// /// The line location for which the goto targets are determined. @@ -40,7 +38,7 @@ public record GotoTargetsResponse /// /// The possible goto targets of the specified location. /// - public Container Targets { get; init; } + public Container Targets { get; init; } = null!; } } @@ -60,7 +58,7 @@ public record GotoTarget /// /// The name of the goto target (shown in the UI). /// - public string Label { get; init; } + public string Label { get; init; } = null!; /// /// The line of the goto target. diff --git a/src/Dap.Protocol/Feature/Requests/InitializeRequestFeature.cs b/src/Dap.Protocol/Feature/Requests/InitializeRequestFeature.cs index 07df4b3e6..a8c4e645c 100644 --- a/src/Dap.Protocol/Feature/Requests/InitializeRequestFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/InitializeRequestFeature.cs @@ -12,18 +12,17 @@ namespace Requests { [Parallel] [Method(RequestNames.Initialize, Direction.ClientToServer)] - [ - GenerateHandler(Name = "DebugAdapterInitialize"), - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler(Name = "DebugAdapterInitialize")] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record InitializeRequestArguments : IRequest, IInitializeRequestArguments { /// /// The ID of the(frontend) client using this adapter. /// - [Optional, JsonProperty("clientID")] + [Optional] + [JsonProperty("clientID")] public string? ClientId { get; set; } /// @@ -102,8 +101,6 @@ public record InitializeRequestArguments : IRequest, IInitia public bool SupportsInvalidatedEvent { get; set; } } - public record InitializeResponse : Capabilities - { - } + public record InitializeResponse : Capabilities; } } diff --git a/src/Dap.Protocol/Feature/Requests/LaunchFeature.cs b/src/Dap.Protocol/Feature/Requests/LaunchFeature.cs index d57aa0a5d..a8e793ed7 100644 --- a/src/Dap.Protocol/Feature/Requests/LaunchFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/LaunchFeature.cs @@ -13,11 +13,9 @@ namespace Requests { [Parallel] [Method(RequestNames.Launch, Direction.ClientToServer)] - [ - GenerateHandler(Name = "Launch", AllowDerivedRequests = true), - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler(Name = "Launch", AllowDerivedRequests = true)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record LaunchRequestArguments : IRequest { /// @@ -38,8 +36,6 @@ public record LaunchRequestArguments : IRequest [JsonExtensionData] public IDictionary ExtensionData { get; init; } = new Dictionary(); } - public record LaunchResponse - { - } + public record LaunchResponse; } } diff --git a/src/Dap.Protocol/Feature/Requests/LoadedSourcesFeature.cs b/src/Dap.Protocol/Feature/Requests/LoadedSourcesFeature.cs index cd6eaac6d..74d5fd822 100644 --- a/src/Dap.Protocol/Feature/Requests/LoadedSourcesFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/LoadedSourcesFeature.cs @@ -10,21 +10,17 @@ namespace Requests { [Parallel] [Method(RequestNames.LoadedSources, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] - public record LoadedSourcesArguments : IRequest - { - } + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public record LoadedSourcesArguments : IRequest; public record LoadedSourcesResponse { /// /// Set of loaded sources. /// - public Container Sources { get; init; } + public Container Sources { get; init; } = null!; } } diff --git a/src/Dap.Protocol/Feature/Requests/ModulesFeature.cs b/src/Dap.Protocol/Feature/Requests/ModulesFeature.cs index 42d0f5ed6..b6bb7251d 100644 --- a/src/Dap.Protocol/Feature/Requests/ModulesFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/ModulesFeature.cs @@ -11,11 +11,9 @@ namespace Requests { [Parallel] [Method(RequestNames.Modules, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record ModulesArguments : IRequest { /// @@ -36,7 +34,7 @@ public record ModulesResponse /// /// All modules or range of modules. /// - public Container Modules { get; init; } + public Container Modules { get; init; } = null!; /// /// The total number of modules available. diff --git a/src/Dap.Protocol/Feature/Requests/NextFeature.cs b/src/Dap.Protocol/Feature/Requests/NextFeature.cs index b053b23a4..32f8e94bd 100644 --- a/src/Dap.Protocol/Feature/Requests/NextFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/NextFeature.cs @@ -11,11 +11,9 @@ namespace Requests { [Parallel] [Method(RequestNames.Next, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record NextArguments : IRequest { /// @@ -30,8 +28,6 @@ public record NextArguments : IRequest public SteppingGranularity Granularity { get; init; } } - public record NextResponse - { - } + public record NextResponse; } } diff --git a/src/Dap.Protocol/Feature/Requests/PauseFeature.cs b/src/Dap.Protocol/Feature/Requests/PauseFeature.cs index e1a34b884..68e3a0ca3 100644 --- a/src/Dap.Protocol/Feature/Requests/PauseFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/PauseFeature.cs @@ -9,11 +9,9 @@ namespace Requests { [Parallel] [Method(RequestNames.Pause, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record PauseArguments : IRequest { /// @@ -22,8 +20,6 @@ public record PauseArguments : IRequest public long ThreadId { get; init; } } - public record PauseResponse - { - } + public record PauseResponse; } } diff --git a/src/Dap.Protocol/Feature/Requests/ReadMemoryFeature.cs b/src/Dap.Protocol/Feature/Requests/ReadMemoryFeature.cs index 6abfd2947..b5aaa375f 100644 --- a/src/Dap.Protocol/Feature/Requests/ReadMemoryFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/ReadMemoryFeature.cs @@ -10,17 +10,15 @@ namespace Requests { [Parallel] [Method(RequestNames.ReadMemory, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record ReadMemoryArguments : IRequest { /// /// Memory reference to the base location from which data should be read. /// - public string MemoryReference { get; init; } + public string MemoryReference { get; init; } = null!; /// /// Optional offset(in bytes) to be applied to the reference location before reading data.Can be negative. @@ -40,10 +38,11 @@ public record ReadMemoryResponse /// /// The address of the first byte of data returned.Treated as a hex value if prefixed with '0x', or as a decimal value otherwise. /// - public string Address { get; init; } + public string Address { get; init; } = null!; /// - /// The number of unreadable bytes encountered after the last successfully read byte. This can be used to determine the number of bytes that must be skipped before a subsequent + /// The number of unreadable bytes encountered after the last successfully read byte. This can be used to determine the number of bytes that must be skipped before + /// a subsequent /// 'readMemory' request will succeed. /// [Optional] diff --git a/src/Dap.Protocol/Feature/Requests/RestartFeature.cs b/src/Dap.Protocol/Feature/Requests/RestartFeature.cs index 4c2ba7803..e8eacee83 100644 --- a/src/Dap.Protocol/Feature/Requests/RestartFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/RestartFeature.cs @@ -9,17 +9,11 @@ namespace Requests { [Parallel] [Method(RequestNames.Restart, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] - public record RestartArguments : IRequest - { - } + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public record RestartArguments : IRequest; - public record RestartResponse - { - } + public record RestartResponse; } } diff --git a/src/Dap.Protocol/Feature/Requests/RestartFrameFeature.cs b/src/Dap.Protocol/Feature/Requests/RestartFrameFeature.cs index b39262630..ba8641736 100644 --- a/src/Dap.Protocol/Feature/Requests/RestartFrameFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/RestartFrameFeature.cs @@ -9,11 +9,9 @@ namespace Requests { [Parallel] [Method(RequestNames.RestartFrame, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record RestartFrameArguments : IRequest { /// @@ -22,8 +20,6 @@ public record RestartFrameArguments : IRequest public long FrameId { get; init; } } - public record RestartFrameResponse - { - } + public record RestartFrameResponse; } } diff --git a/src/Dap.Protocol/Feature/Requests/ReverseContinueFeature.cs b/src/Dap.Protocol/Feature/Requests/ReverseContinueFeature.cs index cfb892f5b..4e1d0980a 100644 --- a/src/Dap.Protocol/Feature/Requests/ReverseContinueFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/ReverseContinueFeature.cs @@ -9,11 +9,9 @@ namespace Requests { [Parallel] [Method(RequestNames.ReverseContinue, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record ReverseContinueArguments : IRequest { /// @@ -22,8 +20,6 @@ public record ReverseContinueArguments : IRequest public long ThreadId { get; init; } } - public record ReverseContinueResponse - { - } + public record ReverseContinueResponse; } } diff --git a/src/Dap.Protocol/Feature/Requests/RunInTerminalFeature.cs b/src/Dap.Protocol/Feature/Requests/RunInTerminalFeature.cs index 139173497..15a9b7aa3 100644 --- a/src/Dap.Protocol/Feature/Requests/RunInTerminalFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/RunInTerminalFeature.cs @@ -14,11 +14,9 @@ namespace Requests { [Parallel] [Method(RequestNames.RunInTerminal, Direction.ServerToClient)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record RunInTerminalArguments : IRequest { /// @@ -36,12 +34,12 @@ public record RunInTerminalArguments : IRequest /// /// Working directory of the command. /// - public string Cwd { get; init; } + public string Cwd { get; init; } = null!; /// /// List of arguments.The first argument is the command to run. /// - public Container Args { get; init; } + public Container Args { get; init; } = null!; /// /// Environment key-value pairs that are added to or removed from the default environment. diff --git a/src/Dap.Protocol/Feature/Requests/ScopesFeature.cs b/src/Dap.Protocol/Feature/Requests/ScopesFeature.cs index 21930d92b..73315a52b 100644 --- a/src/Dap.Protocol/Feature/Requests/ScopesFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/ScopesFeature.cs @@ -11,11 +11,9 @@ namespace Requests { [Parallel] [Method(RequestNames.Scopes, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record ScopesArguments : IRequest { /// @@ -29,7 +27,7 @@ public record ScopesResponse /// /// The scopes of the stackframe.If the array has length zero, there are no scopes available. /// - public Container Scopes { get; init; } + public Container Scopes { get; init; } = null!; } } @@ -43,7 +41,7 @@ public record Scope /// /// Name of the scope such as 'Arguments', 'Locals', or 'Registers'. This string is shown in the UI as is and can be translated. /// - public string Name { get; init; } + public string Name { get; init; } = null!; /// /// An optional hint for how to present this scope in the UI. If this attribute is missing, the scope is shown with a generic UI. diff --git a/src/Dap.Protocol/Feature/Requests/SetBreakpointsFeature.cs b/src/Dap.Protocol/Feature/Requests/SetBreakpointsFeature.cs index eb8002949..cf498fe37 100644 --- a/src/Dap.Protocol/Feature/Requests/SetBreakpointsFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/SetBreakpointsFeature.cs @@ -12,17 +12,15 @@ namespace Requests { [Parallel] [Method(RequestNames.SetBreakpoints, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record SetBreakpointsArguments : IRequest { /// /// The source location of the breakpoints; either 'source.path' or 'source.reference' must be specified. /// - public Source Source { get; init; } + public Source Source { get; init; } = null!; /// /// The code locations of the breakpoints. @@ -47,9 +45,10 @@ public record SetBreakpointsArguments : IRequest public record SetBreakpointsResponse { /// - /// Information about the breakpoints.The array elements are in the same order as the elements of the 'breakpoints' (or the deprecated 'lines') array in the arguments. + /// Information about the breakpoints.The array elements are in the same order as the elements of the 'breakpoints' (or the deprecated 'lines') array in the + /// arguments. /// - public Container Breakpoints { get; init; } + public Container Breakpoints { get; init; } = null!; } } } diff --git a/src/Dap.Protocol/Feature/Requests/SetDataBreakpointsFeature.cs b/src/Dap.Protocol/Feature/Requests/SetDataBreakpointsFeature.cs index c0c62005b..a6f9408da 100644 --- a/src/Dap.Protocol/Feature/Requests/SetDataBreakpointsFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/SetDataBreakpointsFeature.cs @@ -10,17 +10,15 @@ namespace Requests { [Parallel] [Method(RequestNames.SetDataBreakpoints, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record SetDataBreakpointsArguments : IRequest { /// /// The contents of this array replaces all existing data breakpoints. An empty array clears all data breakpoints. /// - public Container Breakpoints { get; init; } + public Container Breakpoints { get; init; } = null!; } public record SetDataBreakpointsResponse @@ -28,7 +26,7 @@ public record SetDataBreakpointsResponse /// /// Information about the data breakpoints.The array elements correspond to the elements of the input argument 'breakpoints' array. /// - public Container Breakpoints { get; init; } + public Container Breakpoints { get; init; } = null!; } } } diff --git a/src/Dap.Protocol/Feature/Requests/SetExceptionBreakpointsFeature.cs b/src/Dap.Protocol/Feature/Requests/SetExceptionBreakpointsFeature.cs index 0e4c62d33..429073517 100644 --- a/src/Dap.Protocol/Feature/Requests/SetExceptionBreakpointsFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/SetExceptionBreakpointsFeature.cs @@ -13,24 +13,23 @@ namespace Requests { [Parallel] [Method(RequestNames.SetExceptionBreakpoints, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record SetExceptionBreakpointsArguments : IRequest { /// /// IDs of checked exception options.The set of IDs is returned via the 'exceptionBreakpointFilters' capability. /// - public Container Filters { get; init; } + public Container Filters { get; init; } = null!; + /// - /// Set of exception filters and their options. The set of all possible - /// exception filters is defined by the 'exceptionBreakpointFilters' - /// capability. This attribute is only honored by a debug adapter if the - /// capability 'supportsExceptionFilterOptions' is true. The 'filter' and - /// 'filterOptions' sets are additive. - /// + /// Set of exception filters and their options. The set of all possible + /// exception filters is defined by the 'exceptionBreakpointFilters' + /// capability. This attribute is only honored by a debug adapter if the + /// capability 'supportsExceptionFilterOptions' is true. The 'filter' and + /// 'filterOptions' sets are additive. + /// [Optional] public Container? FilterOptions { get; init; } @@ -41,9 +40,7 @@ public record SetExceptionBreakpointsArguments : IRequest? ExceptionOptions { get; init; } } - public record SetExceptionBreakpointsResponse - { - } + public record SetExceptionBreakpointsResponse; } namespace Models @@ -55,7 +52,8 @@ namespace Models public record ExceptionOptions { /// - /// A path that selects a single or multiple exceptions in a tree. If 'path' is missing, the whole tree is selected. By convention the first segment of the path is a category that is + /// A path that selects a single or multiple exceptions in a tree. If 'path' is missing, the whole tree is selected. By convention the first segment of the path is + /// a category that is /// used to group exceptions in the UI. /// [Optional] @@ -68,7 +66,8 @@ public record ExceptionOptions } /// - /// An ExceptionPathSegment represents a segment in a path that is used to match leafs or nodes in a tree of exceptions.If a segment consists of more than one name, it matches the + /// An ExceptionPathSegment represents a segment in a path that is used to match leafs or nodes in a tree of exceptions.If a segment consists of more than one + /// name, it matches the /// names provided if ‘negate’ is false or missing or it matches anything except the names provided if ‘negate’ is true. /// public record ExceptionPathSegment @@ -82,7 +81,7 @@ public record ExceptionPathSegment /// /// Depending on the value of 'negate' the names that should match or not match. /// - public Container Names { get; init; } + public Container Names { get; init; } = null!; } /// diff --git a/src/Dap.Protocol/Feature/Requests/SetExpressionFeature.cs b/src/Dap.Protocol/Feature/Requests/SetExpressionFeature.cs index 4bbcd7eae..036565e16 100644 --- a/src/Dap.Protocol/Feature/Requests/SetExpressionFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/SetExpressionFeature.cs @@ -11,22 +11,20 @@ namespace Requests { [Parallel] [Method(RequestNames.SetExpression, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record SetExpressionArguments : IRequest { /// /// The l-value expression to assign to. /// - public string Expression { get; init; } + public string Expression { get; init; } = null!; /// /// The value expression to assign to the l-value expression. /// - public string Value { get; init; } + public string Value { get; init; } = null!; /// /// Evaluate the expressions in the scope of this stack frame. If not specified, the expressions are evaluated in the global scope. @@ -46,7 +44,7 @@ public record SetExpressionResponse /// /// The new value of the expression. /// - public string Value { get; init; } + public string Value { get; init; } = null!; /// /// The optional type of the value. diff --git a/src/Dap.Protocol/Feature/Requests/SetFunctionBreakpointsFeature.cs b/src/Dap.Protocol/Feature/Requests/SetFunctionBreakpointsFeature.cs index 89ffd7b5d..7e8a52843 100644 --- a/src/Dap.Protocol/Feature/Requests/SetFunctionBreakpointsFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/SetFunctionBreakpointsFeature.cs @@ -11,17 +11,15 @@ namespace Requests { [Parallel] [Method(RequestNames.SetFunctionBreakpoints, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record SetFunctionBreakpointsArguments : IRequest { /// /// The function names of the breakpoints. /// - public Container Breakpoints { get; init; } + public Container Breakpoints { get; init; } = null!; } public record SetFunctionBreakpointsResponse @@ -29,7 +27,7 @@ public record SetFunctionBreakpointsResponse /// /// Information about the breakpoints.The array elements correspond to the elements of the 'breakpoints' array. /// - public Container Breakpoints { get; init; } + public Container Breakpoints { get; init; } = null!; } } @@ -44,7 +42,7 @@ public record FunctionBreakpoint /// /// The name of the function. /// - public string Name { get; init; } + public string Name { get; init; } = null!; /// /// An optional expression for conditional breakpoints. diff --git a/src/Dap.Protocol/Feature/Requests/SetInstructionBreakpointsFeature.cs b/src/Dap.Protocol/Feature/Requests/SetInstructionBreakpointsFeature.cs index 059ec1780..e43d569cc 100644 --- a/src/Dap.Protocol/Feature/Requests/SetInstructionBreakpointsFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/SetInstructionBreakpointsFeature.cs @@ -10,17 +10,15 @@ namespace Requests { [Parallel] [Method(RequestNames.SetInstructionBreakpoints, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record SetInstructionBreakpointsArguments : IRequest { /// /// The contents of this array replaces all existing data breakpoints. An empty array clears all data breakpoints. /// - public Container Breakpoints { get; init; } + public Container Breakpoints { get; init; } = null!; } public record SetInstructionBreakpointsResponse @@ -28,7 +26,7 @@ public record SetInstructionBreakpointsResponse /// /// Information about the data breakpoints.The array elements correspond to the elements of the input argument 'breakpoints' array. /// - public Container Breakpoints { get; init; } + public Container Breakpoints { get; init; } = null!; } } diff --git a/src/Dap.Protocol/Feature/Requests/SetVariableFeature.cs b/src/Dap.Protocol/Feature/Requests/SetVariableFeature.cs index 86c0ff019..3a60c46e1 100644 --- a/src/Dap.Protocol/Feature/Requests/SetVariableFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/SetVariableFeature.cs @@ -11,11 +11,9 @@ namespace Requests { [Parallel] [Method(RequestNames.SetVariable, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record SetVariableArguments : IRequest { /// @@ -26,12 +24,12 @@ public record SetVariableArguments : IRequest /// /// The name of the variable in the container. /// - public string Name { get; init; } + public string Name { get; init; } = null!; /// /// The value of the variable. /// - public string Value { get; init; } + public string Value { get; init; } = null!; /// /// Specifies details on how to format the response value. @@ -45,7 +43,7 @@ public record SetVariableResponse /// /// The new value of the variable. /// - public string Value { get; init; } + public string Value { get; init; } = null!; /// /// The type of the new value.Typically shown in the UI when hovering over the value. diff --git a/src/Dap.Protocol/Feature/Requests/SourceFeature.cs b/src/Dap.Protocol/Feature/Requests/SourceFeature.cs index 5f536cb4b..c93f266c1 100644 --- a/src/Dap.Protocol/Feature/Requests/SourceFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/SourceFeature.cs @@ -11,11 +11,9 @@ namespace Requests { [Parallel] [Method(RequestNames.Source, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record SourceArguments : IRequest { /// @@ -25,7 +23,8 @@ public record SourceArguments : IRequest public Source? Source { get; init; } /// - /// The reference to the source.This is the same as source.sourceReference.This is provided for backward compatibility since old backends do not understand the 'source' attribute. + /// The reference to the source.This is the same as source.sourceReference.This is provided for backward compatibility since old backends do not understand the + /// 'source' attribute. /// public long SourceReference { get; init; } } @@ -35,7 +34,7 @@ public record SourceResponse /// /// Content of the source reference. /// - public string Content { get; init; } + public string Content { get; init; } = null!; /// /// Optional content type(mime type) of the source. diff --git a/src/Dap.Protocol/Feature/Requests/StepBackFeature.cs b/src/Dap.Protocol/Feature/Requests/StepBackFeature.cs index e10fc90fa..a18e8b912 100644 --- a/src/Dap.Protocol/Feature/Requests/StepBackFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/StepBackFeature.cs @@ -11,11 +11,9 @@ namespace Requests { [Parallel] [Method(RequestNames.StepBack, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record StepBackArguments : IRequest { /// @@ -30,9 +28,7 @@ public record StepBackArguments : IRequest public SteppingGranularity? Granularity { get; init; } } - public record StepBackResponse - { - } + public record StepBackResponse; } namespace Models diff --git a/src/Dap.Protocol/Feature/Requests/StepInFeature.cs b/src/Dap.Protocol/Feature/Requests/StepInFeature.cs index de48539ab..11ba85a4b 100644 --- a/src/Dap.Protocol/Feature/Requests/StepInFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/StepInFeature.cs @@ -11,11 +11,9 @@ namespace Requests { [Parallel] [Method(RequestNames.StepIn, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record StepInArguments : IRequest { /// @@ -36,9 +34,7 @@ public record StepInArguments : IRequest public SteppingGranularity? Granularity { get; init; } } - public record StepInResponse - { - } + public record StepInResponse; } namespace Models diff --git a/src/Dap.Protocol/Feature/Requests/StepInTargetsFeature.cs b/src/Dap.Protocol/Feature/Requests/StepInTargetsFeature.cs index 340f9fa3d..828ed4b04 100644 --- a/src/Dap.Protocol/Feature/Requests/StepInTargetsFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/StepInTargetsFeature.cs @@ -10,11 +10,9 @@ namespace Requests { [Parallel] [Method(RequestNames.StepInTargets, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record StepInTargetsArguments : IRequest { /// @@ -47,7 +45,7 @@ public record StepInTarget /// /// The name of the stepIn target (shown in the UI). /// - public string Label { get; init; } + public string Label { get; init; } = null!; } } } diff --git a/src/Dap.Protocol/Feature/Requests/StepOutFeature.cs b/src/Dap.Protocol/Feature/Requests/StepOutFeature.cs index eb55141d5..9bc8567eb 100644 --- a/src/Dap.Protocol/Feature/Requests/StepOutFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/StepOutFeature.cs @@ -11,11 +11,9 @@ namespace Requests { [Parallel] [Method(RequestNames.StepOut, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record StepOutArguments : IRequest { /// @@ -30,9 +28,7 @@ public record StepOutArguments : IRequest public SteppingGranularity? Granularity { get; init; } } - public record StepOutResponse - { - } + public record StepOutResponse; } namespace Models diff --git a/src/Dap.Protocol/Feature/Requests/TerminateFeature.cs b/src/Dap.Protocol/Feature/Requests/TerminateFeature.cs index 8edb397ed..f15f4d256 100644 --- a/src/Dap.Protocol/Feature/Requests/TerminateFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/TerminateFeature.cs @@ -10,11 +10,9 @@ namespace Requests { [Parallel] [Method(RequestNames.Terminate, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record TerminateArguments : IRequest { /// @@ -24,9 +22,7 @@ public record TerminateArguments : IRequest public bool Restart { get; init; } } - public record TerminateResponse - { - } + public record TerminateResponse; } namespace Models diff --git a/src/Dap.Protocol/Feature/Requests/TerminateThreadsFeature.cs b/src/Dap.Protocol/Feature/Requests/TerminateThreadsFeature.cs index 5677d8e1e..592e19cff 100644 --- a/src/Dap.Protocol/Feature/Requests/TerminateThreadsFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/TerminateThreadsFeature.cs @@ -11,11 +11,9 @@ namespace Requests { [Parallel] [Method(RequestNames.TerminateThreads, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] public record TerminateThreadsArguments : IRequest { /// @@ -25,9 +23,7 @@ public record TerminateThreadsArguments : IRequest public Container? ThreadIds { get; init; } } - public record TerminateThreadsResponse - { - } + public record TerminateThreadsResponse; } namespace Models diff --git a/src/Dap.Protocol/Feature/Requests/ThreadsFeature.cs b/src/Dap.Protocol/Feature/Requests/ThreadsFeature.cs index 1975a2b2e..498ccf17b 100644 --- a/src/Dap.Protocol/Feature/Requests/ThreadsFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/ThreadsFeature.cs @@ -10,14 +10,10 @@ namespace Requests { [Parallel] [Method(RequestNames.Threads, Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods, - GenerateRequestMethods - ] - public record ThreadsArguments : IRequest - { - } + [GenerateHandler] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public record ThreadsArguments : IRequest; public record ThreadsResponse { diff --git a/src/Dap.Protocol/IDebugAdapterProtocolProxy.cs b/src/Dap.Protocol/IDebugAdapterProtocolProxy.cs index 7bab6b7fc..5d8f4921e 100644 --- a/src/Dap.Protocol/IDebugAdapterProtocolProxy.cs +++ b/src/Dap.Protocol/IDebugAdapterProtocolProxy.cs @@ -14,33 +14,60 @@ public interface IDebugAdapterProtocolProxy : IResponseRouter, IDebugAdapterProt { } - abstract class DebugAdapterProtocolProxy : IDebugAdapterProtocolProxy + internal abstract class DebugAdapterProtocolProxy : IDebugAdapterProtocolProxy { private readonly IResponseRouter _responseRouter; protected readonly IResolverContext ResolverContext; private readonly IDebugAdapterProtocolSettings _debugAdapterProtocolSettings; - public DebugAdapterProtocolProxy(IResponseRouter requestRouter, IResolverContext resolverContext, IDebugAdapterProtocolSettings debugAdapterProtocolSettings) + public DebugAdapterProtocolProxy( + IResponseRouter requestRouter, IResolverContext resolverContext, IDebugAdapterProtocolSettings debugAdapterProtocolSettings + ) { _responseRouter = requestRouter; ResolverContext = resolverContext; _debugAdapterProtocolSettings = debugAdapterProtocolSettings; } - public void SendNotification(string method) => _responseRouter.SendNotification(method); + public void SendNotification(string method) + { + _responseRouter.SendNotification(method); + } - public void SendNotification(string method, T @params) => _responseRouter.SendNotification(method, @params); + public void SendNotification(string method, T @params) + { + _responseRouter.SendNotification(method, @params); + } - public void SendNotification(IRequest request) => _responseRouter.SendNotification(request); + public void SendNotification(IRequest request) + { + _responseRouter.SendNotification(request); + } - public IResponseRouterReturns SendRequest(string method, T @params) => _responseRouter.SendRequest(method, @params); + public IResponseRouterReturns SendRequest(string method, T @params) + { + return _responseRouter.SendRequest(method, @params); + } - public IResponseRouterReturns SendRequest(string method) => _responseRouter.SendRequest(method); + public IResponseRouterReturns SendRequest(string method) + { + return _responseRouter.SendRequest(method); + } + + public Task SendRequest(IRequest request, CancellationToken cancellationToken) + { + return _responseRouter.SendRequest(request, cancellationToken); + } - public Task SendRequest(IRequest request, CancellationToken cancellationToken) => _responseRouter.SendRequest(request, cancellationToken); + bool IResponseRouter.TryGetRequest(long id, [NotNullWhen(true)] out string? method, [NotNullWhen(true)] out TaskCompletionSource? pendingTask) + { + return _responseRouter.TryGetRequest(id, out method, out pendingTask); + } - bool IResponseRouter.TryGetRequest(long id, [NotNullWhen(true)] out string method, [NotNullWhen(true)] out TaskCompletionSource pendingTask) => _responseRouter.TryGetRequest(id, out method, out pendingTask); - object IServiceProvider.GetService(Type serviceType) => ResolverContext.GetService(serviceType); + object IServiceProvider.GetService(Type serviceType) + { + return ResolverContext.GetService(serviceType); + } public InitializeRequestArguments ClientSettings => _debugAdapterProtocolSettings.ClientSettings; public InitializeResponse ServerSettings => _debugAdapterProtocolSettings.ServerSettings; diff --git a/src/Dap.Protocol/Models/Checksum.cs b/src/Dap.Protocol/Models/Checksum.cs index 00f35e175..26d3a5cdc 100644 --- a/src/Dap.Protocol/Models/Checksum.cs +++ b/src/Dap.Protocol/Models/Checksum.cs @@ -16,6 +16,6 @@ public record Checksum /// Value of the checksum. /// [JsonProperty("checksum")] - public string Value { get; init; } + public string Value { get; init; } = null!; } } diff --git a/src/Dap.Protocol/Models/ColumnDescriptor.cs b/src/Dap.Protocol/Models/ColumnDescriptor.cs index 83456b904..d3c705e2e 100644 --- a/src/Dap.Protocol/Models/ColumnDescriptor.cs +++ b/src/Dap.Protocol/Models/ColumnDescriptor.cs @@ -11,12 +11,12 @@ public record ColumnDescriptor /// /// Name of the attribute rendered in this column. /// - public string AttributeName { get; init; } + public string AttributeName { get; init; } = null!; /// /// Header UI label of column. /// - public string Label { get; init; } + public string Label { get; init; } = null!; /// /// Format to use for the rendered values in this column. TBD how the format strings looks like. diff --git a/src/Dap.Protocol/Models/DataBreakpoint.cs b/src/Dap.Protocol/Models/DataBreakpoint.cs index 34cb4fd51..42e58a63f 100644 --- a/src/Dap.Protocol/Models/DataBreakpoint.cs +++ b/src/Dap.Protocol/Models/DataBreakpoint.cs @@ -10,7 +10,7 @@ public record DataBreakpoint /// /// An id representing the data. This id is returned from the dataBreakpointInfo request. /// - public string DataId { get; init; } + public string DataId { get; init; } = null!; /// /// The access type of the data. diff --git a/src/Dap.Protocol/Models/ExceptionBreakpointsFilter.cs b/src/Dap.Protocol/Models/ExceptionBreakpointsFilter.cs index 5100a89f7..86431b9ba 100644 --- a/src/Dap.Protocol/Models/ExceptionBreakpointsFilter.cs +++ b/src/Dap.Protocol/Models/ExceptionBreakpointsFilter.cs @@ -11,12 +11,12 @@ public record ExceptionBreakpointsFilter /// /// The internal ID of the filter. This value is passed to the setExceptionBreakpoints request. /// - public string Filter { get; init; } + public string Filter { get; init; } = null!; /// /// The name of the filter. This will be shown in the UI. /// - public string Label { get; init; } + public string Label { get; init; } = null!; /// /// Initial value of the filter. If not specified a value 'false' is assumed. diff --git a/src/Dap.Protocol/Models/ExceptionFilterOptions.cs b/src/Dap.Protocol/Models/ExceptionFilterOptions.cs index a7046d04a..3230ec432 100644 --- a/src/Dap.Protocol/Models/ExceptionFilterOptions.cs +++ b/src/Dap.Protocol/Models/ExceptionFilterOptions.cs @@ -8,7 +8,7 @@ public record ExceptionFilterOptions /// ID of an exception filter returned by the 'exceptionBreakpointFilters' /// capability. /// - public string FilterId { get; init; } + public string FilterId { get; init; } = null!; /// /// An optional expression for conditional exceptions. diff --git a/src/Dap.Protocol/Models/InstructionBreakpoint.cs b/src/Dap.Protocol/Models/InstructionBreakpoint.cs index f33622484..054aa71ec 100644 --- a/src/Dap.Protocol/Models/InstructionBreakpoint.cs +++ b/src/Dap.Protocol/Models/InstructionBreakpoint.cs @@ -8,7 +8,7 @@ public record InstructionBreakpoint /// The instruction reference of the breakpoint. /// This should be a memory or instruction pointer reference from an EvaluateResponse, Variable, StackFrame, GotoTarget, or Breakpoint. /// - public string InstructionReference { get; init; } + public string InstructionReference { get; init; } = null!; /// /// An optional offset from the instruction reference. diff --git a/src/Dap.Protocol/Models/Message.cs b/src/Dap.Protocol/Models/Message.cs index cf25c1c35..171fcac43 100644 --- a/src/Dap.Protocol/Models/Message.cs +++ b/src/Dap.Protocol/Models/Message.cs @@ -17,7 +17,7 @@ public record Message /// A format string for the message. Embedded variables have the form '{name}'. /// If variable name starts with an underscore character, the variable does not contain user data (PII) and can be safely used for telemetry purposes. /// - public string Format { get; init; } + public string Format { get; init; } = null!; /// /// An object used as a dictionary for looking up the variables in the format string. diff --git a/src/Dap.Protocol/Models/Module.cs b/src/Dap.Protocol/Models/Module.cs index bdb12efa7..dfd02c144 100644 --- a/src/Dap.Protocol/Models/Module.cs +++ b/src/Dap.Protocol/Models/Module.cs @@ -6,7 +6,8 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { /// /// A Module object represents a row in the modules view. - /// Two attributes are mandatory: an id identifies a module in the modules view and is used in a ModuleEvent for identifying a module for adding, updating or deleting. + /// Two attributes are mandatory: an id identifies a module in the modules view and is used in a ModuleEvent for identifying a module for adding, updating or + /// deleting. /// The name is used to minimally render the module in the UI. /// Additional attributes can be added to the module.They will show up in the module View if they have a corresponding ColumnDescriptor. /// To avoid an unnecessary proliferation of additional attributes with similar semantics but different names @@ -22,7 +23,7 @@ public record Module /// /// A name of the module. /// - public string Name { get; init; } + public string Name { get; init; } = null!; /// /// optional but recommended attributes. diff --git a/src/Dap.Protocol/Models/ModulesViewDescriptor.cs b/src/Dap.Protocol/Models/ModulesViewDescriptor.cs index 56fb696b4..404bde7b5 100644 --- a/src/Dap.Protocol/Models/ModulesViewDescriptor.cs +++ b/src/Dap.Protocol/Models/ModulesViewDescriptor.cs @@ -6,6 +6,6 @@ /// public record ModulesViewDescriptor { - public Container Columns { get; init; } + public Container Columns { get; init; } = null!; } } diff --git a/src/Dap.Protocol/Models/StackFrame.cs b/src/Dap.Protocol/Models/StackFrame.cs index 29b09753c..f05571723 100644 --- a/src/Dap.Protocol/Models/StackFrame.cs +++ b/src/Dap.Protocol/Models/StackFrame.cs @@ -70,8 +70,8 @@ public record StackFrame [StringEnum] public readonly partial struct StackFramePresentationHint { - public static SourcePresentationHint Normal { get; } = new SourcePresentationHint("normal"); - public static SourcePresentationHint Label { get; } = new SourcePresentationHint("label"); - public static SourcePresentationHint Subtle { get; } = new SourcePresentationHint("subtle"); + public static StackFramePresentationHint Normal { get; } = new StackFramePresentationHint("normal"); + public static StackFramePresentationHint Label { get; } = new StackFramePresentationHint("label"); + public static StackFramePresentationHint Subtle { get; } = new StackFramePresentationHint("subtle"); } } diff --git a/src/Dap.Protocol/Models/Thread.cs b/src/Dap.Protocol/Models/Thread.cs index f0ac0c653..b55d738c8 100644 --- a/src/Dap.Protocol/Models/Thread.cs +++ b/src/Dap.Protocol/Models/Thread.cs @@ -13,6 +13,6 @@ public record Thread /// /// A name of the thread. /// - public string Name { get; init; } + public string Name { get; init; } = null!; } } diff --git a/src/Dap.Protocol/Models/Variable.cs b/src/Dap.Protocol/Models/Variable.cs index e78b36246..e7aba6042 100644 --- a/src/Dap.Protocol/Models/Variable.cs +++ b/src/Dap.Protocol/Models/Variable.cs @@ -15,12 +15,12 @@ public record Variable /// /// The variable's name. /// - public string Name { get; init; } + public string Name { get; init; } = null!; /// /// The variable's value. This can be a multi-line text, e.g. for a function the body of a function. /// - public string Value { get; init; } + public string Value { get; init; } = null!; /// /// The type of the variable's value. Typically shown in the UI when hovering over the value. diff --git a/src/Dap.Shared/DapResponseRouter.cs b/src/Dap.Shared/DapResponseRouter.cs index 0133caaeb..a41b86032 100644 --- a/src/Dap.Shared/DapResponseRouter.cs +++ b/src/Dap.Shared/DapResponseRouter.cs @@ -28,31 +28,48 @@ public DapResponseRouter(IOutputHandler outputHandler, ISerializer serializer) Serializer = serializer; } - public void SendNotification(string method) => + public void SendNotification(string method) + { OutputHandler.Send( - new OutgoingNotification { + new OutgoingNotification + { Method = method } ); + } - public void SendNotification(string method, T @params) => + public void SendNotification(string method, T @params) + { OutputHandler.Send( - new OutgoingNotification { + new OutgoingNotification + { Method = method, Params = @params } ); + } - public void SendNotification(IRequest @params) => SendNotification(GetMethodName(@params.GetType()), @params); + public void SendNotification(IRequest @params) + { + SendNotification(GetMethodName(@params.GetType()), @params); + } - public Task SendRequest(IRequest @params, CancellationToken cancellationToken) => - SendRequest(GetMethodName(@params.GetType()), @params).Returning(cancellationToken); + public Task SendRequest(IRequest @params, CancellationToken cancellationToken) + { + return SendRequest(GetMethodName(@params.GetType()), @params).Returning(cancellationToken); + } - public IResponseRouterReturns SendRequest(string method) => new ResponseRouterReturnsImpl(this, method, new object()); + public IResponseRouterReturns SendRequest(string method) + { + return new ResponseRouterReturnsImpl(this, method, new object()); + } - public IResponseRouterReturns SendRequest(string method, T @params) => new ResponseRouterReturnsImpl(this, method, @params); + public IResponseRouterReturns SendRequest(string method, T @params) + { + return new ResponseRouterReturnsImpl(this, method, @params); + } - public bool TryGetRequest(long id, [NotNullWhen(true)] out string method, [NotNullWhen(true)] out TaskCompletionSource pendingTask) + public bool TryGetRequest(long id, [NotNullWhen(true)] out string? method, [NotNullWhen(true)] out TaskCompletionSource? pendingTask) { var result = Requests.TryGetValue(id, out var source); method = source.method; @@ -99,7 +116,8 @@ public async Task Returning(CancellationToken cancellation cancellationToken.ThrowIfCancellationRequested(); _router.OutputHandler.Send( - new OutgoingRequest { + new OutgoingRequest + { Method = _method, Params = _params, Id = nextId @@ -108,7 +126,8 @@ public async Task Returning(CancellationToken cancellation if (_method != RequestNames.Cancel) { cancellationToken.Register( - () => { + () => + { if (tcs.Task.IsCompleted) return; #pragma warning disable VSTHRD110 _router.SendRequest(RequestNames.Cancel, new { requestId = nextId }).Returning(CancellationToken.None); @@ -122,7 +141,7 @@ public async Task Returning(CancellationToken cancellation var result = await tcs.Task.ConfigureAwait(false); if (typeof(TResponse) == typeof(Unit)) { - return (TResponse) (object) Unit.Value; + return (TResponse)(object)Unit.Value; } return result.ToObject(_router.Serializer.JsonSerializer); @@ -133,7 +152,10 @@ public async Task Returning(CancellationToken cancellation } } - public async Task ReturningVoid(CancellationToken cancellationToken) => await Returning(cancellationToken).ConfigureAwait(false); + public async Task ReturningVoid(CancellationToken cancellationToken) + { + await Returning(cancellationToken).ConfigureAwait(false); + } } } } diff --git a/src/JsonRpc.Generation/JsonRpc.Generation.csproj b/src/JsonRpc.Generation/JsonRpc.Generation.csproj deleted file mode 100644 index c053a21df..000000000 --- a/src/JsonRpc.Generation/JsonRpc.Generation.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - - netstandard1.0 - OmniSharp.Extensions.JsonRpc.Generation - OmniSharp.Extensions.JsonRpc.Generation - - - - - - - - diff --git a/src/JsonRpc.Generators/AssemblyCapabilityKeyAttributeGenerator.cs b/src/JsonRpc.Generators/AssemblyCapabilityKeyAttributeGenerator.cs index 538a04a54..63f581d5a 100644 --- a/src/JsonRpc.Generators/AssemblyCapabilityKeyAttributeGenerator.cs +++ b/src/JsonRpc.Generators/AssemblyCapabilityKeyAttributeGenerator.cs @@ -15,7 +15,7 @@ public class AssemblyCapabilityKeyAttributeGenerator : IIncrementalGenerator public void Initialize(IncrementalGeneratorInitializationContext context) { var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( - predicate: (syntaxNode, token) => + (syntaxNode, _) => { if (syntaxNode.Parent is TypeDeclarationSyntax) return false; if (syntaxNode is TypeDeclarationSyntax { Arity: 0, BaseList: { } bl } typeDeclarationSyntax @@ -38,11 +38,11 @@ public void Initialize(IncrementalGeneratorInitializationContext context) return false; }, - transform: (syntaxContext, token) => + (syntaxContext, _) => { - var namespaces = new HashSet() { "OmniSharp.Extensions.LanguageServer.Protocol" }; + var namespaces = new HashSet { "OmniSharp.Extensions.LanguageServer.Protocol" }; var tds = (TypeDeclarationSyntax)syntaxContext.Node; - + foreach (var item in syntaxContext.Node.SyntaxTree.GetCompilationUnitRoot() .Usings.Where(z => z.Alias == null) .Select(z => z.Name.ToFullString())) @@ -52,14 +52,26 @@ public void Initialize(IncrementalGeneratorInitializationContext context) var typeSymbol = syntaxContext.SemanticModel.GetDeclaredSymbol(syntaxContext.Node)!; - return (namespaces, Attribute(IdentifierName("AssemblyCapabilityKey"), AttributeArgumentList(SeparatedList(new[] { AttributeArgument(TypeOfExpression(ParseName(typeSymbol.ToDisplayString()))), }.Concat(tds.AttributeLists.GetAttribute("CapabilityKey")!.ArgumentList!.Arguments))))); + return ( namespaces, + Attribute( + IdentifierName("AssemblyCapabilityKey"), + AttributeArgumentList( + SeparatedList( + new[] { AttributeArgument(TypeOfExpression(ParseName(typeSymbol.ToDisplayString()))), }.Concat( + tds.AttributeLists.GetAttribute("CapabilityKey")!.ArgumentList!.Arguments + ) + ) + ) + ) ); } ).Collect(); - + context.RegisterSourceOutput(syntaxProvider, GenerateAssemblyCapabilityKeys); } - private void GenerateAssemblyCapabilityKeys(SourceProductionContext context, ImmutableArray<(HashSet namespaces, AttributeSyntax attribute)> types) + private void GenerateAssemblyCapabilityKeys( + SourceProductionContext context, ImmutableArray<(HashSet namespaces, AttributeSyntax attribute)> types + ) { var namespaces = types.Aggregate( new HashSet(), (set, tuple) => @@ -75,8 +87,10 @@ private void GenerateAssemblyCapabilityKeys(SourceProductionContext context, Imm if (types.Any()) { var cu = CompilationUnit() - .WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z))))) - .AddAttributeLists(AttributeList(target: AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), SeparatedList(types.Select(z => z.attribute)))); + .WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z))))) + .AddAttributeLists( + AttributeList(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), SeparatedList(types.Select(z => z.attribute))) + ); context.AddSource("AssemblyCapabilityKeys.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8)); } diff --git a/src/JsonRpc.Generators/AssemblyJsonRpcHandlersAttributeGenerator.cs b/src/JsonRpc.Generators/AssemblyJsonRpcHandlersAttributeGenerator.cs index 9871cd1bb..89f043221 100644 --- a/src/JsonRpc.Generators/AssemblyJsonRpcHandlersAttributeGenerator.cs +++ b/src/JsonRpc.Generators/AssemblyJsonRpcHandlersAttributeGenerator.cs @@ -1,7 +1,5 @@ -using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.Diagnostics; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; @@ -19,7 +17,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) var syntaxProvider = context .SyntaxProvider .CreateSyntaxProvider( - predicate: (syntaxNode, token) => + (syntaxNode, _) => { if (syntaxNode.Parent is TypeDeclarationSyntax) return false; if (syntaxNode is TypeDeclarationSyntax { Arity: 0, BaseList: { } bl } typeDeclarationSyntax @@ -58,7 +56,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) return false; }, - transform: (syntaxContext, token) => AttributeArgument( + (syntaxContext, _) => AttributeArgument( TypeOfExpression( ParseName(syntaxContext.SemanticModel.GetDeclaredSymbol(syntaxContext.Node)!.ToDisplayString()) ) @@ -71,16 +69,21 @@ public void Initialize(IncrementalGeneratorInitializationContext context) private void GenerateAssemblyJsonRpcHandlers(SourceProductionContext context, ImmutableArray types) { - var namespaces = new HashSet() { "OmniSharp.Extensions.JsonRpc" }; + var namespaces = new HashSet { "OmniSharp.Extensions.JsonRpc" }; if (types.Any()) { var cu = CompilationUnit() - .WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z))))); + .WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z))))); while (types.Length > 0) { var innerTypes = types.Take(10).ToArray(); types = types.Skip(10).ToImmutableArray(); - cu = cu.AddAttributeLists(AttributeList(target: AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), SingletonSeparatedList(Attribute(IdentifierName("AssemblyJsonRpcHandlers"), AttributeArgumentList(SeparatedList(innerTypes)))))); + cu = cu.AddAttributeLists( + AttributeList( + AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), + SingletonSeparatedList(Attribute(IdentifierName("AssemblyJsonRpcHandlers"), AttributeArgumentList(SeparatedList(innerTypes)))) + ) + ); } context.AddSource("AssemblyJsonRpcHandlers.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8)); diff --git a/src/JsonRpc.Generators/AutoImplementParamsGenerator.cs b/src/JsonRpc.Generators/AutoImplementParamsGenerator.cs index 74287848d..c9eac05da 100644 --- a/src/JsonRpc.Generators/AutoImplementParamsGenerator.cs +++ b/src/JsonRpc.Generators/AutoImplementParamsGenerator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -20,7 +19,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) var _interfaces = "IPartialItemsRequest,IPartialItemRequest,IWorkDoneProgressParams,IHandlerIdentity"; var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( - predicate: (syntaxNode, token) => + (syntaxNode, _) => { if (syntaxNode is TypeDeclarationSyntax typeDeclarationSyntax and (ClassDeclarationSyntax or RecordDeclarationSyntax) && ( typeDeclarationSyntax.AttributeLists.ContainsAttribute(_attributes) @@ -32,7 +31,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) } return false; - }, transform: (syntaxContext, token) => { return syntaxContext; } + }, (syntaxContext, _) => { return syntaxContext; } ); @@ -50,10 +49,14 @@ private static void GenerateAutoImplementedInterfaces(SourceProductionContext co var autoImplementProperties = AutoImplementInterfaces(candidate, symbol).ToArray(); if (autoImplementProperties is { Length: > 0 }) { - var extendedParams = candidate.WithAttributeLists(List()) - .WithMembers(List(autoImplementProperties)) - .WithConstraintClauses(List()) - .WithBaseList(null); + var extendedParams = candidate + .WithAttributeLists(List()) + .WithMembers(List(autoImplementProperties)) + .WithConstraintClauses(List()) + .WithBaseList(null) + .WithOpenBraceToken(Token(SyntaxKind.OpenBraceToken)) + .WithCloseBraceToken(Token(SyntaxKind.CloseBraceToken)) + .WithSemicolonToken(Token(SyntaxKind.None)); members.Add(extendedParams); } @@ -65,7 +68,12 @@ private static void GenerateAutoImplementedInterfaces(SourceProductionContext co } var cu = CompilationUnit( - List(), List(candidate.SyntaxTree.GetCompilationUnitRoot().Usings), List(), + List(), + List( + candidate.SyntaxTree.GetCompilationUnitRoot().Usings.Concat( + new[] { UsingDirective(ParseName("Newtonsoft.Json")), UsingDirective(ParseName("System.ComponentModel")) } + ) + ), List(), SingletonList( NamespaceDeclaration(ParseName(symbol.ContainingNamespace.ToDisplayString())) .WithMembers(List(members)) @@ -144,7 +152,7 @@ private static IEnumerable AutoImplementInterfaces(Base SingletonSeparatedList( AttributeArgument( MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, IdentifierName("EditorBrowsableState"), + SyntaxKind.SimpleMemberAccessExpression, ParseName("EditorBrowsableState"), IdentifierName("Never") ) ) diff --git a/src/JsonRpc.Generators/Contexts/GeneratorData.cs b/src/JsonRpc.Generators/Contexts/GeneratorData.cs index 8af0444e6..33cffce86 100644 --- a/src/JsonRpc.Generators/Contexts/GeneratorData.cs +++ b/src/JsonRpc.Generators/Contexts/GeneratorData.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; @@ -8,7 +7,7 @@ namespace OmniSharp.Extensions.JsonRpc.Generators.Contexts { - abstract record GeneratorData( + internal abstract record GeneratorData( TypeDeclarationSyntax TypeDeclaration, INamedTypeSymbol TypeSymbol, JsonRpcAttributes JsonRpcAttributes, @@ -91,7 +90,10 @@ HashSet additionalUsings && tds.AttributeLists.ContainsAttribute("GenerateHandler") )?.GetSyntax() is TypeDeclarationSyntax declarationSyntax) { - return Create(parent.Compilation, declarationSyntax, parent.Compilation.GetSemanticModel(declarationSyntax.SyntaxTree), parent.AdditionalUsings) as RequestItem; } + return Create( + parent.Compilation, declarationSyntax, parent.Compilation.GetSemanticModel(declarationSyntax.SyntaxTree), parent.AdditionalUsings + ) as RequestItem; + } return null; } diff --git a/src/JsonRpc.Generators/Contexts/RegistrationOptionAttributes.cs b/src/JsonRpc.Generators/Contexts/RegistrationOptionAttributes.cs index dd19d8100..28b59670c 100644 --- a/src/JsonRpc.Generators/Contexts/RegistrationOptionAttributes.cs +++ b/src/JsonRpc.Generators/Contexts/RegistrationOptionAttributes.cs @@ -1,4 +1,3 @@ -using System.Collections; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; @@ -7,7 +6,7 @@ namespace OmniSharp.Extensions.JsonRpc.Generators.Contexts { - record RegistrationOptionAttributes( + internal record RegistrationOptionAttributes( SyntaxAttributeData? GenerateRegistrationOptions, string? Key, ExpressionSyntax[]? KeyExpression, @@ -23,13 +22,14 @@ bool ImplementsStaticRegistrationOptions public static RegistrationOptionAttributes? Parse(Compilation compilation, TypeDeclarationSyntax syntax, INamedTypeSymbol symbol) { var registrationOptionsAttributeSymbol = - compilation.GetTypeByMetadataName($"OmniSharp.Extensions.LanguageServer.Protocol.Generation.GenerateRegistrationOptionsAttribute"); + compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Generation.GenerateRegistrationOptionsAttribute"); var registrationOptionsConverterAttributeSymbol = - compilation.GetTypeByMetadataName($"OmniSharp.Extensions.LanguageServer.Protocol.RegistrationOptionsConverterAttribute"); + compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.RegistrationOptionsConverterAttribute"); // var registrationOptionsInterfaceSymbol = compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.IRegistrationOptions"); var textDocumentRegistrationOptionsInterfaceSymbol = compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.ITextDocumentRegistrationOptions"); - var workDoneProgressOptionsInterfaceSymbol = compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.IWorkDoneProgressOptions"); + var workDoneProgressOptionsInterfaceSymbol = + compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.IWorkDoneProgressOptions"); var staticRegistrationOptionsInterfaceSymbol = compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.IStaticRegistrationOptions"); @@ -40,33 +40,35 @@ bool ImplementsStaticRegistrationOptions ITypeSymbol? converter = null; var supportsDocumentSelector = data.NamedArguments.Any(z => z is { Key: nameof(SupportsDocumentSelector), Value: { Value: true } }) - || symbol.AllInterfaces.Length > 0 && symbol.AllInterfaces.Any( + || ( symbol.AllInterfaces.Length > 0 && symbol.AllInterfaces.Any( z => SymbolEqualityComparer.Default.Equals(z, textDocumentRegistrationOptionsInterfaceSymbol) - ) - || textDocumentRegistrationOptionsInterfaceSymbol is { } && syntax.BaseList?.Types.Any( + ) ) + || ( textDocumentRegistrationOptionsInterfaceSymbol is { } && syntax.BaseList?.Types.Any( type => type.Type.GetSyntaxName()?.Contains(textDocumentRegistrationOptionsInterfaceSymbol.Name) == true - ) == true; + ) == true ); var supportsWorkDoneProgress = data.NamedArguments.Any(z => z is { Key: nameof(SupportsWorkDoneProgress), Value: { Value: true } }) - || symbol.AllInterfaces.Length > 0 && symbol.AllInterfaces.Any( + || ( symbol.AllInterfaces.Length > 0 && symbol.AllInterfaces.Any( z => SymbolEqualityComparer.Default.Equals(z, workDoneProgressOptionsInterfaceSymbol) - ) - || workDoneProgressOptionsInterfaceSymbol is { } && syntax.BaseList?.Types.Any( + ) ) + || ( workDoneProgressOptionsInterfaceSymbol is { } && syntax.BaseList?.Types.Any( type => type.Type.GetSyntaxName()?.Contains(workDoneProgressOptionsInterfaceSymbol.Name) == true - ) == true; - var supportsStaticRegistrationOptions = data.NamedArguments.Any(z => z is { Key: nameof(SupportsStaticRegistrationOptions), Value: { Value: true } }) - || symbol.AllInterfaces.Length > 0 && symbol.AllInterfaces.Any( - z => SymbolEqualityComparer.Default.Equals(z, staticRegistrationOptionsInterfaceSymbol) - ) - || staticRegistrationOptionsInterfaceSymbol is { } && syntax.BaseList?.Types.Any( - type => type.Type.GetSyntaxName()?.Contains(staticRegistrationOptionsInterfaceSymbol.Name) == true - ) == true; + ) == true ); + var supportsStaticRegistrationOptions = + data.NamedArguments.Any(z => z is { Key: nameof(SupportsStaticRegistrationOptions), Value: { Value: true } }) + || ( symbol.AllInterfaces.Length > 0 && symbol.AllInterfaces.Any( + z => SymbolEqualityComparer.Default.Equals(z, staticRegistrationOptionsInterfaceSymbol) + ) ) + || ( staticRegistrationOptionsInterfaceSymbol is { } && syntax.BaseList?.Types.Any( + type => type.Type.GetSyntaxName()?.Contains(staticRegistrationOptionsInterfaceSymbol.Name) == true + ) == true ); - if (attributeSyntax is { ArgumentList: { Arguments: { Count: >=1 } syntaxArguments } }) + if (attributeSyntax is { ArgumentList: { Arguments: { Count: >= 1 } syntaxArguments } }) { converter = data.NamedArguments.FirstOrDefault(z => z is { Key: "Converter" }).Value.Type; converterSyntax = syntaxArguments .Select( - z => z is { + z => z is + { Expression: TypeOfExpressionSyntax expressionSyntax, NameEquals: { Name: { Identifier: { Text: "Converter" } } } } ? expressionSyntax.Type @@ -75,7 +77,8 @@ bool ImplementsStaticRegistrationOptions .FirstOrDefault(); if (converter is null) { - if (symbol.GetAttribute(registrationOptionsConverterAttributeSymbol) is { ConstructorArguments: { Length: >=1 } converterArguments } converterData + if (symbol.GetAttribute(registrationOptionsConverterAttributeSymbol) is + { ConstructorArguments: { Length: >= 1 } converterArguments } converterData && converterArguments[0].Kind is TypedConstantKind.Type && converterData.ApplicationSyntaxReference?.GetSyntax() is AttributeSyntax converterAttributeSyntax && converterAttributeSyntax is { ArgumentList: { Arguments: { Count: 1 } converterArgumentSyntax } } @@ -115,7 +118,9 @@ static IEnumerable getStringExpressionSyntaxes(AttributeArgume yield return literalExpressionSyntax; break; case InvocationExpressionSyntax - { Expression: IdentifierNameSyntax { Identifier: { Text: "nameof" } } }: + { + Expression: IdentifierNameSyntax { Identifier: { Text: "nameof" } } + }: yield return syntax.Expression; break; } @@ -132,7 +137,7 @@ static IEnumerable getStringExpressionSyntaxes(AttributeArgume supportsWorkDoneProgress, supportsDocumentSelector, supportsStaticRegistrationOptions, - converterSyntax is null ? null : new SyntaxSymbol(converterSyntax, (INamedTypeSymbol) converter!), + converterSyntax is null ? null : new SyntaxSymbol(converterSyntax, (INamedTypeSymbol)converter!), symbol .GetMembers() .AsEnumerable() diff --git a/src/JsonRpc.Generators/EnumLikeStringGenerator.cs b/src/JsonRpc.Generators/EnumLikeStringGenerator.cs index 25d2b6e42..7d395976e 100644 --- a/src/JsonRpc.Generators/EnumLikeStringGenerator.cs +++ b/src/JsonRpc.Generators/EnumLikeStringGenerator.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; @@ -15,10 +14,10 @@ public class EnumLikeStringGenerator : IIncrementalGenerator public void Initialize(IncrementalGeneratorInitializationContext context) { var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( - predicate: (node, token) => node is StructDeclarationSyntax tds && tds.AttributeLists.ContainsAttribute("StringEnum"), - transform: (syntaxContext, token) => syntaxContext + (node, _) => node is StructDeclarationSyntax tds && tds.AttributeLists.ContainsAttribute("StringEnum"), + (syntaxContext, _) => syntaxContext ); - + context.RegisterSourceOutput(syntaxProvider, GenerateEnum); } @@ -47,25 +46,48 @@ private void GenerateEnum(SourceProductionContext context, GeneratorSyntaxContex .WithMembers(SingletonList(GetImplementation(candidate))) ) ) - .AddUsings(UsingDirective(ParseName("System")), UsingDirective(ParseName("System.Collections.Generic")), UsingDirective(ParseName("System.Diagnostics")), UsingDirective(ParseName("System.Linq")), UsingDirective(ParseName("System.Reflection")), UsingDirective(ParseName("Newtonsoft.Json")), UsingDirective(ParseName("OmniSharp.Extensions.JsonRpc")), UsingDirective(ParseName("OmniSharp.Extensions.JsonRpc.Serialization.Converters"))) + .AddUsings( + UsingDirective(ParseName("System")), UsingDirective(ParseName("System.Collections.Generic")), + UsingDirective(ParseName("System.Diagnostics")), UsingDirective(ParseName("System.Linq")), + UsingDirective(ParseName("System.Reflection")), UsingDirective(ParseName("Newtonsoft.Json")), + UsingDirective(ParseName("OmniSharp.Extensions.JsonRpc")), + UsingDirective(ParseName("OmniSharp.Extensions.JsonRpc.Serialization.Converters")) + ) .WithLeadingTrivia() .WithTrailingTrivia() .WithLeadingTrivia(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.EnableKeyword), true))) .WithTrailingTrivia(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.RestoreKeyword), true))); - context.AddSource($"{Path.GetFileNameWithoutExtension(candidate.SyntaxTree.FilePath)}_{candidate.Identifier.Text}{( candidate.Arity > 0 ? candidate.Arity.ToString() : "" )}.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8)); + context.AddSource( + $"{Path.GetFileNameWithoutExtension(candidate.SyntaxTree.FilePath)}_{candidate.Identifier.Text}{( candidate.Arity > 0 ? candidate.Arity.ToString() : "" )}.cs", + cu.NormalizeWhitespace().GetText(Encoding.UTF8) + ); } private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax syntax) { + var items = syntax.Members + .OfType() + .Where(z => z.Modifiers.Any(SyntaxKind.StaticKeyword)) + .Select(z => IdentifierName(z.Identifier.Text)) + .Concat( + syntax.Members + .OfType() + .Where(z => z.Modifiers.Any(SyntaxKind.StaticKeyword)) + .Where(z => z.Declaration.Variables.Count == 1) + .Select(z => IdentifierName(z.Declaration.Variables[0].Identifier.Text)) + ); return syntax .WithBaseList( BaseList( SeparatedList( - new BaseTypeSyntax[] { + new BaseTypeSyntax[] + { SimpleBaseType( GenericName(Identifier("IEquatable")) - .WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList(PredefinedType(Token(SyntaxKind.StringKeyword))))) + .WithTypeArgumentList( + TypeArgumentList(SingletonSeparatedList(PredefinedType(Token(SyntaxKind.StringKeyword)))) + ) ), SimpleBaseType( GenericName(Identifier("IEquatable")) @@ -78,7 +100,8 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithAttributeLists( List( - new[] { + new[] + { AttributeList( SingletonSeparatedList( Attribute(IdentifierName("JsonConverter")) @@ -112,7 +135,8 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithMembers( List( - new MemberDeclarationSyntax[] { + new MemberDeclarationSyntax[] + { FieldDeclaration( VariableDeclaration( GenericName(Identifier("Lazy")) @@ -121,7 +145,9 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax SingletonSeparatedList( GenericName(Identifier("IReadOnlyList")) .WithTypeArgumentList( - TypeArgumentList(SingletonSeparatedList(IdentifierName(syntax.Identifier.Text))) + TypeArgumentList( + SingletonSeparatedList(IdentifierName(syntax.Identifier.Text)) + ) ) ) ) @@ -140,7 +166,9 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax GenericName(Identifier("IReadOnlyList")) .WithTypeArgumentList( TypeArgumentList( - SingletonSeparatedList(IdentifierName(syntax.Identifier.Text)) + SingletonSeparatedList( + IdentifierName(syntax.Identifier.Text) + ) ) ) ) @@ -156,169 +184,25 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax Block( SingletonList( ReturnStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - InvocationExpression( - MemberAccessExpression( - SyntaxKind - .SimpleMemberAccessExpression, - InvocationExpression( - MemberAccessExpression( - SyntaxKind - .SimpleMemberAccessExpression, - TypeOfExpression( - IdentifierName( - syntax.Identifier - .Text - ) - ), - IdentifierName( - "GetProperties" - ) - ) - ) - .WithArgumentList( - ArgumentList( - SingletonSeparatedList( - Argument( - BinaryExpression( - SyntaxKind - .BitwiseOrExpression, - MemberAccessExpression( - SyntaxKind - .SimpleMemberAccessExpression, - IdentifierName( - "BindingFlags" - ), - IdentifierName( - "Static" - ) - ), - MemberAccessExpression( - SyntaxKind - .SimpleMemberAccessExpression, - IdentifierName( - "BindingFlags" - ), - IdentifierName( - "Public" - ) - ) - ) - ) - ) - ) - ), - IdentifierName("Where") - ) - ) - .WithArgumentList( - ArgumentList( - SingletonSeparatedList( - Argument( - SimpleLambdaExpression( - Parameter( - Identifier("z") - ) - ) - .WithExpressionBody( - BinaryExpression( - SyntaxKind - .NotEqualsExpression, - MemberAccessExpression( - SyntaxKind - .SimpleMemberAccessExpression, - IdentifierName( - "z" - ), - IdentifierName( - "Name" - ) - ), - InvocationExpression( - IdentifierName( - "nameof" - ) - ) - .WithArgumentList( - ArgumentList( - SingletonSeparatedList( - Argument( - IdentifierName( - "Defaults" - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ), - IdentifierName("Select") - ) - ) - .WithArgumentList( - ArgumentList( - SingletonSeparatedList( - Argument( - SimpleLambdaExpression( - Parameter( - Identifier("z") - ) - ) - .WithExpressionBody( - InvocationExpression( - MemberAccessExpression( - SyntaxKind - .SimpleMemberAccessExpression, - IdentifierName("z"), - IdentifierName( - "GetValue" - ) - ) - ) - .WithArgumentList( - ArgumentList( - SingletonSeparatedList( - Argument( - LiteralExpression( - SyntaxKind - .NullLiteralExpression - ) - ) - ) - ) - ) - ) - ) - ) - ) - ), - GenericName( - Identifier("Cast") - ) - .WithTypeArgumentList( - TypeArgumentList( - SingletonSeparatedList( - IdentifierName(syntax.Identifier.Text) - ) + ArrayCreationExpression( + ArrayType(IdentifierName(syntax.Identifier.Text)) + .WithRankSpecifiers( + SingletonList( + ArrayRankSpecifier( + SingletonSeparatedList< + ExpressionSyntax>( + OmittedArraySizeExpression() ) ) + ) ) - ), - IdentifierName("ToArray") ) - ) + .WithInitializer( + InitializerExpression( + SyntaxKind.ArrayInitializerExpression, + SeparatedList(items) + ) + ) ) ) ) @@ -334,11 +218,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PrivateKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.ReadOnlyKeyword) - } + Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.ReadOnlyKeyword) ) ), PropertyDeclaration( @@ -356,10 +236,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword) ) ) .WithExpressionBody( @@ -390,10 +267,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PrivateKeyword), - Token(SyntaxKind.ReadOnlyKeyword) - } + Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword) ) ), ConstructorDeclaration( @@ -436,10 +310,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword) ) ) .WithParameterList( @@ -483,10 +354,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword) ) ) .WithParameterList( @@ -521,10 +389,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.OverrideKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword) ) ) .WithExpressionBody( @@ -619,10 +484,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.OverrideKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword) ) ) .WithParameterList( @@ -706,10 +568,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.OverrideKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword) ) ) .WithExpressionBody( @@ -734,16 +593,14 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword) ) ) .WithParameterList( ParameterList( SeparatedList( - new SyntaxNodeOrToken[] { + new SyntaxNodeOrToken[] + { Parameter( Identifier("left") ) @@ -792,16 +649,14 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword) ) ) .WithParameterList( ParameterList( SeparatedList( - new SyntaxNodeOrToken[] { + new SyntaxNodeOrToken[] + { Parameter( Identifier("left") ) @@ -848,6 +703,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax } ) ) + .NormalizeWhitespace() ; } } diff --git a/src/JsonRpc.Generators/GenerateHandlerMethodsGenerator.cs b/src/JsonRpc.Generators/GenerateHandlerMethodsGenerator.cs index 9f954c748..51e875466 100644 --- a/src/JsonRpc.Generators/GenerateHandlerMethodsGenerator.cs +++ b/src/JsonRpc.Generators/GenerateHandlerMethodsGenerator.cs @@ -20,14 +20,14 @@ public void Initialize(IncrementalGeneratorInitializationContext context) { var _attributes = "GenerateHandler,GenerateRequestMethods,GenerateHandlerMethods"; var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( - predicate: (syntaxNode, token) => + (syntaxNode, _) => syntaxNode is TypeDeclarationSyntax tds and (ClassDeclarationSyntax or RecordDeclarationSyntax or InterfaceDeclarationSyntax) - && tds.AttributeLists.ContainsAttribute(_attributes), transform: (syntaxContext, token) => syntaxContext + && tds.AttributeLists.ContainsAttribute(_attributes), (syntaxContext, _) => syntaxContext ) .Combine(context.CompilationProvider) .Select( - (tuple, token) => + (tuple, _) => { var (syntaxContext, compilaiton) = tuple; var additionalUsings = new HashSet @@ -64,10 +64,15 @@ syntaxNode is TypeDeclarationSyntax tds ); context.RegisterSourceOutput(syntaxProvider, GenerateHandlerMethods); - context.RegisterSourceOutput(syntaxProvider.Where(z => z.actionItem is {}).SelectMany((z, _) => z.actionItem!.AssemblyJsonRpcHandlersAttributeArguments).Collect(), GenerateAssemblyJsonRpcHandlers); + context.RegisterSourceOutput( + syntaxProvider.Where(z => z.actionItem is { }).SelectMany((z, _) => z.actionItem!.AssemblyJsonRpcHandlersAttributeArguments).Collect(), + GenerateAssemblyJsonRpcHandlers + ); } - private void GenerateHandlerMethods(SourceProductionContext context, (GeneratorData? actionItem, Diagnostic? diagnostic, HashSet additionalUsings) valueTuple) + private void GenerateHandlerMethods( + SourceProductionContext context, (GeneratorData? actionItem, Diagnostic? diagnostic, HashSet additionalUsings) valueTuple + ) { var (actionItem, diagnostic, additionalUsings) = valueTuple; // context.ReportDiagnostic(Diagnostic.Create(GeneratorDiagnostics.Message, null, $"candidate: {candidateClass.Identifier.ToFullString()}")); @@ -108,7 +113,7 @@ private void GenerateHandlerMethods(SourceProductionContext context, (GeneratorD if (!members.Any()) return; - var namespacesMapping = new Dictionary() + var namespacesMapping = new Dictionary { ["OmniSharp.Extensions.DebugAdapter"] = new[] { @@ -157,18 +162,18 @@ private void GenerateHandlerMethods(SourceProductionContext context, (GeneratorD private void GenerateAssemblyJsonRpcHandlers(SourceProductionContext context, ImmutableArray handlers) { - var namespaces = new HashSet() { "OmniSharp.Extensions.JsonRpc" }; + var namespaces = new HashSet { "OmniSharp.Extensions.JsonRpc" }; if (handlers.Any()) { var cu = CompilationUnit() - .WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z))))); + .WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z))))); while (handlers.Length > 0) { var innerTypes = handlers.Take(10).ToArray(); handlers = handlers.Skip(10).ToImmutableArray(); cu = cu.AddAttributeLists( AttributeList( - target: AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), + AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), SingletonSeparatedList(Attribute(IdentifierName("AssemblyJsonRpcHandlers"), AttributeArgumentList(SeparatedList(innerTypes)))) ) ); diff --git a/src/JsonRpc.Generators/RegistrationOptionsGenerator.cs b/src/JsonRpc.Generators/RegistrationOptionsGenerator.cs index edf1356f9..2c36fcf4f 100644 --- a/src/JsonRpc.Generators/RegistrationOptionsGenerator.cs +++ b/src/JsonRpc.Generators/RegistrationOptionsGenerator.cs @@ -15,7 +15,7 @@ namespace OmniSharp.Extensions.JsonRpc.Generators [Generator] public class RegistrationOptionsGenerator : IIncrementalGenerator { - private static string[] RequiredUsings = + private static readonly string[] RequiredUsings = { "OmniSharp.Extensions.LanguageServer.Protocol", "OmniSharp.Extensions.LanguageServer.Protocol.Serialization", @@ -26,11 +26,12 @@ private record AttributeData( INamedTypeSymbol RegistrationOptionsInterfaceSymbol, INamedTypeSymbol TextDocumentRegistrationOptionsInterfaceSymbol, INamedTypeSymbol WorkDoneProgressOptionsInterfaceSymbol, INamedTypeSymbol StaticRegistrationOptionsInterfaceSymbol ); + public void Initialize(IncrementalGeneratorInitializationContext context) { var attributes = context.CompilationProvider .Select( - (compilation, token) => + (compilation, _) => { var registrationOptionsInterfaceSymbol = compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.IRegistrationOptions")!; @@ -53,16 +54,16 @@ public void Initialize(IncrementalGeneratorInitializationContext context) } ); var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( - predicate: (syntaxNode, token) => + (syntaxNode, _) => syntaxNode is TypeDeclarationSyntax tds and (ClassDeclarationSyntax or RecordDeclarationSyntax) && tds.AttributeLists .SelectMany(z => z.Attributes) .Any(z => z.Name.ToFullString().Contains("GenerateRegistrationOptions")), - (syntaxContext, token) => syntaxContext + (syntaxContext, _) => syntaxContext ) .Combine(context.CompilationProvider) .Select( - (tuple, token) => + (tuple, _) => { var (syntaxContext, compilation) = tuple; var typeSymbol = syntaxContext.SemanticModel.GetDeclaredSymbol((TypeDeclarationSyntax)syntaxContext.Node); @@ -75,13 +76,13 @@ syntaxNode is TypeDeclarationSyntax tds and (ClassDeclarationSyntax or RecordDec return data is not { } ? default! : ( registrationOptions: (TypeDeclarationSyntax)syntaxContext.Node, - semanticModel: syntaxContext.SemanticModel, typeSymbol: typeSymbol, data: data! ); + semanticModel: syntaxContext.SemanticModel, typeSymbol, data: data! ); } ) .Where(z => z is { data: { } }) .Combine(attributes) .Select( - (tuple, token) => ( + (tuple, _) => ( tuple.Left.registrationOptions, tuple.Left.data, tuple.Left.semanticModel, tuple.Left.typeSymbol, attributes: tuple.Right ) ) @@ -91,8 +92,8 @@ syntaxNode is TypeDeclarationSyntax tds and (ClassDeclarationSyntax or RecordDec context.RegisterSourceOutput( syntaxProvider .Select( - (tuple, token) => ( namespaces: tuple.typeSymbol.ContainingNamespace.ToDisplayString(), - AttributeArgument(TypeOfExpression(IdentifierName(tuple.typeSymbol.Name))) ) + (tuple, _) => ( namespaces: tuple.typeSymbol.ContainingNamespace.ToDisplayString(), + AttributeArgument(TypeOfExpression(IdentifierName(tuple.typeSymbol.Name))) ) ) .Collect(), GenerateAssemblyRegistrationOptions ); @@ -128,7 +129,7 @@ private void GenerateRegistrationOptions( .WithMembers(List()); - var staticRegistrationOptions = registrationOptions.WithIdentifier(Identifier($"StaticOptions")) + var staticRegistrationOptions = registrationOptions.WithIdentifier(Identifier("StaticOptions")) .WithMembers( List( registrationOptions.Members.OfType() @@ -247,7 +248,7 @@ private void GenerateRegistrationOptions( extendedRegistrationOptions = extendedRegistrationOptions.AddMembers(staticRegistrationOptions); - var members = new List() { extendedRegistrationOptions }; + var members = new List { extendedRegistrationOptions }; var cu = CompilationUnit() .WithUsings(registrationOptions.SyntaxTree.GetCompilationUnitRoot().Usings) @@ -282,7 +283,7 @@ private void GenerateAssemblyRegistrationOptions( SourceProductionContext context, ImmutableArray<(string @namespace, AttributeArgumentSyntax argumentSyntax)> types ) { - var namespaces = new HashSet() { "OmniSharp.Extensions.LanguageServer.Protocol" }; + var namespaces = new HashSet { "OmniSharp.Extensions.LanguageServer.Protocol" }; if (types.Any()) { foreach (var item in types) @@ -294,7 +295,7 @@ private void GenerateAssemblyRegistrationOptions( .WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z))))) .AddAttributeLists( AttributeList( - target: AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), + AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), SingletonSeparatedList( Attribute( IdentifierName("AssemblyRegistrationOptions"), @@ -309,7 +310,7 @@ private void GenerateAssemblyRegistrationOptions( } - static TypeDeclarationSyntax ExtendAndImplementInterface(TypeDeclarationSyntax syntax, ITypeSymbol symbolToExtendFrom) + private static TypeDeclarationSyntax ExtendAndImplementInterface(TypeDeclarationSyntax syntax, ITypeSymbol symbolToExtendFrom) { return syntax switch { @@ -319,7 +320,7 @@ static TypeDeclarationSyntax ExtendAndImplementInterface(TypeDeclarationSyntax s }; } - static PropertyDeclarationSyntax GetWorkDoneProperty() + private static PropertyDeclarationSyntax GetWorkDoneProperty() { return PropertyDeclaration(PredefinedType(Token(SyntaxKind.BoolKeyword)), Identifier("WorkDoneProgress")) .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))) @@ -333,7 +334,7 @@ static PropertyDeclarationSyntax GetWorkDoneProperty() .WithAccessorList(CommonElements.GetSetAccessor); } - static PropertyDeclarationSyntax GetIdProperty() + private static PropertyDeclarationSyntax GetIdProperty() { return PropertyDeclaration(NullableType(PredefinedType(Token(SyntaxKind.StringKeyword))), Identifier("Id")) .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))) diff --git a/src/JsonRpc.Generators/Strategies/WarnIfResponseRouterIsNotProvidedStrategy.cs b/src/JsonRpc.Generators/Strategies/WarnIfResponseRouterIsNotProvidedStrategy.cs index 17eb45176..6432f37d7 100644 --- a/src/JsonRpc.Generators/Strategies/WarnIfResponseRouterIsNotProvidedStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/WarnIfResponseRouterIsNotProvidedStrategy.cs @@ -13,14 +13,18 @@ public IEnumerable Apply(SourceProductionContext contex var generateRequestMethods = item.JsonRpcAttributes.GenerateRequestMethods; if (generateRequestMethods != null && ( - generateRequestMethods.Data.ConstructorArguments.Length == 0 || - generateRequestMethods.Data.ConstructorArguments[0].Kind != TypedConstantKind.Array - && generateRequestMethods.Data.ConstructorArguments[0].Value == null - || generateRequestMethods.Data.ConstructorArguments[0].Kind == TypedConstantKind.Array - && generateRequestMethods.Data.ConstructorArguments[0].Values.Length == 0 ) - && !extensionMethodContext.TypeSymbol.ContainingNamespace.ToDisplayString().StartsWith("OmniSharp.Extensions.DebugAdapter.Protocol")) + generateRequestMethods.Data.ConstructorArguments.Length == 0 || + ( generateRequestMethods.Data.ConstructorArguments[0].Kind != TypedConstantKind.Array + && generateRequestMethods.Data.ConstructorArguments[0].Value == null ) + || ( generateRequestMethods.Data.ConstructorArguments[0].Kind == TypedConstantKind.Array + && generateRequestMethods.Data.ConstructorArguments[0].Values.Length == 0 ) ) && !extensionMethodContext.TypeSymbol.ContainingNamespace + .ToDisplayString().StartsWith("OmniSharp.Extensions.DebugAdapter.Protocol")) { - context.ReportDiagnostic(Diagnostic.Create(GeneratorDiagnostics.NoResponseRouterProvided, item.TypeDeclaration.Identifier.GetLocation(), item.TypeDeclaration.Identifier.Text)); + context.ReportDiagnostic( + Diagnostic.Create( + GeneratorDiagnostics.NoResponseRouterProvided, item.TypeDeclaration.Identifier.GetLocation(), item.TypeDeclaration.Identifier.Text + ) + ); } } } diff --git a/src/JsonRpc.Generators/StronglyTypedGenerator.cs b/src/JsonRpc.Generators/StronglyTypedGenerator.cs index 42f64bcf5..299cd4f25 100644 --- a/src/JsonRpc.Generators/StronglyTypedGenerator.cs +++ b/src/JsonRpc.Generators/StronglyTypedGenerator.cs @@ -13,7 +13,7 @@ namespace OmniSharp.Extensions.JsonRpc.Generators [Generator] public class StronglyTypedGenerator : IIncrementalGenerator { - private static string[] RequiredUsings = new[] + private static readonly string[] RequiredUsings = { "System.Collections.Generic", "System.Collections.ObjectModel", @@ -27,7 +27,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) { var attributes = context.CompilationProvider .Select( - (compilation, token) => new AttributeData( + (compilation, _) => new AttributeData( compilation.GetTypeByMetadataName( "OmniSharp.Extensions.LanguageServer.Protocol.Generation.GenerateTypedDataAttribute" )!, @@ -38,30 +38,30 @@ public void Initialize(IncrementalGeneratorInitializationContext context) ); var createContainersSyntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( - predicate: (syntaxNode, token) => syntaxNode switch + (syntaxNode, _) => syntaxNode switch { StructDeclarationSyntax structDeclarationSyntax when structDeclarationSyntax.AttributeLists.ContainsAttribute("GenerateContainer") => true, TypeDeclarationSyntax typeDeclarationSyntax and (ClassDeclarationSyntax or RecordDeclarationSyntax) when typeDeclarationSyntax .AttributeLists.ContainsAttribute("GenerateContainer") => true, _ => false - }, transform: (syntaxContext, token) => syntaxContext + }, (syntaxContext, _) => syntaxContext ); var canBeResolvedSyntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( - predicate: (syntaxNode, token) => + (syntaxNode, _) => syntaxNode is TypeDeclarationSyntax { BaseList: { } } typeDeclarationSyntax and (ClassDeclarationSyntax or RecordDeclarationSyntax) && syntaxNode.SyntaxTree.HasCompilationUnitRoot && typeDeclarationSyntax.Members.OfType().Any(z => z.Identifier.Text == "Data") && typeDeclarationSyntax.BaseList.Types.Any(z => z.Type.GetSyntaxName() == "ICanBeResolved"), - transform: (syntaxContext, token) => syntaxContext + (syntaxContext, _) => syntaxContext ); var canHaveDataSyntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( - predicate: (syntaxNode, token) => + (syntaxNode, _) => syntaxNode is TypeDeclarationSyntax { BaseList: { } } typeDeclarationSyntax and (ClassDeclarationSyntax or RecordDeclarationSyntax) && syntaxNode.SyntaxTree.HasCompilationUnitRoot && typeDeclarationSyntax.Members.OfType().Any(z => z.Identifier.Text == "Data") - && typeDeclarationSyntax.BaseList.Types.Any(z => z.Type.GetSyntaxName() == "ICanHaveData"), transform: (syntaxContext, token) => syntaxContext + && typeDeclarationSyntax.BaseList.Types.Any(z => z.Type.GetSyntaxName() == "ICanHaveData"), (syntaxContext, _) => syntaxContext ); context.RegisterSourceOutput(createContainersSyntaxProvider.Combine(attributes), GenerateContainerClass); @@ -123,10 +123,11 @@ private void GenerateCanBeResolvedClass(SourceProductionContext context, (Genera var (syntaxContext, attributeData) = valueTuple; var canBeResolved = (TypeDeclarationSyntax)syntaxContext.Node; var typeSymbol = syntaxContext.SemanticModel.GetDeclaredSymbol(canBeResolved)!; - + var dataInterfaceName = IdentifierName("ICanBeResolved"); CreateTypedClass( - context, canBeResolved, typeSymbol, dataInterfaceName, attributeData.GenerateTypedDataAttributeSymbol, attributeData.GenerateContainerAttributeSymbol, true + context, canBeResolved, typeSymbol, dataInterfaceName, attributeData.GenerateTypedDataAttributeSymbol, + attributeData.GenerateContainerAttributeSymbol, true ); } @@ -135,10 +136,11 @@ private void GenerateCanHaveDataClass(SourceProductionContext context, (Generato var (syntaxContext, attributeData) = valueTuple; var canBeResolved = (TypeDeclarationSyntax)syntaxContext.Node; var typeSymbol = syntaxContext.SemanticModel.GetDeclaredSymbol(canBeResolved)!; - + var dataInterfaceName = IdentifierName("ICanHaveData"); CreateTypedClass( - context, canBeResolved, typeSymbol, dataInterfaceName, attributeData.GenerateTypedDataAttributeSymbol, attributeData.GenerateContainerAttributeSymbol, true + context, canBeResolved, typeSymbol, dataInterfaceName, attributeData.GenerateTypedDataAttributeSymbol, + attributeData.GenerateContainerAttributeSymbol, true ); } @@ -169,6 +171,9 @@ bool includeHandlerIdentity .WithAttributeLists(List()) .WithBaseList(null) .WithMembers(List()) + .WithOpenBraceToken(Token(SyntaxKind.OpenBraceToken)) + .WithCloseBraceToken(Token(SyntaxKind.CloseBraceToken)) + .WithSemicolonToken(Token(SyntaxKind.None)) .AddMembers( GetWithDataMethod(candidate, HandlerIdentityConstraintClause(includeHandlerIdentity, IdentifierName("TData"))), GetFromMethod(candidate, includeHandlerIdentity) @@ -385,8 +390,11 @@ private static IEnumerable GetMapping(TypeDeclarationSyntax sy { return syntax.Members.OfType() .Where( - z => z.AccessorList?.Accessors.Any(a => a.Keyword.Kind() == SyntaxKind.SetKeyword || a.Keyword.Kind() == SyntaxKind.InitKeyword) - == true + z => z.AccessorList?.Accessors.Any( + a => + a.Keyword.IsKind(SyntaxKind.SetKeyword) + || a.Keyword.IsKind(SyntaxKind.InitKeyword) + ) == true ) .Where(z => z.Identifier.Text != "Data") .Select( @@ -465,7 +473,7 @@ private static ConversionOperatorDeclarationSyntax GetConvertFromOperator(TypeDe Token(SyntaxKind.ImplicitKeyword), GenericName(identifier).WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList(IdentifierName("T")))) ) - .WithModifiers(TokenList(new[] { Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword) })) + .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword))) .WithParameterList( ParameterList( SingletonSeparatedList(Parameter(paramIdentifier).WithType(name)) @@ -557,7 +565,7 @@ private static PropertyDeclarationSyntax GetJDataProperty() ); } - static PropertyDeclarationSyntax GetPropertyImpl(PropertyDeclarationSyntax syntax) + private static PropertyDeclarationSyntax GetPropertyImpl(PropertyDeclarationSyntax syntax) { return syntax.WithAccessorList( AccessorList( @@ -847,7 +855,7 @@ static ParameterSyntax ArrayParameter(TypeSyntax typeName) static BaseMethodDeclarationSyntax AddConversionBody(TypeSyntax typeName, SyntaxToken collectionName, BaseMethodDeclarationSyntax syntax) { - TypeSyntax objectName = syntax is ConversionOperatorDeclarationSyntax d ? d.Type : syntax is MethodDeclarationSyntax m ? m.ReturnType : null!; + var objectName = syntax is ConversionOperatorDeclarationSyntax d ? d.Type : syntax is MethodDeclarationSyntax m ? m.ReturnType : null!; objectName = objectName.EnsureNotNullable(); return syntax .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword))) diff --git a/src/JsonRpc.Testing/JsonRpcTestBase.cs b/src/JsonRpc.Testing/JsonRpcTestBase.cs index 991ca6165..ddfc4b88f 100644 --- a/src/JsonRpc.Testing/JsonRpcTestBase.cs +++ b/src/JsonRpc.Testing/JsonRpcTestBase.cs @@ -1,9 +1,7 @@ using System; using System.Diagnostics; using System.Reactive; -using System.Reactive.Concurrency; using System.Reactive.Disposables; -using System.Reactive.Threading.Tasks; using System.Threading; using System.Threading.Tasks; @@ -35,8 +33,16 @@ public JsonRpcTestBase(JsonRpcTestOptions testOptions) public ISettler Events { get; } public JsonRpcTestOptions TestOptions { get; } public CancellationToken CancellationToken => _cancellationTokenSource.Token; - public Task SettleNext() => Events.SettleNext(); - public IObservable Settle() => Events.Settle(); + + public Task SettleNext() + { + return Events.SettleNext(); + } + + public IObservable Settle() + { + return Events.Settle(); + } public void Dispose() { diff --git a/src/JsonRpc/AssemblyScanningHandlerTypeDescriptorProvider.cs b/src/JsonRpc/AssemblyScanningHandlerTypeDescriptorProvider.cs index d880f1f57..6666c5361 100644 --- a/src/JsonRpc/AssemblyScanningHandlerTypeDescriptorProvider.cs +++ b/src/JsonRpc/AssemblyScanningHandlerTypeDescriptorProvider.cs @@ -31,7 +31,8 @@ public class HandlerTypeDescriptorHelper .FirstOrDefault(t => MethodAttribute.AllFrom(t).Any()); } - private static readonly Type[] HandlerTypes = { + private static readonly Type[] HandlerTypes = + { typeof(IJsonRpcNotificationHandler<>), typeof(IJsonRpcRequestHandler<>), typeof(IJsonRpcRequestHandler<,>), @@ -55,8 +56,8 @@ public static Type GetHandlerInterface(Type type) { if (IsValidInterface(type)) return type; return type.GetTypeInfo() - .ImplementedInterfaces - .First(IsValidInterface); + .ImplementedInterfaces + .First(IsValidInterface); } catch (Exception e) { @@ -64,15 +65,17 @@ public static Type GetHandlerInterface(Type type) } } - internal static Type? UnwrapGenericType(Type genericType, Type type, int arity = 0) => - type.GetTypeInfo() - .ImplementedInterfaces - .FirstOrDefault(x => x.GetTypeInfo().IsGenericType && x.GetTypeInfo().GetGenericTypeDefinition() == genericType) - ?.GetTypeInfo() - ?.GetGenericArguments()[arity]; + internal static Type? UnwrapGenericType(Type genericType, Type type, int arity = 0) + { + return type.GetTypeInfo() + .ImplementedInterfaces + .FirstOrDefault(x => x.GetTypeInfo().IsGenericType && x.GetTypeInfo().GetGenericTypeDefinition() == genericType) + ?.GetTypeInfo() + ?.GetGenericArguments()[arity]; + } } - class AssemblyScanningHandlerTypeDescriptorProvider : IHandlerTypeDescriptorProvider + internal class AssemblyScanningHandlerTypeDescriptorProvider : IHandlerTypeDescriptorProvider { private readonly ConcurrentDictionary _methodNames = new(); @@ -91,44 +94,52 @@ internal AssemblyScanningHandlerTypeDescriptorProvider(IEnumerable ass } } - internal static IEnumerable GetDescriptors(IEnumerable assemblies) => assemblies.SelectMany( - x => { - try - { - return x.GetTypes(); - } - catch - { - return Enumerable.Empty(); - } - } - ) - .Where(z => z.IsInterface || z.IsClass && !z.IsAbstract) - // running on mono this call can cause issues when scanning of the entire assembly. - .Where( - z => { - try - { - return typeof(IJsonRpcHandler).IsAssignableFrom(z); - } - catch - { - return false; - } - } - ) - .Where(z => MethodAttribute.From(z) != null) - .Where(z => !z.Name.EndsWith("Manager")) // Manager interfaces are generally specializations around the handlers - .Select(HandlerTypeDescriptorHelper.GetMethodType) - .Distinct() - .ToLookup(x => MethodAttribute.From(x)!.Method) - .SelectMany( - x => x - .Distinct() - .Select(z => new HandlerTypeDescriptor(z!) as IHandlerTypeDescriptor) - ); - - public IHandlerTypeDescriptor? GetHandlerTypeDescriptor() => GetHandlerTypeDescriptor(typeof(TA)); + internal static IEnumerable GetDescriptors(IEnumerable assemblies) + { + return assemblies.SelectMany( + x => + { + try + { + return x.GetTypes(); + } + catch + { + return Enumerable.Empty(); + } + } + ) + .Where(z => z.IsInterface || ( z.IsClass && !z.IsAbstract )) + // running on mono this call can cause issues when scanning of the entire assembly. + .Where( + z => + { + try + { + return typeof(IJsonRpcHandler).IsAssignableFrom(z); + } + catch + { + return false; + } + } + ) + .Where(z => MethodAttribute.From(z) != null) + .Where(z => !z.Name.EndsWith("Manager")) // Manager interfaces are generally specializations around the handlers + .Select(HandlerTypeDescriptorHelper.GetMethodType) + .Distinct() + .ToLookup(x => MethodAttribute.From(x)!.Method) + .SelectMany( + x => x + .Distinct() + .Select(z => new HandlerTypeDescriptor(z!) as IHandlerTypeDescriptor) + ); + } + + public IHandlerTypeDescriptor? GetHandlerTypeDescriptor() + { + return GetHandlerTypeDescriptor(typeof(TA)); + } public IHandlerTypeDescriptor? GetHandlerTypeDescriptor(Type type) { @@ -144,9 +155,15 @@ internal static IEnumerable GetDescriptors(IEnumerable() where T : IJsonRpcHandler => GetMethodName(typeof(T)); + public string? GetMethodName() where T : IJsonRpcHandler + { + return GetMethodName(typeof(T)); + } - public bool IsMethodName(string name, params Type[] types) => types.Any(z => GetMethodName(z)?.Equals(name) == true); + public bool IsMethodName(string name, params Type[] types) + { + return types.Any(z => GetMethodName(z)?.Equals(name) == true); + } public string? GetMethodName(Type type) { @@ -172,7 +189,7 @@ internal static IEnumerable GetDescriptors(IEnumerable + internal class AssemblyAttributeHandlerTypeDescriptorProvider : IHandlerTypeDescriptorProvider { private readonly ConcurrentDictionary _methodNames = new(); @@ -191,19 +208,25 @@ internal AssemblyAttributeHandlerTypeDescriptorProvider(IEnumerable as } } - internal static IEnumerable GetDescriptors(IEnumerable assemblies) => assemblies.SelectMany(x => x.GetCustomAttributes()) - .SelectMany(z => z.Types) - .Where(z => !z.Name.EndsWith("Manager")) // Manager interfaces are generally specializations around the handlers - .Select(HandlerTypeDescriptorHelper.GetMethodType) - .Distinct() - .ToLookup(x => MethodAttribute.From(x)!.Method) - .SelectMany( - x => x - .Distinct() - .Select(z => new HandlerTypeDescriptor(z!) as IHandlerTypeDescriptor) - ); + internal static IEnumerable GetDescriptors(IEnumerable assemblies) + { + return assemblies.SelectMany(x => x.GetCustomAttributes()) + .SelectMany(z => z.Types) + .Where(z => !z.Name.EndsWith("Manager")) // Manager interfaces are generally specializations around the handlers + .Select(HandlerTypeDescriptorHelper.GetMethodType) + .Distinct() + .ToLookup(x => MethodAttribute.From(x)!.Method) + .SelectMany( + x => x + .Distinct() + .Select(z => new HandlerTypeDescriptor(z!) as IHandlerTypeDescriptor) + ); + } - public IHandlerTypeDescriptor? GetHandlerTypeDescriptor() => GetHandlerTypeDescriptor(typeof(TA)); + public IHandlerTypeDescriptor? GetHandlerTypeDescriptor() + { + return GetHandlerTypeDescriptor(typeof(TA)); + } public IHandlerTypeDescriptor? GetHandlerTypeDescriptor(Type type) { @@ -219,9 +242,15 @@ internal static IEnumerable GetDescriptors(IEnumerable() where T : IJsonRpcHandler => GetMethodName(typeof(T)); + public string? GetMethodName() where T : IJsonRpcHandler + { + return GetMethodName(typeof(T)); + } - public bool IsMethodName(string name, params Type[] types) => types.Any(z => GetMethodName(z)?.Equals(name) == true); + public bool IsMethodName(string name, params Type[] types) + { + return types.Any(z => GetMethodName(z)?.Equals(name) == true); + } public string? GetMethodName(Type type) { diff --git a/src/JsonRpc/DefaultJsonRpcServerFacade.cs b/src/JsonRpc/DefaultJsonRpcServerFacade.cs index e9ef8a4d9..832446d68 100644 --- a/src/JsonRpc/DefaultJsonRpcServerFacade.cs +++ b/src/JsonRpc/DefaultJsonRpcServerFacade.cs @@ -20,20 +20,45 @@ public DefaultJsonRpcServerFacade(IResponseRouter requestRouter, IServiceProvide _handlersManager = handlersManager; } - public void SendNotification(string method) => _responseRouter.SendNotification(method); + public void SendNotification(string method) + { + _responseRouter.SendNotification(method); + } - public void SendNotification(string method, T @params) => _responseRouter.SendNotification(method, @params); + public void SendNotification(string method, T @params) + { + _responseRouter.SendNotification(method, @params); + } - public void SendNotification(IRequest request) => _responseRouter.SendNotification(request); + public void SendNotification(IRequest request) + { + _responseRouter.SendNotification(request); + } - public IResponseRouterReturns SendRequest(string method, T @params) => _responseRouter.SendRequest(method, @params); + public IResponseRouterReturns SendRequest(string method, T @params) + { + return _responseRouter.SendRequest(method, @params); + } - public IResponseRouterReturns SendRequest(string method) => _responseRouter.SendRequest(method); + public IResponseRouterReturns SendRequest(string method) + { + return _responseRouter.SendRequest(method); + } + + public Task SendRequest(IRequest request, CancellationToken cancellationToken) + { + return _responseRouter.SendRequest(request, cancellationToken); + } - public Task SendRequest(IRequest request, CancellationToken cancellationToken) => _responseRouter.SendRequest(request, cancellationToken); + bool IResponseRouter.TryGetRequest(long id, [NotNullWhen(true)] out string? method, [NotNullWhen(true)] out TaskCompletionSource? pendingTask) + { + return _responseRouter.TryGetRequest(id, out method, out pendingTask); + } - bool IResponseRouter.TryGetRequest(long id, [NotNullWhen(true)] out string method, [NotNullWhen(true)] out TaskCompletionSource pendingTask) => _responseRouter.TryGetRequest(id, out method, out pendingTask); - object IServiceProvider.GetService(Type serviceType) => _serviceProvider.GetService(serviceType); + object IServiceProvider.GetService(Type serviceType) + { + return _serviceProvider.GetService(serviceType); + } public IDisposable Register(Action registryAction) { diff --git a/src/JsonRpc/ErrorResponse.cs b/src/JsonRpc/ErrorResponse.cs index 5a499d6a9..1c119ddb3 100644 --- a/src/JsonRpc/ErrorResponse.cs +++ b/src/JsonRpc/ErrorResponse.cs @@ -21,10 +21,16 @@ public ErrorResponse(OutgoingResponse outgoingResponse) public bool IsError => Error != null; public RpcError? Error { get; } - public object? Value => IsResponse ? (object?) Response : IsError ? Error : null; + public object? Value => IsResponse ? Response : IsError ? Error : null; - public static implicit operator ErrorResponse(OutgoingResponse outgoingResponse) => new ErrorResponse(outgoingResponse); + public static implicit operator ErrorResponse(OutgoingResponse outgoingResponse) + { + return new ErrorResponse(outgoingResponse); + } - public static implicit operator ErrorResponse(RpcError error) => new ErrorResponse(error); + public static implicit operator ErrorResponse(RpcError error) + { + return new ErrorResponse(error); + } } } diff --git a/src/JsonRpc/IActivityTracingStrategy.cs b/src/JsonRpc/IActivityTracingStrategy.cs index 6a8837a81..40aaaa699 100644 --- a/src/JsonRpc/IActivityTracingStrategy.cs +++ b/src/JsonRpc/IActivityTracingStrategy.cs @@ -18,27 +18,33 @@ public interface IActivityTracingStrategy void ApplyOutgoing(ITraceData data); IDisposable? ApplyInbound(ITraceData data); } + internal static class Hex { - private static readonly byte[] HexBytes = new byte[] { (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f' }; + private static readonly byte[] HexBytes = + { + (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', + (byte)'d', (byte)'e', (byte)'f' + }; + private static readonly byte[] ReverseHexDigits = BuildReverseHexDigits(); internal static void Encode(ReadOnlySpan src, ref Span dest) { - Span bytes = MemoryMarshal.Cast(dest); + var bytes = MemoryMarshal.Cast(dest); // Inspired by http://stackoverflow.com/questions/623104/c-byte-to-hex-string/3974535#3974535 - int lengthInNibbles = src.Length * 2; + var lengthInNibbles = src.Length * 2; - for (int i = 0; i < (lengthInNibbles & -2); i++) + for (var i = 0; i < ( lengthInNibbles & -2 ); i++) { - int index0 = +i >> 1; - var b = (byte)(src[index0] >> 4); - bytes[(2 * i) + 1] = 0; + var index0 = +i >> 1; + var b = (byte)( src[index0] >> 4 ); + bytes[( 2 * i ) + 1] = 0; bytes[2 * i++] = HexBytes[b]; - b = (byte)(src[index0] & 0x0F); - bytes[(2 * i) + 1] = 0; + b = (byte)( src[index0] & 0x0F ); + bytes[( 2 * i ) + 1] = 0; bytes[2 * i] = HexBytes[b]; } @@ -47,12 +53,12 @@ internal static void Encode(ReadOnlySpan src, ref Span dest) internal static void Decode(ReadOnlySpan value, Span bytes) { - for (int i = 0; i < value.Length; i++) + for (var i = 0; i < value.Length; i++) { - int c1 = ReverseHexDigits[value[i++] - '0'] << 4; + var c1 = ReverseHexDigits[value[i++] - '0'] << 4; int c2 = ReverseHexDigits[value[i] - '0']; - bytes[i >> 1] = (byte)(c1 + c2); + bytes[i >> 1] = (byte)( c1 + c2 ); } } @@ -60,12 +66,12 @@ private static byte[] BuildReverseHexDigits() { var bytes = new byte['f' - '0' + 1]; - for (int i = 0; i < 10; i++) + for (var i = 0; i < 10; i++) { bytes[i] = (byte)i; } - for (int i = 10; i < 16; i++) + for (var i = 10; i < 16; i++) { bytes[i + 'a' - '0' - 0x0a] = (byte)i; bytes[i + 'A' - '0' - 0x0a] = (byte)i; @@ -94,16 +100,16 @@ internal TraceParent(string? traceparent) { if (traceparent is null) { - this.Version = 0; - this.Flags = TraceFlags.None; + Version = 0; + Flags = TraceFlags.None; return; } - ReadOnlySpan traceparentChars = traceparent.AsSpan(); + var traceparentChars = traceparent.AsSpan(); // Decode version - ReadOnlySpan slice = Consume(ref traceparentChars, VersionByteCount * 2); - fixed (byte* pVersion = &this.Version) + var slice = Consume(ref traceparentChars, VersionByteCount * 2); + fixed (byte* pVersion = &Version) { Hex.Decode(slice, new Span(pVersion, 1)); } @@ -112,7 +118,7 @@ internal TraceParent(string? traceparent) // Decode traceid slice = Consume(ref traceparentChars, TraceIdByteCount * 2); - fixed (byte* pTraceId = this.TraceId) + fixed (byte* pTraceId = TraceId) { Hex.Decode(slice, new Span(pTraceId, TraceIdByteCount)); } @@ -121,7 +127,7 @@ internal TraceParent(string? traceparent) // Decode parentid slice = Consume(ref traceparentChars, ParentIdByteCount * 2); - fixed (byte* pParentId = this.ParentId) + fixed (byte* pParentId = ParentId) { Hex.Decode(slice, new Span(pParentId, ParentIdByteCount)); } @@ -130,7 +136,7 @@ internal TraceParent(string? traceparent) // Decode flags slice = Consume(ref traceparentChars, FlagsByteCount * 2); - fixed (TraceFlags* pFlags = &this.Flags) + fixed (TraceFlags* pFlags = &Flags) { Hex.Decode(slice, new Span(pFlags, 1)); } @@ -147,7 +153,7 @@ static void ConsumeHyphen(ref ReadOnlySpan value) ReadOnlySpan Consume(ref ReadOnlySpan buffer, int length) { - ReadOnlySpan result = buffer.Slice(0, length); + var result = buffer.Slice(0, length); buffer = buffer.Slice(length); return result; } @@ -171,7 +177,7 @@ internal Guid TraceIdGuid { get { - fixed (byte* pTraceId = this.TraceId) + fixed (byte* pTraceId = TraceId) { return CopyBufferToGuid(new ReadOnlySpan(pTraceId, TraceIdByteCount)); } @@ -181,31 +187,32 @@ internal Guid TraceIdGuid public override string ToString() { // When calculating the number of characters required, double each 'byte' we have to encode since we're using hex. - Span traceparent = stackalloc char[(VersionByteCount * 2) + 1 + (TraceIdByteCount * 2) + 1 + (ParentIdByteCount * 2) + 1 + (FlagsByteCount * 2)]; - Span traceParentRemaining = traceparent; + Span traceparent = + stackalloc char[( VersionByteCount * 2 ) + 1 + ( TraceIdByteCount * 2 ) + 1 + ( ParentIdByteCount * 2 ) + 1 + ( FlagsByteCount * 2 )]; + var traceParentRemaining = traceparent; - fixed (byte* pVersion = &this.Version) + fixed (byte* pVersion = &Version) { Hex.Encode(new ReadOnlySpan(pVersion, 1), ref traceParentRemaining); } AddHyphen(ref traceParentRemaining); - fixed (byte* pTraceId = this.TraceId) + fixed (byte* pTraceId = TraceId) { Hex.Encode(new ReadOnlySpan(pTraceId, TraceIdByteCount), ref traceParentRemaining); } AddHyphen(ref traceParentRemaining); - fixed (byte* pParentId = this.ParentId) + fixed (byte* pParentId = ParentId) { Hex.Encode(new ReadOnlySpan(pParentId, ParentIdByteCount), ref traceParentRemaining); } AddHyphen(ref traceParentRemaining); - fixed (TraceFlags* pFlags = &this.Flags) + fixed (TraceFlags* pFlags = &Flags) { Hex.Encode(new ReadOnlySpan(pFlags, 1), ref traceParentRemaining); } @@ -224,7 +231,7 @@ static void AddHyphen(ref Span value) } } - private static unsafe Guid CopyBufferToGuid(ReadOnlySpan buffer) + private static Guid CopyBufferToGuid(ReadOnlySpan buffer) { Debug.Assert(buffer.Length == 16, "Guid buffer length mismatch."); fixed (byte* pBuffer = buffer) @@ -248,7 +255,7 @@ public static string? TraceState } /// - /// Gets or sets the that will receive the activity transfer, start and stop events . + /// Gets or sets the that will receive the activity transfer, start and stop events . /// public TraceSource? TraceSource { get; set; } @@ -261,7 +268,8 @@ public unsafe void ApplyOutgoing(ITraceData data) FillRandomBytes(new Span(traceparent.ParentId, TraceParent.ParentIdByteCount)); CopyGuidToBuffer(Trace.CorrelationManager.ActivityId, new Span(traceparent.TraceId, TraceParent.TraceIdByteCount)); - if (this.TraceSource is object && (this.TraceSource.Switch.Level & SourceLevels.ActivityTracing) == SourceLevels.ActivityTracing && this.TraceSource.Listeners.Count > 0) + if (TraceSource is { } && ( TraceSource.Switch.Level & SourceLevels.ActivityTracing ) == SourceLevels.ActivityTracing + && TraceSource.Listeners.Count > 0) { traceparent.Flags |= TraceParent.TraceFlags.Sampled; } @@ -271,21 +279,24 @@ public unsafe void ApplyOutgoing(ITraceData data) } } - /// - public unsafe IDisposable? ApplyInbound(ITraceData request) + /// + public IDisposable? ApplyInbound(ITraceData request) { var traceparent = new TraceParent(request.TraceParent); - Guid childActivityId = Guid.NewGuid(); - string? activityName = request is IMethodWithParams p ? p.Method : null; + var childActivityId = Guid.NewGuid(); + var activityName = request is IMethodWithParams p ? p.Method : null; - return new ActivityState(request, this.TraceSource, activityName, traceparent.TraceIdGuid, childActivityId); + return new ActivityState(request, TraceSource, activityName, traceparent.TraceIdGuid, childActivityId); } - private static void FillRandomBytes(Span buffer) => CopyGuidToBuffer(Guid.NewGuid(), buffer); + private static void FillRandomBytes(Span buffer) + { + CopyGuidToBuffer(Guid.NewGuid(), buffer); + } - private unsafe static void CopyGuidToBuffer(Guid guid, Span buffer) + private static unsafe void CopyGuidToBuffer(Guid guid, Span buffer) { - ReadOnlySpan guidBytes = new ReadOnlySpan(&guid, sizeof(Guid)); + var guidBytes = new ReadOnlySpan(&guid, sizeof(Guid)); guidBytes.Slice(0, buffer.Length).CopyTo(buffer); } @@ -294,17 +305,17 @@ private class ActivityState : IDisposable private readonly TraceSource? traceSource; private readonly Guid originalActivityId; private readonly string? originalTraceState; - private readonly string? activityName; + private readonly string activityName; private readonly Guid parentTraceId; internal ActivityState(ITraceData request, TraceSource? traceSource, string? activityName, Guid parentTraceId, Guid childTraceId) { - this.originalActivityId = Trace.CorrelationManager.ActivityId; - this.originalTraceState = TraceState; - this.activityName = activityName; + originalActivityId = Trace.CorrelationManager.ActivityId; + originalTraceState = TraceState; + this.activityName = activityName ?? ""; this.parentTraceId = parentTraceId; - if (traceSource is object && parentTraceId != Guid.Empty) + if (traceSource is { } && parentTraceId != Guid.Empty) { // We set ActivityId to a short-lived value here for the sake of the TraceTransfer call that comes next. // TraceTransfer goes from the current activity to the one passed as an argument. @@ -323,31 +334,29 @@ internal ActivityState(ITraceData request, TraceSource? traceSource, string? act public void Dispose() { - this.traceSource?.TraceEvent(TraceEventType.Stop, 0, this.activityName); + traceSource?.TraceEvent(TraceEventType.Stop, 0, activityName); - if (this.parentTraceId != Guid.Empty) + if (parentTraceId != Guid.Empty) { - this.traceSource?.TraceTransfer(0, nameof(TraceEventType.Transfer), this.parentTraceId); + traceSource?.TraceTransfer(0, nameof(TraceEventType.Transfer), parentTraceId); } - Trace.CorrelationManager.ActivityId = this.originalActivityId; - TraceState = this.originalTraceState; + Trace.CorrelationManager.ActivityId = originalActivityId; + TraceState = originalTraceState; } } } public interface ITraceData { - - /// /// Gets or sets the data for the W3C Trace Context traceparent value. /// - string? TraceParent { get; set; } + string? TraceParent { get; set; } /// /// Gets or sets the data for the W3C Trace Context tracestate value. /// - string? TraceState { get; set; } + string? TraceState { get; set; } } } diff --git a/src/JsonRpc/IJsonRpcRequestHandler.cs b/src/JsonRpc/IJsonRpcRequestHandler.cs index 3a885c86b..59f4f3a46 100644 --- a/src/JsonRpc/IJsonRpcRequestHandler.cs +++ b/src/JsonRpc/IJsonRpcRequestHandler.cs @@ -6,7 +6,7 @@ namespace OmniSharp.Extensions.JsonRpc /// /// Client --> --> /// | - /// Server <-- <-- + /// Server (-- (-- /// /// /// @@ -20,7 +20,7 @@ public interface IJsonRpcRequestHandler : IRequestHandle /// /// Client --> --> /// | - /// Server <-- <-- + /// Server (-- (-- /// /// /// diff --git a/src/JsonRpc/IResponseHandler.cs b/src/JsonRpc/IResponseHandler.cs index cd02f2875..2090791e0 100644 --- a/src/JsonRpc/IResponseHandler.cs +++ b/src/JsonRpc/IResponseHandler.cs @@ -6,7 +6,7 @@ namespace OmniSharp.Extensions.JsonRpc /// /// Server --> --> /// | - /// Client <-- <-- + /// Client (-- (-- /// /// /// diff --git a/src/JsonRpc/IResponseRouter.cs b/src/JsonRpc/IResponseRouter.cs index 6d3337ee2..6fa2ba15a 100644 --- a/src/JsonRpc/IResponseRouter.cs +++ b/src/JsonRpc/IResponseRouter.cs @@ -14,6 +14,6 @@ public interface IResponseRouter IResponseRouterReturns SendRequest(string method, T @params); IResponseRouterReturns SendRequest(string method); Task SendRequest(IRequest request, CancellationToken cancellationToken); - bool TryGetRequest(long id, [NotNullWhen(true)] out string method, [NotNullWhen(true)] out TaskCompletionSource pendingTask); + bool TryGetRequest(long id, [NotNullWhen(true)] out string? method, [NotNullWhen(true)] out TaskCompletionSource? pendingTask); } } diff --git a/src/JsonRpc/InputHandler.cs b/src/JsonRpc/InputHandler.cs index d2f9cdfdb..38f4d25c3 100644 --- a/src/JsonRpc/InputHandler.cs +++ b/src/JsonRpc/InputHandler.cs @@ -83,15 +83,18 @@ IScheduler scheduler new RequestInvokerOptions( requestTimeout, supportContentModified, - concurrency ?? 0), + concurrency ?? 0 + ), loggerFactory, - scheduler), + scheduler + ), loggerFactory, unhandledInputProcessException, - getException) + getException + ) { } - + public InputHandler( PipeReader pipeReader, IOutputHandler outputHandler, @@ -120,7 +123,8 @@ public InputHandler( new Memory(_contentLengthValueBuffer); // Max string length of the long value _stopProcessing = new CancellationTokenSource(); - _disposable = new CompositeDisposable { + _disposable = new CompositeDisposable + { Disposable.Create(() => _stopProcessing.Cancel()), _stopProcessing, _requestInvoker, @@ -133,16 +137,19 @@ public InputHandler( public void Start() { _disposable.Add( - Observable.FromAsync(async () => { - try + Observable.FromAsync( + async () => { - await ProcessInputStream(_stopProcessing.Token).ConfigureAwait(false); - } - catch (Exception e) - { - _logger.LogCritical(e, "unhandled exception"); + try + { + await ProcessInputStream(_stopProcessing.Token).ConfigureAwait(false); + } + catch (Exception e) + { + _logger.LogCritical(e, "unhandled exception"); + } } - }).Subscribe(_inputActive) + ).Subscribe(_inputActive) ); _disposable.Add( _inputQueue @@ -250,7 +257,7 @@ private bool TryParseContentLength(ref ReadOnlySequence buffer, out long l return false; } - var slice = buffer.Slice(0, colon!.Value); + var slice = buffer.Slice(0, colon.Value); slice.CopyTo(_contentLengthBuffer.Span); if (IsEqual(_contentLengthBuffer.Span, ContentLength)) @@ -280,7 +287,7 @@ private bool TryParseContentLength(ref ReadOnlySequence buffer, out long l var whitespacePosition = lengthSlice.PositionOf((byte)' '); if (whitespacePosition.HasValue) { - lengthSlice = lengthSlice.Slice(0, whitespacePosition!.Value); + lengthSlice = lengthSlice.Slice(0, whitespacePosition.Value); } lengthSlice.CopyTo(_contentLengthValueMemory.Span); @@ -415,7 +422,8 @@ private void HandleRequest(in ReadOnlySequence request) _inputQueue.OnNext( Observable.Create( - observer => { + observer => + { if (response is ServerResponse serverResponse) { // _logger.LogDebug("Setting successful Response for {ResponseId}", response.Id); @@ -455,7 +463,7 @@ private void HandleRequest(in ReadOnlySequence request) var requestHandle = _requestInvoker.InvokeRequest(descriptor, item.Request); _requests.TryAdd(requestHandle.Request.Id, requestHandle); - requestHandle.OnComplete += (request) => _requests.TryRemove(request.Id, out _); + requestHandle.OnComplete += r => _requests.TryRemove(r.Id, out _); } catch (JsonReaderException e) { @@ -480,11 +488,11 @@ private void HandleRequest(in ReadOnlySequence request) var cancelParams = item.Notification.Params?.ToObject(); if (cancelParams == null) { - _logger.LogDebug("Got incorrect cancellation params", item.Notification.Method); + _logger.LogDebug("Got incorrect cancellation params for {Method}", item.Notification.Method); continue; } - _logger.LogDebug("Cancelling pending request", item.Notification.Method); + _logger.LogDebug("Cancelling pending request for {Method}", item.Notification.Method); if (_requests.TryGetValue(cancelParams.Id, out var requestHandle)) { requestHandle.CancellationTokenSource.Cancel(); @@ -522,8 +530,10 @@ private void HandleRequest(in ReadOnlySequence request) } } - private static Exception DefaultErrorParser(string? method, ServerError error, CreateResponseExceptionHandler? customHandler) => - error.Error.Code switch { + private static Exception DefaultErrorParser(string? method, ServerError error, CreateResponseExceptionHandler? customHandler) + { + return error.Error.Code switch + { ErrorCodes.ServerNotInitialized => new ServerNotInitializedException(error.Id), ErrorCodes.MethodNotSupported => new MethodNotSupportedException(error.Id, method ?? "UNKNOWN"), ErrorCodes.InvalidRequest => new InvalidRequestException(error.Id), @@ -540,5 +550,6 @@ private static Exception DefaultErrorParser(string? method, ServerError error, C error.Error.Data?.ToString() ?? string.Empty ) }; + } } } diff --git a/src/JsonRpc/JsonRpcCommonMethodsBase.cs b/src/JsonRpc/JsonRpcCommonMethodsBase.cs index 81898519e..da1536d7c 100644 --- a/src/JsonRpc/JsonRpcCommonMethodsBase.cs +++ b/src/JsonRpc/JsonRpcCommonMethodsBase.cs @@ -11,73 +11,119 @@ public abstract class JsonRpcCommonMethodsBase : IJsonRpcHandlerRegistry w { #region OnRequest / OnNotification - public T OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions? options = null) => - AddHandler(method, _ => new DelegatingJsonRequestHandler(handler), options); - - public T OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions? options = null) => - OnJsonRequest(method, HandlerAdapter.Adapt(handler), options); - - public T OnRequest(string method, Func> handler, JsonRpcHandlerOptions? options = null) => - OnRequest(method, HandlerAdapter.Adapt(handler), options); - - public T OnRequest(string method, Func> handler, JsonRpcHandlerOptions? options = null) => - OnRequest(method, (_, _) => handler(), options); - - public T OnRequest(string method, Func> handler, JsonRpcHandlerOptions? options = null) => AddHandler( - method, _ => new DelegatingRequestHandler(_.GetRequiredService(), handler), options - ); - - public T OnRequest(string method, Func> handler, JsonRpcHandlerOptions? options = null) => - OnRequest(method, (_, cancellationToken) => handler(cancellationToken), options); - - public T OnRequest(string method, Func handler, JsonRpcHandlerOptions? options = null) => - OnRequest(method, HandlerAdapter.Adapt(handler), options); - - public T OnRequest(string method, Func handler, JsonRpcHandlerOptions? options = null) => AddHandler( - method, _ => new DelegatingRequestHandler(_.GetRequiredService(), handler), options - ); - - public T OnRequest(string method, Func handler, JsonRpcHandlerOptions? options = null) => - OnRequest(method, (_, cancellationToken) => handler(cancellationToken), options); - - public T OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions? options = null) => - OnJsonNotification(method, HandlerAdapter.Adapt(handler), options); - - public T OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions? options = null) => - OnJsonNotification(method, HandlerAdapter.Adapt(handler), options); - - public T OnJsonNotification(string method, Func handler, JsonRpcHandlerOptions? options = null) => - AddHandler(method, _ => new DelegatingJsonNotificationHandler(handler), options); - - public T OnJsonNotification(string method, Func handler, JsonRpcHandlerOptions? options = null) => - OnJsonNotification(method, HandlerAdapter.Adapt(handler), options); - - public T OnNotification(string method, Action handler, JsonRpcHandlerOptions? options = null) => - OnNotification(method, HandlerAdapter.Adapt(handler), options); - - public T OnNotification(string method, Action handler, JsonRpcHandlerOptions? options = null) => - OnNotification(method, HandlerAdapter.Adapt(handler), options); - - public T OnNotification(string method, Func handler, JsonRpcHandlerOptions? options = null) => AddHandler( - method, _ => new DelegatingNotificationHandler(_.GetRequiredService(), handler), options - ); - - public T OnNotification(string method, Func handler, JsonRpcHandlerOptions? options = null) => - OnNotification(method, HandlerAdapter.Adapt(handler), options); - - public T OnNotification(string method, Action handler, JsonRpcHandlerOptions? options = null) => - OnNotification( - method, (_, _) => { + public T OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions? options = null) + { + return AddHandler(method, _ => new DelegatingJsonRequestHandler(handler), options); + } + + public T OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions? options = null) + { + return OnJsonRequest(method, HandlerAdapter.Adapt(handler), options); + } + + public T OnRequest(string method, Func> handler, JsonRpcHandlerOptions? options = null) + { + return OnRequest(method, HandlerAdapter.Adapt(handler), options); + } + + public T OnRequest(string method, Func> handler, JsonRpcHandlerOptions? options = null) + { + return OnRequest(method, (_, _) => handler(), options); + } + + public T OnRequest(string method, Func> handler, JsonRpcHandlerOptions? options = null) + { + return AddHandler( + method, _ => new DelegatingRequestHandler(_.GetRequiredService(), handler), options + ); + } + + public T OnRequest(string method, Func> handler, JsonRpcHandlerOptions? options = null) + { + return OnRequest(method, (_, cancellationToken) => handler(cancellationToken), options); + } + + public T OnRequest(string method, Func handler, JsonRpcHandlerOptions? options = null) + { + return OnRequest(method, HandlerAdapter.Adapt(handler), options); + } + + public T OnRequest(string method, Func handler, JsonRpcHandlerOptions? options = null) + { + return AddHandler( + method, _ => new DelegatingRequestHandler(_.GetRequiredService(), handler), options + ); + } + + public T OnRequest(string method, Func handler, JsonRpcHandlerOptions? options = null) + { + return OnRequest(method, (_, cancellationToken) => handler(cancellationToken), options); + } + + public T OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions? options = null) + { + return OnJsonNotification(method, HandlerAdapter.Adapt(handler), options); + } + + public T OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions? options = null) + { + return OnJsonNotification(method, HandlerAdapter.Adapt(handler), options); + } + + public T OnJsonNotification(string method, Func handler, JsonRpcHandlerOptions? options = null) + { + return AddHandler(method, _ => new DelegatingJsonNotificationHandler(handler), options); + } + + public T OnJsonNotification(string method, Func handler, JsonRpcHandlerOptions? options = null) + { + return OnJsonNotification(method, HandlerAdapter.Adapt(handler), options); + } + + public T OnNotification(string method, Action handler, JsonRpcHandlerOptions? options = null) + { + return OnNotification(method, HandlerAdapter.Adapt(handler), options); + } + + public T OnNotification(string method, Action handler, JsonRpcHandlerOptions? options = null) + { + return OnNotification(method, HandlerAdapter.Adapt(handler), options); + } + + public T OnNotification(string method, Func handler, JsonRpcHandlerOptions? options = null) + { + return AddHandler( + method, _ => new DelegatingNotificationHandler(_.GetRequiredService(), handler), options + ); + } + + public T OnNotification(string method, Func handler, JsonRpcHandlerOptions? options = null) + { + return OnNotification(method, HandlerAdapter.Adapt(handler), options); + } + + public T OnNotification(string method, Action handler, JsonRpcHandlerOptions? options = null) + { + return OnNotification( + method, (_, _) => + { handler(); return Task.CompletedTask; }, options ); + } - public T OnNotification(string method, Func handler, JsonRpcHandlerOptions? options = null) => AddHandler( - method, _ => new DelegatingNotificationHandler(_.GetRequiredService(), (_, token) => handler(token)), options - ); + public T OnNotification(string method, Func handler, JsonRpcHandlerOptions? options = null) + { + return AddHandler( + method, _ => new DelegatingNotificationHandler(_.GetRequiredService(), (_, token) => handler(token)), options + ); + } - public T OnNotification(string method, Func handler, JsonRpcHandlerOptions? options = null) => OnNotification(method, _ => handler(), options); + public T OnNotification(string method, Func handler, JsonRpcHandlerOptions? options = null) + { + return OnNotification(method, _ => handler(), options); + } #endregion diff --git a/src/JsonRpc/JsonRpcServerBase.cs b/src/JsonRpc/JsonRpcServerBase.cs index 123627289..2a5aeed03 100644 --- a/src/JsonRpc/JsonRpcServerBase.cs +++ b/src/JsonRpc/JsonRpcServerBase.cs @@ -17,19 +17,39 @@ protected JsonRpcServerBase(IHandlersManager handlersManager, IResponseRouter re public IResponseRouter ResponseRouter { get; } public IHandlersManager HandlersManager { get; } - public void SendNotification(string method) => ResponseRouter.SendNotification(method); + public void SendNotification(string method) + { + ResponseRouter.SendNotification(method); + } - public void SendNotification(string method, T @params) => ResponseRouter.SendNotification(method, @params); + public void SendNotification(string method, T @params) + { + ResponseRouter.SendNotification(method, @params); + } - public void SendNotification(IRequest @params) => ResponseRouter.SendNotification(@params); + public void SendNotification(IRequest @params) + { + ResponseRouter.SendNotification(@params); + } - public Task SendRequest(IRequest @params, CancellationToken cancellationToken) => ResponseRouter.SendRequest(@params, cancellationToken); + public Task SendRequest(IRequest @params, CancellationToken cancellationToken) + { + return ResponseRouter.SendRequest(@params, cancellationToken); + } - public IResponseRouterReturns SendRequest(string method, T @params) => ResponseRouter.SendRequest(method, @params); + public IResponseRouterReturns SendRequest(string method, T @params) + { + return ResponseRouter.SendRequest(method, @params); + } - public IResponseRouterReturns SendRequest(string method) => ResponseRouter.SendRequest(method); + public IResponseRouterReturns SendRequest(string method) + { + return ResponseRouter.SendRequest(method); + } - bool IResponseRouter.TryGetRequest(long id, [NotNullWhen(true)] out string method, [NotNullWhen(true)] out TaskCompletionSource pendingTask) => - ResponseRouter.TryGetRequest(id, out method, out pendingTask); + bool IResponseRouter.TryGetRequest(long id, [NotNullWhen(true)] out string? method, [NotNullWhen(true)] out TaskCompletionSource? pendingTask) + { + return ResponseRouter.TryGetRequest(id, out method, out pendingTask); + } } } diff --git a/src/JsonRpc/NoopResponseRouter.cs b/src/JsonRpc/NoopResponseRouter.cs index 52a78648f..7816d40d1 100644 --- a/src/JsonRpc/NoopResponseRouter.cs +++ b/src/JsonRpc/NoopResponseRouter.cs @@ -29,13 +29,22 @@ public void SendNotification(IRequest request) { } - public IResponseRouterReturns SendRequest(string method, T @params) => new Impl(); + public IResponseRouterReturns SendRequest(string method, T @params) + { + return new Impl(); + } - public IResponseRouterReturns SendRequest(string method) => new Impl(); + public IResponseRouterReturns SendRequest(string method) + { + return new Impl(); + } - public Task SendRequest(IRequest request, CancellationToken cancellationToken) => Task.FromResult(default!); + public Task SendRequest(IRequest request, CancellationToken cancellationToken) + { + return Task.FromResult(default!); + } - bool IResponseRouter.TryGetRequest(long id, [NotNullWhen(true)] out string method, [NotNullWhen(true)] out TaskCompletionSource pendingTask) + bool IResponseRouter.TryGetRequest(long id, [NotNullWhen(true)] out string? method, [NotNullWhen(true)] out TaskCompletionSource? pendingTask) { method = default!; pendingTask = default!; @@ -44,9 +53,15 @@ bool IResponseRouter.TryGetRequest(long id, [NotNullWhen(true)] out string metho private class Impl : IResponseRouterReturns { - public Task Returning(CancellationToken cancellationToken) => Task.FromResult(default!); + public Task Returning(CancellationToken cancellationToken) + { + return Task.FromResult(default!); + } - public Task ReturningVoid(CancellationToken cancellationToken) => Task.CompletedTask; + public Task ReturningVoid(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } } } } diff --git a/src/JsonRpc/OutputHandler.cs b/src/JsonRpc/OutputHandler.cs index 4402c7c28..5edc7c469 100644 --- a/src/JsonRpc/OutputHandler.cs +++ b/src/JsonRpc/OutputHandler.cs @@ -3,11 +3,9 @@ using System.ComponentModel; using System.IO.Pipelines; using System.Linq; -using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; -using System.Reactive.Subjects; using System.Text; using System.Threading; using System.Threading.Channels; @@ -30,7 +28,6 @@ public class OutputHandler : IOutputHandler private readonly TaskCompletionSource _outputIsFinished; private readonly CompositeDisposable _disposable; private bool _delayComplete; - private readonly CancellationTokenSource _stopProcessing; private readonly Channel _channel; private readonly ChannelWriter _writer; @@ -52,7 +49,8 @@ public OutputHandler( _outputIsFinished = new TaskCompletionSource(); _channel = Channel.CreateUnbounded( - new UnboundedChannelOptions() { + new UnboundedChannelOptions + { AllowSynchronousContinuations = true, SingleReader = true, SingleWriter = false @@ -61,11 +59,12 @@ public OutputHandler( _queue = _channel.Reader; _writer = _channel.Writer; - _stopProcessing = new CancellationTokenSource(); - _disposable = new CompositeDisposable { - Disposable.Create(() => _stopProcessing.Cancel()), - _stopProcessing, - Observable.FromAsync(() => ProcessOutputStream(_stopProcessing.Token)) + var stopProcessing = new CancellationTokenSource(); + _disposable = new CompositeDisposable + { + Disposable.Create(() => stopProcessing.Cancel()), + stopProcessing, + Observable.FromAsync(() => ProcessOutputStream(stopProcessing.Token)) .Do(_ => { }, e => _logger.LogCritical(e, "unhandled exception")) .Subscribe() }; @@ -141,7 +140,8 @@ private async Task ProcessOutputStream(CancellationToken cancellationToken) // TODO: this will be part of the serialization refactor to make streaming first class var content = _serializer.SerializeObject(value); var contentBytes = Encoding.UTF8.GetBytes(content).AsMemory(); - await _pipeWriter.WriteAsync(Encoding.UTF8.GetBytes($"Content-Length: {contentBytes.Length}\r\n\r\n"), cancellationToken).ConfigureAwait(false); + await _pipeWriter.WriteAsync(Encoding.UTF8.GetBytes($"Content-Length: {contentBytes.Length}\r\n\r\n"), cancellationToken) + .ConfigureAwait(false); await _pipeWriter.WriteAsync(contentBytes, cancellationToken).ConfigureAwait(false); await _pipeWriter.FlushAsync(cancellationToken).ConfigureAwait(false); } while (true); @@ -163,7 +163,10 @@ private async Task ProcessOutputStream(CancellationToken cancellationToken) } } - public Task WaitForShutdown() => _outputIsFinished.Task; + public Task WaitForShutdown() + { + return _outputIsFinished.Task; + } private void Error(Exception ex) { diff --git a/src/JsonRpc/Receiver.cs b/src/JsonRpc/Receiver.cs index 201d7f233..017c879d7 100644 --- a/src/JsonRpc/Receiver.cs +++ b/src/JsonRpc/Receiver.cs @@ -27,7 +27,10 @@ public bool IsValid(JToken container) return false; } - public void Initialized() => _initialized = true; + public void Initialized() + { + _initialized = true; + } public virtual (IEnumerable results, bool hasResponse) GetRequests(JToken container) { @@ -63,9 +66,12 @@ protected virtual Renor GetRenor(JToken @object) // ReSharper disable once AssignmentInConditionalExpression if (hasRequestId = request.TryGetValue("id", out var id)) { - var idString = id.Type == JTokenType.String ? (string) id : null; - var idLong = id.Type == JTokenType.Integer ? (long?) id : null; - requestId = idString ?? ( idLong.HasValue ? (object) idLong.Value : null ); + requestId = id switch + { + { Type: JTokenType.String } => id.Value(), + { Type: JTokenType.Integer } => id.Value(), + _ => null + }; } if (hasRequestId && request.TryGetValue("result", out var response)) @@ -109,20 +115,23 @@ protected virtual Renor GetRenor(JToken @object) // !id == notification if (!hasRequestId) { - return new Notification(method!, @params) { + return new Notification(method!, @params) + { TraceState = traceState, TraceParent = traceParent, }; } - else + + return new Request(requestId!, method!, @params) { - return new Request(requestId!, method!, @params) { - TraceState = traceState, - TraceParent = traceParent, - }; - } + TraceState = traceState, + TraceParent = traceParent, + }; } - public bool ShouldOutput(object value) => _initialized; + public bool ShouldOutput(object value) + { + return _initialized; + } } } diff --git a/src/JsonRpc/ResponseRouter.cs b/src/JsonRpc/ResponseRouter.cs index 4ef205245..d66afc528 100644 --- a/src/JsonRpc/ResponseRouter.cs +++ b/src/JsonRpc/ResponseRouter.cs @@ -18,38 +18,57 @@ internal class ResponseRouter : IResponseRouter internal readonly ConcurrentDictionary pendingTask)> Requests = new ConcurrentDictionary pendingTask)>(); - public ResponseRouter(Lazy outputHandler, ISerializer serializer, IHandlerTypeDescriptorProvider handlerTypeDescriptorProvider) + public ResponseRouter( + Lazy outputHandler, ISerializer serializer, IHandlerTypeDescriptorProvider handlerTypeDescriptorProvider + ) { OutputHandler = outputHandler; Serializer = serializer; _handlerTypeDescriptorProvider = handlerTypeDescriptorProvider; } - public void SendNotification(string method) => + public void SendNotification(string method) + { OutputHandler.Value.Send( - new OutgoingNotification { + new OutgoingNotification + { Method = method } ); + } - public void SendNotification(string method, T @params) => + public void SendNotification(string method, T @params) + { OutputHandler.Value.Send( - new OutgoingNotification { + new OutgoingNotification + { Method = method, Params = @params } ); + } - public void SendNotification(IRequest @params) => SendNotification(GetMethodName(@params.GetType()), @params); + public void SendNotification(IRequest @params) + { + SendNotification(GetMethodName(@params.GetType()), @params); + } - public Task SendRequest(IRequest @params, CancellationToken cancellationToken) => - SendRequest(GetMethodName(@params.GetType()), @params).Returning(cancellationToken); + public Task SendRequest(IRequest @params, CancellationToken cancellationToken) + { + return SendRequest(GetMethodName(@params.GetType()), @params).Returning(cancellationToken); + } - public IResponseRouterReturns SendRequest(string method) => new ResponseRouterReturnsImpl(this, method, new object()); + public IResponseRouterReturns SendRequest(string method) + { + return new ResponseRouterReturnsImpl(this, method, new object()); + } - public IResponseRouterReturns SendRequest(string method, T @params) => new ResponseRouterReturnsImpl(this, method, @params); + public IResponseRouterReturns SendRequest(string method, T @params) + { + return new ResponseRouterReturnsImpl(this, method, @params); + } - public bool TryGetRequest(long id, [NotNullWhen(true)] out string method, [NotNullWhen(true)] out TaskCompletionSource pendingTask) + public bool TryGetRequest(long id, [NotNullWhen(true)] out string? method, [NotNullWhen(true)] out TaskCompletionSource? pendingTask) { var result = Requests.TryGetValue(id, out var source); method = source.method; @@ -57,8 +76,11 @@ public bool TryGetRequest(long id, [NotNullWhen(true)] out string method, [NotNu return result; } - private string GetMethodName(Type type) => - _handlerTypeDescriptorProvider.GetMethodName(type) ?? throw new NotSupportedException($"Unable to infer method name for type {type.FullName}"); + private string GetMethodName(Type type) + { + return _handlerTypeDescriptorProvider.GetMethodName(type) + ?? throw new NotSupportedException($"Unable to infer method name for type {type.FullName}"); + } private class ResponseRouterReturnsImpl : IResponseRouterReturns { @@ -84,14 +106,16 @@ public async Task Returning(CancellationToken cancellation try { _router.OutputHandler.Value.Send( - new OutgoingRequest { + new OutgoingRequest + { Method = _method, Params = _params, Id = nextId } ); cancellationToken.Register( - () => { + () => + { if (tcs.Task.IsCompleted) return; _router.CancelRequest(new CancelParams { Id = nextId }); } @@ -100,7 +124,7 @@ public async Task Returning(CancellationToken cancellation var result = await tcs.Task.ConfigureAwait(false); if (typeof(TResponse) == typeof(Unit)) { - return (TResponse) (object) Unit.Value; + return (TResponse)(object)Unit.Value; } return result.ToObject(_router.Serializer.JsonSerializer); @@ -111,7 +135,10 @@ public async Task Returning(CancellationToken cancellation } } - public async Task ReturningVoid(CancellationToken cancellationToken) => await Returning(cancellationToken).ConfigureAwait(false); + public async Task ReturningVoid(CancellationToken cancellationToken) + { + await Returning(cancellationToken).ConfigureAwait(false); + } } } } diff --git a/src/JsonRpc/Serialization/Converters/EnumLikeStringConverter.cs b/src/JsonRpc/Serialization/Converters/EnumLikeStringConverter.cs index 6ff70ff86..ae1c7298d 100644 --- a/src/JsonRpc/Serialization/Converters/EnumLikeStringConverter.cs +++ b/src/JsonRpc/Serialization/Converters/EnumLikeStringConverter.cs @@ -4,21 +4,27 @@ namespace OmniSharp.Extensions.JsonRpc.Serialization.Converters { - internal class EnumLikeStringConverter : JsonConverter + internal class EnumLikeStringConverter : JsonConverter { - public override void WriteJson(JsonWriter writer, IEnumLikeString value, JsonSerializer serializer) => new JValue(value.ToString()).WriteTo(writer); + public override void WriteJson(JsonWriter writer, IEnumLikeString? value, JsonSerializer serializer) + { + new JValue(value?.ToString()).WriteTo(writer); + } - public override IEnumLikeString ReadJson( - JsonReader reader, Type objectType, IEnumLikeString existingValue, + public override IEnumLikeString? ReadJson( + JsonReader reader, Type objectType, IEnumLikeString? existingValue, bool hasExistingValue, JsonSerializer serializer - ) => - ( reader.TokenType, Nullable.GetUnderlyingType(objectType) ) switch { - (JsonToken.String, null) => (IEnumLikeString) Activator.CreateInstance(objectType, (string) reader.Value), - (JsonToken.String, { } realType) => (IEnumLikeString) Activator.CreateInstance(realType, (string) reader.Value), - (_, { }) => (IEnumLikeString) Activator.CreateInstance(objectType, null), + ) + { + return ( reader.TokenType, Nullable.GetUnderlyingType(objectType) ) switch + { + (JsonToken.String, null) => (IEnumLikeString)Activator.CreateInstance(objectType, (string)reader.Value), + (JsonToken.String, { } realType) => (IEnumLikeString)Activator.CreateInstance(realType, (string)reader.Value), + (_, { }) => (IEnumLikeString)Activator.CreateInstance(objectType, null), _ => null }; + } public override bool CanRead => true; } diff --git a/src/JsonRpc/Serialization/Converters/RpcErrorConverter.cs b/src/JsonRpc/Serialization/Converters/RpcErrorConverter.cs index 1ae5cb787..8e39b77a6 100644 --- a/src/JsonRpc/Serialization/Converters/RpcErrorConverter.cs +++ b/src/JsonRpc/Serialization/Converters/RpcErrorConverter.cs @@ -33,9 +33,12 @@ public override RpcError ReadJson( object? requestId = null; if (obj.TryGetValue("id", out var id)) { - var idString = id.Type == JTokenType.String ? (string) id : null; - var idLong = id.Type == JTokenType.Integer ? (long?) id : null; - requestId = idString ?? ( idLong.HasValue ? (object) idLong.Value : null ); + requestId = id switch + { + { Type: JTokenType.String } => id.Value(), + { Type: JTokenType.Integer } => id.Value(), + _ => null + }; } ErrorMessage? data = null; diff --git a/src/JsonRpc/Server/RequestException.cs b/src/JsonRpc/Server/RequestException.cs index d41260fc8..ad8defb3b 100644 --- a/src/JsonRpc/Server/RequestException.cs +++ b/src/JsonRpc/Server/RequestException.cs @@ -49,7 +49,7 @@ public RequestException(int errorCode, object? requestId, string? message) : bas /// public RequestException(int errorCode, string? message, string? requestId, Exception inner) : base(message, inner) { - RequestId = !string.IsNullOrWhiteSpace(requestId) ? requestId! : UnknownRequestId; + RequestId = !string.IsNullOrWhiteSpace(requestId) ? requestId : UnknownRequestId; ErrorCode = errorCode; } diff --git a/src/Protocol.Proposals/Client/Capabilities/ProposedClientCapabilities.cs b/src/Protocol.Proposals/Client/Capabilities/ProposedClientCapabilities.cs index 45d4ac5e9..beaea73a2 100644 --- a/src/Protocol.Proposals/Client/Capabilities/ProposedClientCapabilities.cs +++ b/src/Protocol.Proposals/Client/Capabilities/ProposedClientCapabilities.cs @@ -1,10 +1,9 @@ using System; -using System.Collections.Generic; -using Newtonsoft.Json.Linq; -using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { [Obsolete(Constants.Proposal)] - public class ProposedClientCapabilities : ClientCapabilities { } + public class ProposedClientCapabilities : ClientCapabilities + { + } } diff --git a/src/Protocol.Proposals/ProposedExtensions.cs b/src/Protocol.Proposals/ProposedExtensions.cs index e7f86a3c8..f63be24b3 100644 --- a/src/Protocol.Proposals/ProposedExtensions.cs +++ b/src/Protocol.Proposals/ProposedExtensions.cs @@ -1,5 +1,4 @@ -using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Client; +using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Server; diff --git a/src/Protocol.Proposals/Serialization/ProposedCapabilitiesConverter.cs b/src/Protocol.Proposals/Serialization/ProposedCapabilitiesConverter.cs index 0ea286577..3ff7a2807 100644 --- a/src/Protocol.Proposals/Serialization/ProposedCapabilitiesConverter.cs +++ b/src/Protocol.Proposals/Serialization/ProposedCapabilitiesConverter.cs @@ -1,6 +1,5 @@ using System; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization { @@ -13,8 +12,16 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist return serializer.Deserialize(reader); } - public override bool CanConvert(Type objectType) => objectType == typeof(TFrom); - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException(); + public override bool CanConvert(Type objectType) + { + return objectType == typeof(TFrom); + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + throw new NotImplementedException(); + } + public override bool CanWrite => false; } } diff --git a/src/Protocol.Proposals/Serialization/ProposedLspSerializer.cs b/src/Protocol.Proposals/Serialization/ProposedLspSerializer.cs index aa7c6c8f1..faf237e1d 100644 --- a/src/Protocol.Proposals/Serialization/ProposedLspSerializer.cs +++ b/src/Protocol.Proposals/Serialization/ProposedLspSerializer.cs @@ -11,6 +11,7 @@ internal class ProposedLspSerializer : LspSerializer protected override void AddOrReplaceConverters(ICollection converters) { +#pragma warning disable CS0618 AddProposedCapabilitiesConverter(converters); AddProposedCapabilitiesConverter(converters); AddProposedCapabilitiesConverter(converters); @@ -18,6 +19,7 @@ protected override void AddOrReplaceConverters(ICollection conver AddProposedCapabilitiesConverter(converters); AddProposedCapabilitiesConverter(converters); AddProposedCapabilitiesConverter(converters); +#pragma warning restore CS0618 base.AddOrReplaceConverters(converters); } diff --git a/src/Protocol.Proposals/Server/Capabilities/ProposedServerCapabilities.cs b/src/Protocol.Proposals/Server/Capabilities/ProposedServerCapabilities.cs index c7644c56a..750ca32e4 100644 --- a/src/Protocol.Proposals/Server/Capabilities/ProposedServerCapabilities.cs +++ b/src/Protocol.Proposals/Server/Capabilities/ProposedServerCapabilities.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using Newtonsoft.Json.Linq; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { diff --git a/src/Protocol.Proposals/Server/Capabilities/ProposedWorkspaceServerCapabilities.cs b/src/Protocol.Proposals/Server/Capabilities/ProposedWorkspaceServerCapabilities.cs index b3d70aef4..75ee55e8e 100644 --- a/src/Protocol.Proposals/Server/Capabilities/ProposedWorkspaceServerCapabilities.cs +++ b/src/Protocol.Proposals/Server/Capabilities/ProposedWorkspaceServerCapabilities.cs @@ -1,6 +1,4 @@ using System; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { diff --git a/src/Protocol/Client/Capabilities/TextDocumentClientCapabilities.cs b/src/Protocol/Client/Capabilities/TextDocumentClientCapabilities.cs index 303362a50..f74b73634 100644 --- a/src/Protocol/Client/Capabilities/TextDocumentClientCapabilities.cs +++ b/src/Protocol/Client/Capabilities/TextDocumentClientCapabilities.cs @@ -1,6 +1,3 @@ -using System.Collections.Generic; -using Newtonsoft.Json.Linq; - namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { public class TextDocumentClientCapabilities : CapabilitiesBase, ITextDocumentClientCapabilities diff --git a/src/Protocol/Client/Capabilities/WindowClientCapabilities.cs b/src/Protocol/Client/Capabilities/WindowClientCapabilities.cs index c088e2e18..24ba5cebc 100644 --- a/src/Protocol/Client/Capabilities/WindowClientCapabilities.cs +++ b/src/Protocol/Client/Capabilities/WindowClientCapabilities.cs @@ -1,6 +1,3 @@ -using System.Collections.Generic; -using Newtonsoft.Json.Linq; - namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { /// diff --git a/src/Protocol/DocumentUri.Internal.cs b/src/Protocol/DocumentUri.Internal.cs index a841a3649..3a34bc3a1 100644 --- a/src/Protocol/DocumentUri.Internal.cs +++ b/src/Protocol/DocumentUri.Internal.cs @@ -15,17 +15,35 @@ public partial class DocumentUri private static readonly Regex SingleSlashStart = new Regex(@"^\/"); private static readonly Regex DoubleSlashStart = new Regex(@"^\/\/"); - private static bool IsHighSurrogate(int charCode) => 0xD800 <= charCode && charCode <= 0xDBFF; + private static bool IsHighSurrogate(int charCode) + { + return 0xD800 <= charCode && charCode <= 0xDBFF; + } - private static bool IsLowSurrogate(int charCode) => 0xDC00 <= charCode && charCode <= 0xDFFF; + private static bool IsLowSurrogate(int charCode) + { + return 0xDC00 <= charCode && charCode <= 0xDFFF; + } - private static bool IsLowerAsciiHex(int code) => code >= CharCode.a && code <= CharCode.f; + private static bool IsLowerAsciiHex(int code) + { + return code >= CharCode.a && code <= CharCode.f; + } - private static bool IsLowerAsciiLetter(int code) => code >= CharCode.a && code <= CharCode.z; + private static bool IsLowerAsciiLetter(int code) + { + return code >= CharCode.a && code <= CharCode.z; + } - private static bool IsUpperAsciiLetter(int code) => code >= CharCode.A && code <= CharCode.Z; + private static bool IsUpperAsciiLetter(int code) + { + return code >= CharCode.A && code <= CharCode.Z; + } - private static bool IsAsciiLetter(int code) => IsLowerAsciiLetter(code) || IsUpperAsciiLetter(code); + private static bool IsAsciiLetter(int code) + { + return IsLowerAsciiLetter(code) || IsUpperAsciiLetter(code); + } private static void _validateUri(DocumentUri ret, bool? strict) { @@ -111,7 +129,8 @@ private static string ReferenceResolution(string? scheme, string path) return path; } - private static readonly IDictionary EncodeTable = new Dictionary { + private static readonly IDictionary EncodeTable = new Dictionary + { [CharCode.Colon] = "%3A", // gen-delims [CharCode.Slash] = "%2F", [CharCode.QuestionMark] = "%3F", @@ -146,19 +165,19 @@ private static string EncodeUriComponentFast(string uriComponent, bool allowSlas // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3 if ( - code >= CharCode.a && code <= CharCode.z - || code >= CharCode.A && code <= CharCode.Z - || code >= CharCode.Digit0 && code <= CharCode.Digit9 + ( code >= CharCode.a && code <= CharCode.z ) + || ( code >= CharCode.A && code <= CharCode.Z ) + || ( code >= CharCode.Digit0 && code <= CharCode.Digit9 ) || code == CharCode.Dash || code == CharCode.Period || code == CharCode.Underline || code == CharCode.Tilde - || allowSlash && code == CharCode.Slash - || allowSlash && ( pos == 1 || pos == 2 ) && ( - uriComponent.Length >= 3 && uriComponent[0] == CharCode.Slash && - uriComponent[2] == CharCode.Colon - || uriComponent.Length >= 2 && uriComponent[1] == CharCode.Colon - ) + || ( allowSlash && code == CharCode.Slash ) + || ( allowSlash && ( pos == 1 || pos == 2 ) && ( + ( uriComponent.Length >= 3 && uriComponent[0] == CharCode.Slash && + uriComponent[2] == CharCode.Colon ) + || ( uriComponent.Length >= 2 && uriComponent[1] == CharCode.Colon ) + ) ) ) { // check if we are delaying native encode @@ -249,8 +268,8 @@ private static string UriToFsPath(DocumentUri uri, bool keepDriveLetterCasing) else if ( uri.Path.Length >= 3 && uri.Path[0] == CharCode.Slash - && ( uri.Path[1] >= CharCode.A && uri.Path[1] <= CharCode.Z || - uri.Path[1] >= CharCode.a && uri.Path[1] <= CharCode.z ) + && ( ( uri.Path[1] >= CharCode.A && uri.Path[1] <= CharCode.Z ) || + ( uri.Path[1] >= CharCode.a && uri.Path[1] <= CharCode.z ) ) && uri.Path[2] == CharCode.Colon ) { diff --git a/src/Protocol/DocumentUri.cs b/src/Protocol/DocumentUri.cs index 4f1870c46..299a91eec 100644 --- a/src/Protocol/DocumentUri.cs +++ b/src/Protocol/DocumentUri.cs @@ -69,7 +69,8 @@ public Uri ToUri() var parts = Authority.Split(':'); var host = parts[0]; var port = int.Parse(parts[1]); - return new UriBuilder { + return new UriBuilder + { Scheme = Scheme, Host = host, Port = port, @@ -79,7 +80,8 @@ public Uri ToUri() }.Uri; } - return new UriBuilder { + return new UriBuilder + { Scheme = Scheme, Host = Authority, Path = Path, @@ -101,16 +103,25 @@ public Uri ToUri() /// /// @param skipEncoding Do not encode the result, default is `false` /// - public override string ToString() => _asFormatted(this, false); + public override string ToString() + { + return _asFormatted(this, false); + } - public string ToUnencodedString() => _asFormatted(this, true); + public string ToUnencodedString() + { + return _asFormatted(this, true); + } /// /// Gets the file system path prefixed with / for unix platforms /// /// /// This will not a uri encode asian and cyrillic characters - public string GetFileSystemPath() => UriToFsPath(this, false); + public string GetFileSystemPath() + { + return UriToFsPath(this, false); + } /// public bool Equals(DocumentUri? other) @@ -133,7 +144,7 @@ public override bool Equals(object? obj) { if (obj is null) return false; if (ReferenceEquals(this, obj)) return true; - return obj.GetType() == GetType() && Equals((DocumentUri) obj); + return obj.GetType() == GetType() && Equals((DocumentUri)obj); } /// @@ -146,7 +157,7 @@ public override int GetHashCode() unchecked { var hashCode = comparer.GetHashCode(Path); - hashCode = ( hashCode * 397 ) ^ comparer.GetHashCode(Scheme); + hashCode = ( hashCode * 397 ) ^ comparer.GetHashCode(Scheme ?? ""); hashCode = ( hashCode * 397 ) ^ comparer.GetHashCode(Authority); hashCode = ( hashCode * 397 ) ^ comparer.GetHashCode(Query); hashCode = ( hashCode * 397 ) ^ comparer.GetHashCode(Fragment); @@ -181,7 +192,10 @@ out string fragment /// /// /// - public static bool operator ==(DocumentUri left, DocumentUri right) => Equals(left, right); + public static bool operator ==(DocumentUri left, DocumentUri right) + { + return Equals(left, right); + } /// /// Check if two uris are not equal @@ -189,15 +203,23 @@ out string fragment /// /// /// - public static bool operator !=(DocumentUri left, DocumentUri right) => !Equals(left, right); + public static bool operator !=(DocumentUri left, DocumentUri right) + { + return !Equals(left, right); + } /// /// Convert this uri into a . /// /// - /// This is explicit because to string gives the schema string with file:// but if you want the file system you use + /// + /// This is explicit because to string gives the schema string with file:// but if you want the file system you use + /// /// - public static explicit operator string(DocumentUri uri) => uri.ToString(); + public static explicit operator string(DocumentUri uri) + { + return uri.ToString(); + } /// /// Convert this into a . @@ -205,21 +227,30 @@ out string fragment /// /// The uri class has issues with higher level utf8 characters such as asian and cyrillic characters /// - public static explicit operator Uri(DocumentUri uri) => uri.ToUri(); + public static explicit operator Uri(DocumentUri uri) + { + return uri.ToUri(); + } /// /// Automatically convert a string to a uri for both filesystem paths or uris in a string /// /// /// - public static implicit operator DocumentUri(string url) => From(url); + public static implicit operator DocumentUri(string url) + { + return From(url); + } /// /// Automatically convert a uri to a document uri /// /// /// - public static implicit operator DocumentUri(Uri uri) => From(uri); + public static implicit operator DocumentUri(Uri uri) + { + return From(uri); + } /// /// Create a new document uri from the given @@ -267,8 +298,10 @@ public static DocumentUri From(string url) /// /// The file-system path, or null if the URI does not represent a file-system path. /// - public static string? GetFileSystemPath(ITextDocumentIdentifierParams textDocumentIdentifierParams) => - GetFileSystemPath(textDocumentIdentifierParams.TextDocument.Uri); + public static string? GetFileSystemPath(ITextDocumentIdentifierParams textDocumentIdentifierParams) + { + return GetFileSystemPath(textDocumentIdentifierParams.TextDocument.Uri); + } /// /// Get the local file-system path for the specified document URI. @@ -279,8 +312,10 @@ public static DocumentUri From(string url) /// /// The file-system path, or null if the URI does not represent a file-system path. /// - public static string? GetFileSystemPath(TextDocumentIdentifier textDocumentIdentifier) => - GetFileSystemPath(textDocumentIdentifier.Uri); + public static string? GetFileSystemPath(TextDocumentIdentifier textDocumentIdentifier) + { + return GetFileSystemPath(textDocumentIdentifier.Uri); + } /// /// Get the local file-system path for the specified document URI. @@ -310,7 +345,10 @@ public static DocumentUri From(string url) /// /// The LSP document URI. /// - public static DocumentUri FromFileSystemPath(string fileSystemPath) => File(fileSystemPath); + public static DocumentUri FromFileSystemPath(string fileSystemPath) + { + return File(fileSystemPath); + } private sealed class DocumentUriEqualityComparer : IEqualityComparer { @@ -322,7 +360,10 @@ public bool Equals(DocumentUri? x, DocumentUri? y) return x.GetType() == y.GetType() && x.Equals(y); } - public int GetHashCode(DocumentUri obj) => obj.GetHashCode(); + public int GetHashCode(DocumentUri obj) + { + return obj.GetHashCode(); + } } /// @@ -441,22 +482,26 @@ public static DocumentUri File(string path) return new DocumentUri("file", authority, path, Empty, Empty); } - public DocumentUri With(DocumentUriComponents components) => - new DocumentUri( + public DocumentUri With(DocumentUriComponents components) + { + return new DocumentUri( components.Scheme ?? Scheme, components.Authority ?? Authority, components.Path ?? Path, components.Query ?? Query, components.Fragment ?? Fragment ); + } - public static DocumentUri From(DocumentUriComponents components) => - new DocumentUri( + public static DocumentUri From(DocumentUriComponents components) + { + return new DocumentUri( components.Scheme ?? string.Empty, components.Authority ?? string.Empty, components.Path ?? string.Empty, components.Query ?? string.Empty, components.Fragment ?? string.Empty ); + } } } diff --git a/src/Protocol/Features/Client/LogTraceFeature.cs b/src/Protocol/Features/Client/LogTraceFeature.cs index 6712ce7e4..7c033130a 100644 --- a/src/Protocol/Features/Client/LogTraceFeature.cs +++ b/src/Protocol/Features/Client/LogTraceFeature.cs @@ -11,14 +11,15 @@ namespace Models { [Parallel] [Method(GeneralNames.LogTrace, Direction.ServerToClient)] - [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Client"), GenerateHandlerMethods, - GenerateRequestMethods(typeof(IClientLanguageServer), typeof(ILanguageServer))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Client")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IClientLanguageServer), typeof(ILanguageServer))] public record LogTraceParams : IRequest { /// /// The message to be logged. /// - public string Message { get; init; } + public string Message { get; init; } = null!; /// /// Additional information that can be computed if the `trace` configuration is set to `'verbose'` diff --git a/src/Protocol/Features/Client/RegistrationFeature.cs b/src/Protocol/Features/Client/RegistrationFeature.cs index 557d6b578..b48e81a7c 100644 --- a/src/Protocol/Features/Client/RegistrationFeature.cs +++ b/src/Protocol/Features/Client/RegistrationFeature.cs @@ -2,6 +2,7 @@ using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Newtonsoft.Json; using OmniSharp.Extensions.JsonRpc; @@ -17,23 +18,19 @@ namespace Models { [Parallel] [Method(ClientNames.RegisterCapability, Direction.ServerToClient)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Client", Name = "RegisterCapability"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(IClientLanguageServer), typeof(ILanguageServer)) - ] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Client", Name = "RegisterCapability")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IClientLanguageServer), typeof(ILanguageServer))] public partial record RegistrationParams : IJsonRpcRequest { - public RegistrationContainer Registrations { get; init; } + public RegistrationContainer Registrations { get; init; } = null!; } [Parallel] [Method(ClientNames.UnregisterCapability, Direction.ServerToClient)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Client", Name = "UnregisterCapability"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(IClientLanguageServer), typeof(ILanguageServer)) - ] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Client", Name = "UnregisterCapability")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IClientLanguageServer), typeof(ILanguageServer))] public partial record UnregistrationParams : IJsonRpcRequest { public UnregistrationContainer? Unregisterations { get; init; } @@ -58,12 +55,12 @@ public partial record Registration /// The id used to register the request. The id can be used to deregister /// the request again. /// - public string Id { get; init; } + public string Id { get; init; } = null!; /// /// The method / capability to register for. /// - public string Method { get; init; } + public string Method { get; init; } = null!; /// /// Options necessary for the registration. @@ -71,15 +68,23 @@ public partial record Registration [Optional] public object? RegisterOptions { get; init; } - private string DebuggerDisplay => $"[{Id}] {( RegisterOptions is ITextDocumentRegistrationOptions td ? $"{td.DocumentSelector}" : string.Empty )} {Method}"; + private string DebuggerDisplay => + $"[{Id}] {( RegisterOptions is ITextDocumentRegistrationOptions td ? $"{td.DocumentSelector}" : string.Empty )} {Method}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } - public static Unregistration ToUnregistration(Registration registration) => new Unregistration() { - Id = registration.Id, - Method = registration.Method, - }; + public static Unregistration ToUnregistration(Registration registration) + { + return new Unregistration + { + Id = registration.Id, + Method = registration.Method, + }; + } public class TextDocumentComparer : IEqualityComparer { @@ -93,7 +98,7 @@ public bool Equals(Registration? x, Registration? y) { // Id doesn't matter if they target the same text document // this is arbitrary but should be good in most cases. - return ( x.Id == y.Id || xTdro.DocumentSelector == yTdro.DocumentSelector ) && x.Method == y.Method; + return ( x.Id == y.Id || xTdro.DocumentSelector! == yTdro.DocumentSelector! ) && x.Method == y.Method; } return x.Id == y.Id && x.Method == y.Method; @@ -106,13 +111,13 @@ public int GetHashCode(Registration? obj) if (obj!.RegisterOptions is ITextDocumentRegistrationOptions tdro) { var hashCode = obj.Method.GetHashCode(); - return ( hashCode * 397 ) ^ ( tdro.DocumentSelector != null ? tdro.DocumentSelector.GetHashCode() : 0 ); + return ( hashCode * 397 ) ^ ( tdro.DocumentSelector?.GetHashCode() ?? 0 ); } else { var hashCode = obj!.Id.GetHashCode(); hashCode = ( hashCode * 397 ) ^ obj.Method.GetHashCode(); - return ( hashCode * 397 ) ^ ( obj.RegisterOptions != null ? obj.RegisterOptions.GetHashCode() : 0 ); + return ( hashCode * 397 ) ^ ( obj.RegisterOptions?.GetHashCode() ?? 0 ); } } } @@ -130,80 +135,122 @@ public partial record Unregistration /// The id used to unregister the request or notification. Usually an id /// provided during the register request. /// - public string Id { get; init; } + public string Id { get; init; } = null!; /// /// The method to unregister for. /// - public string Method { get; init; } + public string Method { get; init; } = null!; - public static implicit operator Unregistration(Registration registration) => - new Unregistration { + public static implicit operator Unregistration(Registration registration) + { + return new Unregistration + { Id = registration.Id, Method = registration.Method }; + } private string DebuggerDisplay => $"[{Id}] {Method}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } public partial class UnregistrationContainer { - [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("items")] - public static UnregistrationContainer? From(IEnumerable? items) => items switch { - not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), - _ => null - }; - - [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("items")] - public static implicit operator UnregistrationContainer?(Registration[] items) => items switch { - not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), - _ => null - }; - - [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("items")] - public static UnregistrationContainer? From(params Registration[] items) => items switch { - not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), - _ => null - }; - - [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("items")] - public static implicit operator UnregistrationContainer?(Collection? items) => items switch { - not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), - _ => null - }; - - [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("items")] - public static UnregistrationContainer? From(Collection? items) => items switch { - not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), - _ => null - }; - - [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("items")] - public static implicit operator UnregistrationContainer?(List? items) => items switch { - not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), - _ => null - }; - - [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("items")] - public static UnregistrationContainer? From(List? items) => items switch { - not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), - _ => null - }; - - [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("items")] - public static implicit operator UnregistrationContainer?(ImmutableList? items) => items switch { - not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), - _ => null - }; - - [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("items")] - public static UnregistrationContainer? From(ImmutableList? items) => items switch { - not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), - _ => null - }; + [return: NotNullIfNotNull("items")] + public static UnregistrationContainer? From(IEnumerable? items) + { + return items switch + { + not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), + _ => null + }; + } + + [return: NotNullIfNotNull("items")] + public static implicit operator UnregistrationContainer?(Registration[] items) + { + return items switch + { + not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), + _ => null + }; + } + + [return: NotNullIfNotNull("items")] + public static UnregistrationContainer? From(params Registration[] items) + { + return items switch + { + not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), + _ => null + }; + } + + [return: NotNullIfNotNull("items")] + public static implicit operator UnregistrationContainer?(Collection? items) + { + return items switch + { + not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), + _ => null + }; + } + + [return: NotNullIfNotNull("items")] + public static UnregistrationContainer? From(Collection? items) + { + return items switch + { + not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), + _ => null + }; + } + + [return: NotNullIfNotNull("items")] + public static implicit operator UnregistrationContainer?(List? items) + { + return items switch + { + not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), + _ => null + }; + } + + [return: NotNullIfNotNull("items")] + public static UnregistrationContainer? From(List? items) + { + return items switch + { + not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), + _ => null + }; + } + + [return: NotNullIfNotNull("items")] + public static implicit operator UnregistrationContainer?(ImmutableList? items) + { + return items switch + { + not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), + _ => null + }; + } + + [return: NotNullIfNotNull("items")] + public static UnregistrationContainer? From(ImmutableList? items) + { + return items switch + { + not null => new UnregistrationContainer(items.Select(Registration.ToUnregistration)), + _ => null + }; + } } } diff --git a/src/Protocol/Features/Document/CallHierarchyFeature.cs b/src/Protocol/Features/Document/CallHierarchyFeature.cs index cdfa8096c..73f0949dd 100644 --- a/src/Protocol/Features/Document/CallHierarchyFeature.cs +++ b/src/Protocol/Features/Document/CallHierarchyFeature.cs @@ -30,16 +30,13 @@ namespace Models /// [Parallel] [Method(TextDocumentNames.PrepareCallHierarchy, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(CallHierarchyRegistrationOptions)), Capability(typeof(CallHierarchyCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(CallHierarchyRegistrationOptions))] + [Capability(typeof(CallHierarchyCapability))] public partial record CallHierarchyPrepareParams : TextDocumentPositionParams, IWorkDoneProgressParams, - IPartialItemsRequest?, CallHierarchyItem> - { - } + IPartialItemsRequest?, CallHierarchyItem>; /// /// Represents programming constructs like functions or constructors in the context @@ -54,7 +51,7 @@ public partial record CallHierarchyItem : ICanBeResolved /// /// The name of this item. /// - public string Name { get; init; } + public string Name { get; init; } = null!; /// /// The kind of this item. @@ -76,18 +73,18 @@ public partial record CallHierarchyItem : ICanBeResolved /// /// The resource identifier of this item. /// - public DocumentUri Uri { get; init; } + public DocumentUri Uri { get; init; } = null!; /// /// The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code. /// - public Range Range { get; init; } + public Range Range { get; init; } = null!; /// /// The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function. /// Must be contained by the [`range`](#CallHierarchyItem.range). /// - public Range SelectionRange { get; init; } + public Range SelectionRange { get; init; } = null!; /// /// A data entry field that is preserved between a call hierarchy prepare and @@ -103,11 +100,15 @@ public partial record CallHierarchyItem : ICanBeResolved $"{Range}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } + public abstract record CallHierarchyBaseCallParams : ICanBeResolved { - public CallHierarchyItem Item { get; init; } + public CallHierarchyItem Item { get; init; } = null!; JToken? ICanBeResolved.Data { @@ -115,10 +116,11 @@ public abstract record CallHierarchyBaseCallParams : ICanBeResolved init => Item.SetRawData(value); } } + public abstract record CallHierarchyBaseCallParams : ICanBeResolved where T : class?, IHandlerIdentity? { - public CallHierarchyItem Item { get; init; } + public CallHierarchyItem Item { get; init; } = null!; JToken? ICanBeResolved.Data { @@ -134,16 +136,13 @@ public abstract record CallHierarchyBaseCallParams : ICanBeResolved /// [Parallel] [Method(TextDocumentNames.CallHierarchyIncoming, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "CallHierarchyIncoming"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "CallHierarchyIncoming")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] [Capability(typeof(CallHierarchyCapability))] public partial record CallHierarchyIncomingCallsParams : CallHierarchyBaseCallParams, IWorkDoneProgressParams, - IPartialItemsRequest?, CallHierarchyIncomingCall>, IDoesNotParticipateInRegistration - { - } + IPartialItemsRequest?, CallHierarchyIncomingCall>, + IDoesNotParticipateInRegistration; /// /// The parameter of a `callHierarchy/incomingCalls` request. @@ -151,29 +150,28 @@ public partial record CallHierarchyIncomingCallsParams : CallHierarchyBaseCallPa /// @since 3.16.0 /// [Method(TextDocumentNames.CallHierarchyIncoming, Direction.ClientToServer)] - public partial record CallHierarchyIncomingCallsParams : CallHierarchyBaseCallParams, IWorkDoneProgressParams, - IPartialItemsRequest?, CallHierarchyIncomingCall>, IDoesNotParticipateInRegistration - where T : class?, IHandlerIdentity? - { - } + public partial record CallHierarchyIncomingCallsParams : CallHierarchyBaseCallParams, IWorkDoneProgressParams, + IPartialItemsRequest?, CallHierarchyIncomingCall>, + IDoesNotParticipateInRegistration + where T : class?, IHandlerIdentity?; /// /// Represents an incoming call, e.g. a caller of a method or constructor. /// /// @since 3.16.0 /// - public partial record CallHierarchyIncomingCall + public partial record CallHierarchyIncomingCall { /// /// The item that makes the call. /// - public CallHierarchyItem From { get; init; } + public CallHierarchyItem From { get; init; } = null!; /// /// The range at which at which the calls appears. This is relative to the caller /// denoted by [`this.from`](#CallHierarchyIncomingCall.from). /// - public Container FromRanges { get; init; } + public Container FromRanges { get; init; } = null!; } /// @@ -183,20 +181,20 @@ public partial record CallHierarchyIncomingCall /// [Parallel] [Method(TextDocumentNames.CallHierarchyOutgoing, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "CallHierarchyOutgoing"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "CallHierarchyOutgoing")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] [Capability(typeof(CallHierarchyCapability))] public partial record CallHierarchyOutgoingCallsParams : CallHierarchyBaseCallParams, IWorkDoneProgressParams, - IPartialItemsRequest?, CallHierarchyOutgoingCall>, IDoesNotParticipateInRegistration + IPartialItemsRequest?, CallHierarchyOutgoingCall>, + IDoesNotParticipateInRegistration { public static CallHierarchyOutgoingCallsParams Create(CallHierarchyOutgoingCallsParams item) where T : class?, IHandlerIdentity? { - return new CallHierarchyOutgoingCallsParams() { + return new CallHierarchyOutgoingCallsParams + { Item = item.Item, PartialResultToken = item.PartialResultToken, WorkDoneToken = item.PartialResultToken @@ -211,20 +209,29 @@ public static CallHierarchyOutgoingCallsParams Create(CallHierarchyOutgoin /// [Method(TextDocumentNames.CallHierarchyOutgoing, Direction.ClientToServer)] public partial record CallHierarchyOutgoingCallsParams : CallHierarchyBaseCallParams, IWorkDoneProgressParams, - IPartialItemsRequest?, CallHierarchyOutgoingCall>, IDoesNotParticipateInRegistration + IPartialItemsRequest?, CallHierarchyOutgoingCall>, + IDoesNotParticipateInRegistration where T : class?, IHandlerIdentity? { public static CallHierarchyOutgoingCallsParams Create(CallHierarchyOutgoingCallsParams item) { - return new CallHierarchyOutgoingCallsParams() { + return new CallHierarchyOutgoingCallsParams + { Item = item.Item, PartialResultToken = item.PartialResultToken, WorkDoneToken = item.PartialResultToken }; } - public static implicit operator CallHierarchyOutgoingCallsParams(CallHierarchyOutgoingCallsParams item) => Create(item); - public static implicit operator CallHierarchyOutgoingCallsParams(CallHierarchyOutgoingCallsParams item) => CallHierarchyOutgoingCallsParams.Create(item); + public static implicit operator CallHierarchyOutgoingCallsParams(CallHierarchyOutgoingCallsParams item) + { + return Create(item); + } + + public static implicit operator CallHierarchyOutgoingCallsParams(CallHierarchyOutgoingCallsParams item) + { + return CallHierarchyOutgoingCallsParams.Create(item); + } } /// @@ -237,14 +244,14 @@ public partial record CallHierarchyOutgoingCall /// /// The item that is called. /// - public CallHierarchyItem To { get; init; } + public CallHierarchyItem To { get; init; } = null!; /// /// The range at which this item is called. This is the range relative to the caller, e.g the item /// passed to [`provideCallHierarchyOutgoingCalls`](#CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls) /// and not [`this.to`](#CallHierarchyOutgoingCall.to). /// - public Container FromRanges { get; init; } + public Container FromRanges { get; init; } = null!; } /// @@ -274,7 +281,8 @@ public partial class CallHierarchyCapability : DynamicCapability namespace Document { - public abstract class CallHierarchyHandlerBase : AbstractHandlers.Base, ICallHierarchyPrepareHandler, + public abstract class CallHierarchyHandlerBase : AbstractHandlers.Base, + ICallHierarchyPrepareHandler, ICallHierarchyIncomingHandler, ICallHierarchyOutgoingHandler { @@ -294,7 +302,9 @@ protected CallHierarchyHandlerBase() : this(Guid.NewGuid()) public abstract Task?> Handle(CallHierarchyIncomingCallsParams request, CancellationToken cancellationToken); public abstract Task?> Handle(CallHierarchyOutgoingCallsParams request, CancellationToken cancellationToken); } - public abstract class PartialCallHierarchyHandlerBase : AbstractHandlers.PartialResults?, CallHierarchyItem, + + public abstract class PartialCallHierarchyHandlerBase : AbstractHandlers.PartialResults?, + CallHierarchyItem, CallHierarchyRegistrationOptions, CallHierarchyCapability>, ICallHierarchyPrepareHandler, ICallHierarchyIncomingHandler, ICallHierarchyOutgoingHandler { @@ -314,11 +324,15 @@ protected PartialCallHierarchyHandlerBase(IProgressManager progressManager) : th { } - public Task?> Handle(CallHierarchyIncomingCallsParams request, CancellationToken cancellationToken) => - _incoming.Handle(request, cancellationToken); + public Task?> Handle(CallHierarchyIncomingCallsParams request, CancellationToken cancellationToken) + { + return _incoming.Handle(request, cancellationToken); + } - public Task?> Handle(CallHierarchyOutgoingCallsParams request, CancellationToken cancellationToken) => - _outgoing.Handle(request, cancellationToken); + public Task?> Handle(CallHierarchyOutgoingCallsParams request, CancellationToken cancellationToken) + { + return _outgoing.Handle(request, cancellationToken); + } protected abstract void Handle( CallHierarchyIncomingCallsParams request, IObserver> results, CancellationToken cancellationToken @@ -351,15 +365,24 @@ protected override void Handle( CallHierarchyIncomingCallsParams request, IObserver> results, CancellationToken cancellationToken - ) => _self.Handle(request, results, cancellationToken); + ) + { + _self.Handle(request, results, cancellationToken); + } - protected internal override CallHierarchyRegistrationOptions CreateRegistrationOptions(CallHierarchyCapability capability, ClientCapabilities clientCapabilities) => - ( (IRegistration) _self ).GetRegistrationOptions(capability, clientCapabilities); + protected internal override CallHierarchyRegistrationOptions CreateRegistrationOptions( + CallHierarchyCapability capability, ClientCapabilities clientCapabilities + ) + { + return ( (IRegistration)_self ).GetRegistrationOptions( + capability, clientCapabilities + ); + } } - class PartialOutgoing : - AbstractHandlers.PartialResults?, CallHierarchyOutgoingCall, CallHierarchyRegistrationOptions - , CallHierarchyCapability>, ICallHierarchyOutgoingHandler + private class PartialOutgoing : AbstractHandlers.PartialResults?, + CallHierarchyOutgoingCall, CallHierarchyRegistrationOptions + , CallHierarchyCapability>, ICallHierarchyOutgoingHandler { private readonly PartialCallHierarchyHandlerBase _self; private readonly Guid _id; @@ -375,12 +398,22 @@ public PartialOutgoing(Guid id, IProgressManager progressManager, PartialCallHie protected override void Handle( CallHierarchyOutgoingCallsParams request, IObserver> results, CancellationToken cancellationToken - ) => _self.Handle(request, results, cancellationToken); + ) + { + _self.Handle(request, results, cancellationToken); + } - protected internal override CallHierarchyRegistrationOptions CreateRegistrationOptions(CallHierarchyCapability capability, ClientCapabilities clientCapabilities) => - ( (IRegistration) _self ).GetRegistrationOptions(capability, clientCapabilities); + protected internal override CallHierarchyRegistrationOptions CreateRegistrationOptions( + CallHierarchyCapability capability, ClientCapabilities clientCapabilities + ) + { + return ( (IRegistration)_self ).GetRegistrationOptions( + capability, clientCapabilities + ); + } } } + public abstract class CallHierarchyHandlerBase : CallHierarchyHandlerBase where T : class?, IHandlerIdentity? { protected CallHierarchyHandlerBase(Guid id) : base(id) @@ -397,10 +430,13 @@ protected CallHierarchyHandlerBase() : this(Guid.NewGuid()) return Container.From(response?.Select(CallHierarchyItem.From)!); } - public sealed override Task?> Handle(CallHierarchyIncomingCallsParams request, CancellationToken cancellationToken) + public sealed override Task?> Handle( + CallHierarchyIncomingCallsParams request, CancellationToken cancellationToken + ) { return HandleIncomingCalls( - new CallHierarchyIncomingCallsParams() { + new CallHierarchyIncomingCallsParams + { Item = request.Item, PartialResultToken = request.PartialResultToken, WorkDoneToken = request.WorkDoneToken @@ -409,10 +445,13 @@ protected CallHierarchyHandlerBase() : this(Guid.NewGuid()) ); } - public sealed override Task?> Handle(CallHierarchyOutgoingCallsParams request, CancellationToken cancellationToken) + public sealed override Task?> Handle( + CallHierarchyOutgoingCallsParams request, CancellationToken cancellationToken + ) { return HandleOutgoingCalls( - new CallHierarchyOutgoingCallsParams() { + new CallHierarchyOutgoingCallsParams + { Item = request.Item, PartialResultToken = request.PartialResultToken, WorkDoneToken = request.WorkDoneToken @@ -422,38 +461,55 @@ protected CallHierarchyHandlerBase() : this(Guid.NewGuid()) } protected abstract Task>?> HandlePrepare(CallHierarchyPrepareParams request, CancellationToken cancellationToken); - protected abstract Task?> HandleIncomingCalls(CallHierarchyIncomingCallsParams request, CancellationToken cancellationToken); - protected abstract Task?> HandleOutgoingCalls(CallHierarchyOutgoingCallsParams request, CancellationToken cancellationToken); + + protected abstract Task?> HandleIncomingCalls( + CallHierarchyIncomingCallsParams request, CancellationToken cancellationToken + ); + + protected abstract Task?> HandleOutgoingCalls( + CallHierarchyOutgoingCallsParams request, CancellationToken cancellationToken + ); } + public abstract class PartialCallHierarchyHandlerBase : PartialCallHierarchyHandlerBase where T : class?, IHandlerIdentity? { protected PartialCallHierarchyHandlerBase(IProgressManager progressManager) : base(progressManager) { } - protected sealed override void Handle(CallHierarchyPrepareParams request, IObserver> results, CancellationToken cancellationToken) => + protected sealed override void Handle( + CallHierarchyPrepareParams request, IObserver> results, CancellationToken cancellationToken + ) + { Handle( request, Observer.Create>>( - x => results.OnNext(x.Select(z => (CallHierarchyItem) z)), + x => results.OnNext(x.Select(z => (CallHierarchyItem)z)), results.OnError, results.OnCompleted ), cancellationToken ); + } - protected abstract void Handle(CallHierarchyPrepareParams request, IObserver>> results, CancellationToken cancellationToken); + protected abstract void Handle( + CallHierarchyPrepareParams request, IObserver>> results, CancellationToken cancellationToken + ); protected sealed override void Handle( CallHierarchyIncomingCallsParams request, IObserver> results, CancellationToken cancellationToken - ) => Handle( - new CallHierarchyIncomingCallsParams() { - Item = request.Item, - PartialResultToken = request.PartialResultToken, - WorkDoneToken = request.WorkDoneToken - }, - results, - cancellationToken - ); + ) + { + Handle( + new CallHierarchyIncomingCallsParams + { + Item = request.Item, + PartialResultToken = request.PartialResultToken, + WorkDoneToken = request.WorkDoneToken + }, + results, + cancellationToken + ); + } protected abstract void Handle( CallHierarchyIncomingCallsParams request, IObserver> results, CancellationToken cancellationToken @@ -461,20 +517,25 @@ protected abstract void Handle( protected sealed override void Handle( CallHierarchyOutgoingCallsParams request, IObserver> results, CancellationToken cancellationToken - ) => Handle( - new CallHierarchyOutgoingCallsParams { - Item = request.Item, - PartialResultToken = request.PartialResultToken, - WorkDoneToken = request.WorkDoneToken - }, - results, - cancellationToken - ); + ) + { + Handle( + new CallHierarchyOutgoingCallsParams + { + Item = request.Item, + PartialResultToken = request.PartialResultToken, + WorkDoneToken = request.WorkDoneToken + }, + results, + cancellationToken + ); + } protected abstract void Handle( CallHierarchyOutgoingCallsParams request, IObserver> results, CancellationToken cancellationToken ); } + public static partial class CallHierarchyExtensions { public static ILanguageServerRegistry OnCallHierarchy( @@ -532,8 +593,10 @@ public static ILanguageServerRegistry OnCallHierarchy( public static ILanguageServerRegistry OnCallHierarchy( this ILanguageServerRegistry registry, Func>?>> handler, - Func, CallHierarchyCapability, CancellationToken, Task?>> incomingHandler, - Func, CallHierarchyCapability, CancellationToken, Task?>> outgoingHandler, + Func, CallHierarchyCapability, CancellationToken, Task?>> + incomingHandler, + Func, CallHierarchyCapability, CancellationToken, Task?>> + outgoingHandler, RegistrationOptionsDelegate? registrationOptionsFactory ) where T : class?, IHandlerIdentity? { @@ -655,8 +718,10 @@ public static ILanguageServerRegistry OnCallHierarchy( public static ILanguageServerRegistry OnCallHierarchy( this ILanguageServerRegistry registry, Action>, CallHierarchyCapability, CancellationToken> handler, - Action>, CallHierarchyCapability, CancellationToken> incomingHandler, - Action>, CallHierarchyCapability, CancellationToken> outgoingHandler, + Action>, CallHierarchyCapability, CancellationToken> + incomingHandler, + Action>, CallHierarchyCapability, CancellationToken> + outgoingHandler, RegistrationOptionsDelegate? registrationOptionsFactory ) { @@ -712,8 +777,10 @@ public static ILanguageServerRegistry OnCallHierarchy( public static ILanguageServerRegistry OnCallHierarchy( this ILanguageServerRegistry registry, Action>>, CallHierarchyCapability, CancellationToken> handler, - Action, IObserver>, CallHierarchyCapability, CancellationToken> incomingHandler, - Action, IObserver>, CallHierarchyCapability, CancellationToken> outgoingHandler, + Action, IObserver>, CallHierarchyCapability, CancellationToken> + incomingHandler, + Action, IObserver>, CallHierarchyCapability, CancellationToken> + outgoingHandler, RegistrationOptionsDelegate? registrationOptionsFactory ) where T : class?, IHandlerIdentity? { @@ -846,20 +913,25 @@ public static ILanguageServerRegistry OnCallHierarchy( private class DelegatingCallHierarchyHandler : CallHierarchyHandlerBase where T : class?, IHandlerIdentity? { - private readonly Func>?>> _handlePrepare; + private readonly Func>?>> + _handlePrepare; - private readonly Func, CallHierarchyCapability, CancellationToken, Task?>> + private readonly Func, CallHierarchyCapability, CancellationToken, + Task?>> _handleIncomingCalls; - private readonly Func, CallHierarchyCapability, CancellationToken, Task?>> + private readonly Func, CallHierarchyCapability, CancellationToken, + Task?>> _handleOutgoingCalls; private readonly RegistrationOptionsDelegate _registrationOptionsFactory; public DelegatingCallHierarchyHandler( Func>?>> handlePrepare, - Func, CallHierarchyCapability, CancellationToken, Task?>> handleIncomingCalls, - Func, CallHierarchyCapability, CancellationToken, Task?>> handleOutgoingCalls, + Func, CallHierarchyCapability, CancellationToken, Task?>> + handleIncomingCalls, + Func, CallHierarchyCapability, CancellationToken, Task?>> + handleOutgoingCalls, RegistrationOptionsDelegate registrationOptionsFactory ) { @@ -869,30 +941,44 @@ RegistrationOptionsDelegate>?> HandlePrepare(CallHierarchyPrepareParams request, CancellationToken cancellationToken) => - _handlePrepare(request, Capability, cancellationToken); + protected override Task>?> HandlePrepare(CallHierarchyPrepareParams request, CancellationToken cancellationToken) + { + return _handlePrepare(request, Capability, cancellationToken); + } protected override Task?> HandleIncomingCalls( CallHierarchyIncomingCallsParams request, CancellationToken cancellationToken - ) => - _handleIncomingCalls(request, Capability, cancellationToken); + ) + { + return _handleIncomingCalls(request, Capability, cancellationToken); + } protected override Task?> HandleOutgoingCalls( CallHierarchyOutgoingCallsParams request, CancellationToken cancellationToken - ) => - _handleOutgoingCalls(request, Capability, cancellationToken); + ) + { + return _handleOutgoingCalls(request, Capability, cancellationToken); + } - protected internal override CallHierarchyRegistrationOptions CreateRegistrationOptions(CallHierarchyCapability capability, ClientCapabilities clientCapabilities) => _registrationOptionsFactory(capability, clientCapabilities); + protected internal override CallHierarchyRegistrationOptions CreateRegistrationOptions( + CallHierarchyCapability capability, ClientCapabilities clientCapabilities + ) + { + return _registrationOptionsFactory(capability, clientCapabilities); + } } private class DelegatingPartialCallHierarchyHandler : PartialCallHierarchyHandlerBase where T : class?, IHandlerIdentity? { - private readonly Action>>, CallHierarchyCapability, CancellationToken> _handleParams; + private readonly Action>>, CallHierarchyCapability, CancellationToken> + _handleParams; - private readonly Action, IObserver>, CallHierarchyCapability, CancellationToken> + private readonly Action, IObserver>, CallHierarchyCapability, + CancellationToken> _handleIncoming; - private readonly Action, IObserver>, CallHierarchyCapability, CancellationToken> + private readonly Action, IObserver>, CallHierarchyCapability, + CancellationToken> _handleOutgoing; private readonly RegistrationOptionsDelegate _registrationOptionsFactory; @@ -900,8 +986,10 @@ private readonly Action, IObserver>>, CallHierarchyCapability, CancellationToken> handleParams, - Action, IObserver>, CallHierarchyCapability, CancellationToken> handleIncoming, - Action, IObserver>, CallHierarchyCapability, CancellationToken> handleOutgoing, + Action, IObserver>, CallHierarchyCapability, CancellationToken> + handleIncoming, + Action, IObserver>, CallHierarchyCapability, CancellationToken> + handleOutgoing, RegistrationOptionsDelegate registrationOptionsFactory ) : base(progressManager) { @@ -911,18 +999,33 @@ RegistrationOptionsDelegate>> results, CancellationToken cancellationToken) => + protected override void Handle( + CallHierarchyPrepareParams request, IObserver>> results, CancellationToken cancellationToken + ) + { _handleParams(request, results, Capability, cancellationToken); + } protected override void Handle( CallHierarchyIncomingCallsParams request, IObserver> results, CancellationToken cancellationToken - ) => _handleIncoming(request, results, Capability, cancellationToken); + ) + { + _handleIncoming(request, results, Capability, cancellationToken); + } protected override void Handle( CallHierarchyOutgoingCallsParams request, IObserver> results, CancellationToken cancellationToken - ) => _handleOutgoing(request, results, Capability, cancellationToken); + ) + { + _handleOutgoing(request, results, Capability, cancellationToken); + } - protected internal override CallHierarchyRegistrationOptions CreateRegistrationOptions(CallHierarchyCapability capability, ClientCapabilities clientCapabilities) => _registrationOptionsFactory(capability, clientCapabilities); + protected internal override CallHierarchyRegistrationOptions CreateRegistrationOptions( + CallHierarchyCapability capability, ClientCapabilities clientCapabilities + ) + { + return _registrationOptionsFactory(capability, clientCapabilities); + } } } } diff --git a/src/Protocol/Features/Document/CodeActionFeature.cs b/src/Protocol/Features/Document/CodeActionFeature.cs index c89ea2556..19bf652b9 100644 --- a/src/Protocol/Features/Document/CodeActionFeature.cs +++ b/src/Protocol/Features/Document/CodeActionFeature.cs @@ -24,28 +24,29 @@ namespace Models /// [Parallel] [Method(TextDocumentNames.CodeAction, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(CodeActionRegistrationOptions)), Capability(typeof(CodeActionCapability)), Resolver(typeof(CodeAction))] - public partial record CodeActionParams : ITextDocumentIdentifierParams, IPartialItemsRequest, IWorkDoneProgressParams + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(CodeActionRegistrationOptions))] + [Capability(typeof(CodeActionCapability))] + [Resolver(typeof(CodeAction))] + public partial record CodeActionParams : ITextDocumentIdentifierParams, IPartialItemsRequest, + IWorkDoneProgressParams { /// /// The document in which the command was invoked. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; /// /// The range for which the command was invoked. /// - public Range Range { get; init; } + public Range Range { get; init; } = null!; /// /// Context carrying additional information. /// - public CodeActionContext Context { get; init; } + public CodeActionContext Context { get; init; } = null!; } /// @@ -61,7 +62,7 @@ public record CodeActionContext /// that these accurately reflect the error state of the resource. The primary parameter /// to compute code actions is the provided range. /// - public Container Diagnostics { get; init; } + public Container Diagnostics { get; init; } = null!; /// /// Requested kind of actions to return. @@ -76,20 +77,18 @@ public record CodeActionContext [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] [Parallel] [Method(TextDocumentNames.CodeActionResolve, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "CodeActionResolve"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)), - GenerateTypedData, - GenerateContainer - ] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "CodeActionResolve")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [GenerateTypedData] + [GenerateContainer] [Capability(typeof(CodeActionCapability))] public partial record CodeAction : ICanBeResolved, IRequest, IDoesNotParticipateInRegistration { /// /// A short, human-readable, title for this code action. /// - public string Title { get; init; } + public string Title { get; init; } = null!; /// /// The kind of the code action. @@ -133,19 +132,19 @@ public partial record CodeAction : ICanBeResolved, IRequest, IDoesNo /// /// Marks that the code action cannot currently be applied. - /// + /// /// Clients should follow the following guidelines regarding disabled code actions: - /// - /// - Disabled code actions are not shown in automatic [lightbulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) - /// code action menu. - /// - /// - Disabled actions are shown as faded out in the code action menu when the user request a more specific type - /// of code action, such as refactorings. - /// - /// - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions) - /// that auto applies a code action and only a disabled code actions are returned, the client should show the user an - /// error message with `reason` in the editor. - /// + /// + /// - Disabled code actions are not shown in automatic [lightbulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) + /// code action menu. + /// + /// - Disabled actions are shown as faded out in the code action menu when the user request a more specific type + /// of code action, such as refactorings. + /// + /// - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions) + /// that auto applies a code action and only a disabled code actions are returned, the client should show the user an + /// error message with `reason` in the editor. + /// /// @since 3.16.0 /// [Optional] @@ -161,24 +160,27 @@ public partial record CodeAction : ICanBeResolved, IRequest, IDoesNo private string DebuggerDisplay => $"[{Kind}] {Title}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } /// /// Marks that the code action cannot currently be applied. - /// + /// /// Clients should follow the following guidelines regarding disabled code actions: - /// - /// - Disabled code actions are not shown in automatic [lightbulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) - /// code action menu. - /// - /// - Disabled actions are shown as faded out in the code action menu when the user request a more specific type - /// of code action, such as refactorings. - /// - /// - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions) - /// that auto applies a code action and only a disabled code actions are returned, the client should show the user an - /// error message with `reason` in the editor. - /// + /// + /// - Disabled code actions are not shown in automatic [lightbulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) + /// code action menu. + /// + /// - Disabled actions are shown as faded out in the code action menu when the user request a more specific type + /// of code action, such as refactorings. + /// + /// - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions) + /// that auto applies a code action and only a disabled code actions are returned, the client should show the user an + /// error message with `reason` in the editor. + /// /// @since 3.16.0 /// public record CodeActionDisabled @@ -188,7 +190,7 @@ public record CodeActionDisabled /// /// This is displayed in the code actions UI. /// - public string Reason { get; init; } + public string Reason { get; init; } = null!; } [JsonConverter(typeof(CommandOrCodeActionConverter))] @@ -216,7 +218,8 @@ public CommandOrCodeAction(Command value) public Command? Command { get => _command; - set { + set + { _command = value; _codeAction = null; } @@ -227,7 +230,8 @@ public Command? Command public CodeAction? CodeAction { get => _codeAction; - set { + set + { _command = default; _codeAction = value; } @@ -235,29 +239,52 @@ public CodeAction? CodeAction public object? RawValue { - get { + get + { if (IsCommand) return Command!; if (IsCodeAction) return CodeAction!; return default; } } - public static CommandOrCodeAction From(Command value) => new(value); - public static implicit operator CommandOrCodeAction(Command value) => new(value); + public static CommandOrCodeAction From(Command value) + { + return new(value); + } + + public static implicit operator CommandOrCodeAction(Command value) + { + return new(value); + } + + public static CommandOrCodeAction From(CodeAction value) + { + return new(value); + } + + public static implicit operator CommandOrCodeAction(CodeAction value) + { + return new(value); + } - public static CommandOrCodeAction From(CodeAction value) => new(value); - public static implicit operator CommandOrCodeAction(CodeAction value) => new(value); - public static CommandOrCodeAction From(CodeAction value) where T : class?, IHandlerIdentity? => new(value); + public static CommandOrCodeAction From(CodeAction value) where T : class?, IHandlerIdentity? + { + return new(value); + } private string DebuggerDisplay => $"{( IsCommand ? $"command: {Command}" : IsCodeAction ? $"code action: {CodeAction}" : "..." )}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } JToken? ICanBeResolved.Data { get => _codeAction?.Data; - init { + init + { if (_codeAction == null) return; _codeAction = _codeAction with { Data = value }; } @@ -266,7 +293,10 @@ public object? RawValue public partial class CodeActionContainer { - public static implicit operator CommandOrCodeActionContainer(CodeActionContainer container) => new(container.Select(CommandOrCodeAction.From)); + public static implicit operator CommandOrCodeActionContainer(CodeActionContainer container) + { + return new(container.Select(CommandOrCodeAction.From)); + } } [GenerateRegistrationOptions(nameof(ServerCapabilities.CodeActionProvider))] @@ -292,7 +322,7 @@ public partial class CodeActionRegistrationOptions : IWorkDoneProgressOptions, I [Optional] public bool ResolveProvider { get; set; } - class CodeActionRegistrationOptionsConverter : RegistrationOptionsConverterBase + private class CodeActionRegistrationOptionsConverter : RegistrationOptionsConverterBase { private readonly IHandlersManager _handlersManager; @@ -303,7 +333,8 @@ public CodeActionRegistrationOptionsConverter(IHandlersManager handlersManager) public override StaticOptions Convert(CodeActionRegistrationOptions source) { - return new() { + return new() + { CodeActionKinds = source.CodeActionKinds, ResolveProvider = source.ResolveProvider || _handlersManager.Descriptors.Any(z => z.HandlerType == typeof(ICodeActionResolveHandler)), WorkDoneProgress = source.WorkDoneProgress, @@ -408,8 +439,8 @@ public partial class CodeActionCapability : DynamicCapability public bool IsPreferredSupport { get; set; } /// - /// Whether code action supports the `disabled` property. - /// + /// Whether code action supports the `disabled` property. + /// /// @since 3.16.0 /// [Optional] diff --git a/src/Protocol/Features/Document/CodeLensFeature.cs b/src/Protocol/Features/Document/CodeLensFeature.cs index dee397f4d..66d7ea1d5 100644 --- a/src/Protocol/Features/Document/CodeLensFeature.cs +++ b/src/Protocol/Features/Document/CodeLensFeature.cs @@ -19,18 +19,18 @@ namespace Models { [Parallel] [Method(TextDocumentNames.CodeLens, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(CodeLensRegistrationOptions)), Capability(typeof(CodeLensCapability)), Resolver(typeof(CodeLens))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(CodeLensRegistrationOptions))] + [Capability(typeof(CodeLensCapability))] + [Resolver(typeof(CodeLens))] public partial record CodeLensParams : ITextDocumentIdentifierParams, IWorkDoneProgressParams, IPartialItemsRequest { /// /// The document to request code lens for. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; } /// @@ -43,20 +43,18 @@ public partial record CodeLensParams : ITextDocumentIdentifierParams, IWorkDoneP [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] [Parallel] [Method(TextDocumentNames.CodeLensResolve, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "CodeLensResolve"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)), - GenerateTypedData, - GenerateContainer - ] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "CodeLensResolve")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [GenerateTypedData] + [GenerateContainer] [Capability(typeof(CodeLensCapability))] public partial record CodeLens : IRequest, ICanBeResolved, IDoesNotParticipateInRegistration { /// /// The range in which this code lens is valid. Should only span a single line. /// - public Range Range { get; init; } + public Range Range { get; init; } = null!; /// /// The command this code lens represents. @@ -74,7 +72,10 @@ public partial record CodeLens : IRequest, ICanBeResolved, IDoesNotPar private string DebuggerDisplay => $"{Range}{( Command != null ? $" {Command}" : "" )}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } [GenerateRegistrationOptions(nameof(ServerCapabilities.CodeLensProvider))] @@ -99,7 +100,8 @@ public CodeLensRegistrationOptionsConverter(IHandlersManager handlersManager) public override StaticOptions Convert(CodeLensRegistrationOptions source) { - return new() { + return new() + { ResolveProvider = source.ResolveProvider || _handlersManager.Descriptors.Any(z => z.HandlerType == typeof(ICodeLensResolveHandler)), WorkDoneProgress = source.WorkDoneProgress }; @@ -112,12 +114,11 @@ namespace Models { [Parallel] [Method(WorkspaceNames.CodeLensRefresh, Direction.ServerToClient)] - [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace"), GenerateHandlerMethods, - GenerateRequestMethods(typeof(IWorkspaceLanguageServer), typeof(ILanguageServer))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageServer), typeof(ILanguageServer))] [Capability(typeof(CodeLensWorkspaceClientCapabilities))] - public partial record CodeLensRefreshParams : IRequest - { - } + public partial record CodeLensRefreshParams : IRequest; } namespace Client.Capabilities diff --git a/src/Protocol/Features/Document/ColorFeature.cs b/src/Protocol/Features/Document/ColorFeature.cs index 852868d44..ee8d60b24 100644 --- a/src/Protocol/Features/Document/ColorFeature.cs +++ b/src/Protocol/Features/Document/ColorFeature.cs @@ -15,12 +15,11 @@ namespace Models { [Parallel] [Method(TextDocumentNames.DocumentColor, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(DocumentColorRegistrationOptions)), Capability(typeof(ColorProviderCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(DocumentColorRegistrationOptions))] + [Capability(typeof(ColorProviderCapability))] public partial record DocumentColorParams : IPartialItemsRequest, ColorInformation>, IWorkDoneProgressParams { /// @@ -43,7 +42,8 @@ public partial record ColorInformation public ColorPresentationParams For(TextDocumentIdentifier textDocumentIdentifier) { - return new ColorPresentationParams() { + return new ColorPresentationParams + { Color = Color, Range = Range, TextDocument = textDocumentIdentifier @@ -53,18 +53,16 @@ public ColorPresentationParams For(TextDocumentIdentifier textDocumentIdentifier [Parallel] [Method(TextDocumentNames.ColorPresentation, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] [Capability(typeof(ColorProviderCapability))] public partial record ColorPresentationParams : ColorInformation, IRequest>, IDoesNotParticipateInRegistration { /// /// The document to provide document links for. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; } public partial record ColorPresentation @@ -74,7 +72,7 @@ public partial record ColorPresentation /// picker header. By default this is also the text that is inserted when selecting /// this color presentation. /// - public string Label { get; init; } + public string Label { get; init; } = null!; /// /// An [edit](#TextEdit) which is applied to a document when selecting @@ -121,7 +119,10 @@ public record DocumentColor private string DebuggerDisplay => $"R:{Red} G:{Green} B:{Blue} A:{Alpha}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } [GenerateRegistrationOptions(nameof(ServerCapabilities.ColorProvider))] diff --git a/src/Protocol/Features/Document/DeclarationFeature.cs b/src/Protocol/Features/Document/DeclarationFeature.cs index 179d73a6e..38654f594 100644 --- a/src/Protocol/Features/Document/DeclarationFeature.cs +++ b/src/Protocol/Features/Document/DeclarationFeature.cs @@ -12,13 +12,13 @@ namespace Models { [Parallel] [Method(TextDocumentNames.Declaration, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(DeclarationRegistrationOptions)), Capability(typeof(DeclarationCapability))] - public partial record DeclarationParams : TextDocumentPositionParams, IWorkDoneProgressParams, IPartialItemsRequest { } + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(DeclarationRegistrationOptions))] + [Capability(typeof(DeclarationCapability))] + public partial record DeclarationParams : TextDocumentPositionParams, IWorkDoneProgressParams, + IPartialItemsRequest; [GenerateRegistrationOptions(nameof(ServerCapabilities.DeclarationProvider))] [RegistrationName(TextDocumentNames.Declaration)] diff --git a/src/Protocol/Features/Document/DefinitionFeature.cs b/src/Protocol/Features/Document/DefinitionFeature.cs index 53bf9f6b2..8da8b62d4 100644 --- a/src/Protocol/Features/Document/DefinitionFeature.cs +++ b/src/Protocol/Features/Document/DefinitionFeature.cs @@ -12,15 +12,13 @@ namespace Models { [Parallel] [Method(TextDocumentNames.Definition, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(DefinitionRegistrationOptions)), Capability(typeof(DefinitionCapability))] - public partial record DefinitionParams : TextDocumentPositionParams, IWorkDoneProgressParams, IPartialItemsRequest - { - } + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(DefinitionRegistrationOptions))] + [Capability(typeof(DefinitionCapability))] + public partial record DefinitionParams : TextDocumentPositionParams, IWorkDoneProgressParams, + IPartialItemsRequest; [GenerateRegistrationOptions(nameof(ServerCapabilities.DefinitionProvider))] [RegistrationName(TextDocumentNames.Definition)] diff --git a/src/Protocol/Features/Document/DocumentFormattingFeature.cs b/src/Protocol/Features/Document/DocumentFormattingFeature.cs index 672150ca8..71bb4201a 100644 --- a/src/Protocol/Features/Document/DocumentFormattingFeature.cs +++ b/src/Protocol/Features/Document/DocumentFormattingFeature.cs @@ -13,28 +13,29 @@ namespace Models { [Parallel] [Method(TextDocumentNames.DocumentFormatting, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(DocumentFormattingRegistrationOptions)), Capability(typeof(DocumentFormattingCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(DocumentFormattingRegistrationOptions))] + [Capability(typeof(DocumentFormattingCapability))] public partial record DocumentFormattingParams : ITextDocumentIdentifierParams, IRequest, IWorkDoneProgressParams { /// /// The document to format. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; /// /// The format options. /// - public FormattingOptions Options { get; init; } + public FormattingOptions Options { get; init; } = null!; } [GenerateRegistrationOptions(nameof(ServerCapabilities.DocumentFormattingProvider))] [RegistrationName(TextDocumentNames.DocumentFormatting)] - public partial class DocumentFormattingRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions { } + public partial class DocumentFormattingRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions + { + } } namespace Client.Capabilities diff --git a/src/Protocol/Features/Document/DocumentHighlightFeature.cs b/src/Protocol/Features/Document/DocumentHighlightFeature.cs index 924186884..552354a3d 100644 --- a/src/Protocol/Features/Document/DocumentHighlightFeature.cs +++ b/src/Protocol/Features/Document/DocumentHighlightFeature.cs @@ -14,15 +14,13 @@ namespace Models { [Parallel] [Method(TextDocumentNames.DocumentHighlight, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(DocumentHighlightRegistrationOptions)), Capability(typeof(DocumentHighlightCapability))] - public partial record DocumentHighlightParams : TextDocumentPositionParams, IWorkDoneProgressParams, IPartialItemsRequest - { - } + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(DocumentHighlightRegistrationOptions))] + [Capability(typeof(DocumentHighlightCapability))] + public partial record DocumentHighlightParams : TextDocumentPositionParams, IWorkDoneProgressParams, + IPartialItemsRequest; /// /// A document highlight is a range inside a text document which deserves @@ -36,7 +34,7 @@ public partial record DocumentHighlight /// /// The range this highlight applies to. /// - public Range Range { get; init; } + public Range Range { get; init; } = null!; /// /// The highlight kind, default is DocumentHighlightKind.Text. diff --git a/src/Protocol/Features/Document/DocumentLinkFeature.cs b/src/Protocol/Features/Document/DocumentLinkFeature.cs index 9806bc14d..5dd5dd796 100644 --- a/src/Protocol/Features/Document/DocumentLinkFeature.cs +++ b/src/Protocol/Features/Document/DocumentLinkFeature.cs @@ -18,18 +18,19 @@ namespace Models { [Parallel] [Method(TextDocumentNames.DocumentLink, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(DocumentLinkRegistrationOptions)), Capability(typeof(DocumentLinkCapability)), Resolver(typeof(DocumentLink))] - public partial record DocumentLinkParams : ITextDocumentIdentifierParams, IPartialItemsRequest, IWorkDoneProgressParams + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(DocumentLinkRegistrationOptions))] + [Capability(typeof(DocumentLinkCapability))] + [Resolver(typeof(DocumentLink))] + public partial record DocumentLinkParams : ITextDocumentIdentifierParams, IPartialItemsRequest, + IWorkDoneProgressParams { /// /// The document to provide document links for. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; } /// @@ -39,20 +40,18 @@ public partial record DocumentLinkParams : ITextDocumentIdentifierParams, IParti [Parallel] [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] [Method(TextDocumentNames.DocumentLinkResolve, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "DocumentLinkResolve"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)), - GenerateTypedData, - GenerateContainer - ] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "DocumentLinkResolve")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [GenerateTypedData] + [GenerateContainer] [Capability(typeof(DocumentLinkCapability))] public partial record DocumentLink : ICanBeResolved, IRequest, IDoesNotParticipateInRegistration { /// /// The range this link applies to. /// - public Range Range { get; init; } + public Range Range { get; init; } = null!; /// /// The uri this link points to. If missing a resolve request is sent later. @@ -79,10 +78,14 @@ public partial record DocumentLink : ICanBeResolved, IRequest, IDo [Optional] public string? Tooltip { get; init; } - private string DebuggerDisplay => $"{Range}{( Target is not null ? $" {Target}" : "" )}{( string.IsNullOrWhiteSpace(Tooltip) ? $" {Tooltip}" : "" )}"; + private string DebuggerDisplay => + $"{Range}{( Target is not null ? $" {Target}" : "" )}{( string.IsNullOrWhiteSpace(Tooltip) ? $" {Tooltip}" : "" )}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } [GenerateRegistrationOptions(nameof(ServerCapabilities.DocumentLinkProvider))] @@ -96,7 +99,7 @@ public partial class DocumentLinkRegistrationOptions : ITextDocumentRegistration [Optional] public bool ResolveProvider { get; set; } - class DocumentLinkRegistrationOptionsConverter : RegistrationOptionsConverterBase + private class DocumentLinkRegistrationOptionsConverter : RegistrationOptionsConverterBase { private readonly IHandlersManager _handlersManager; @@ -105,10 +108,14 @@ public DocumentLinkRegistrationOptionsConverter(IHandlersManager handlersManager _handlersManager = handlersManager; } - public override StaticOptions Convert(DocumentLinkRegistrationOptions source) => new() { - ResolveProvider = source.ResolveProvider || _handlersManager.Descriptors.Any(z => z.HandlerType == typeof(IDocumentLinkResolveHandler)), - WorkDoneProgress = source.WorkDoneProgress, - }; + public override StaticOptions Convert(DocumentLinkRegistrationOptions source) + { + return new() + { + ResolveProvider = source.ResolveProvider || _handlersManager.Descriptors.Any(z => z.HandlerType == typeof(IDocumentLinkResolveHandler)), + WorkDoneProgress = source.WorkDoneProgress, + }; + } } } } diff --git a/src/Protocol/Features/Document/DocumentOnTypeFormattingFeature.cs b/src/Protocol/Features/Document/DocumentOnTypeFormattingFeature.cs index 44d6b9229..548d6704d 100644 --- a/src/Protocol/Features/Document/DocumentOnTypeFormattingFeature.cs +++ b/src/Protocol/Features/Document/DocumentOnTypeFormattingFeature.cs @@ -15,34 +15,33 @@ namespace Models { [Parallel] [Method(TextDocumentNames.OnTypeFormatting, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(DocumentOnTypeFormattingRegistrationOptions)), Capability(typeof(DocumentOnTypeFormattingCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(DocumentOnTypeFormattingRegistrationOptions))] + [Capability(typeof(DocumentOnTypeFormattingCapability))] public partial record DocumentOnTypeFormattingParams : ITextDocumentIdentifierParams, IRequest { /// /// The document to format. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; /// /// The position at which this request was sent. /// - public Position Position { get; init; } + public Position Position { get; init; } = null!; /// /// The character that has been typed. /// [JsonProperty("ch")] - public string Character { get; init; } + public string Character { get; init; } = null!; /// /// The format options. /// - public FormattingOptions Options { get; init; } + public FormattingOptions Options { get; init; } = null!; } [GenerateRegistrationOptions(nameof(ServerCapabilities.DocumentOnTypeFormattingProvider))] diff --git a/src/Protocol/Features/Document/DocumentRangeFormattingFeature.cs b/src/Protocol/Features/Document/DocumentRangeFormattingFeature.cs index faca31fcd..3a9d1168b 100644 --- a/src/Protocol/Features/Document/DocumentRangeFormattingFeature.cs +++ b/src/Protocol/Features/Document/DocumentRangeFormattingFeature.cs @@ -13,28 +13,27 @@ namespace Models { [Parallel] [Method(TextDocumentNames.RangeFormatting, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(DocumentRangeFormattingRegistrationOptions)), Capability(typeof(DocumentRangeFormattingCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(DocumentRangeFormattingRegistrationOptions))] + [Capability(typeof(DocumentRangeFormattingCapability))] public partial record DocumentRangeFormattingParams : ITextDocumentIdentifierParams, IRequest, IWorkDoneProgressParams { /// /// The document to format. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; /// /// The range to format /// - public Range Range { get; init; } + public Range Range { get; init; } = null!; /// /// The format options /// - public FormattingOptions Options { get; init; } + public FormattingOptions Options { get; init; } = null!; } [GenerateRegistrationOptions(nameof(ServerCapabilities.DocumentRangeFormattingProvider))] diff --git a/src/Protocol/Features/Document/DocumentSymbolFeature.cs b/src/Protocol/Features/Document/DocumentSymbolFeature.cs index c1974af9a..067e65fbd 100644 --- a/src/Protocol/Features/Document/DocumentSymbolFeature.cs +++ b/src/Protocol/Features/Document/DocumentSymbolFeature.cs @@ -16,20 +16,19 @@ namespace Models { [Parallel] [Method(TextDocumentNames.DocumentSymbol, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(DocumentSymbolRegistrationOptions)), Capability(typeof(DocumentSymbolCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(DocumentSymbolRegistrationOptions))] + [Capability(typeof(DocumentSymbolCapability))] public partial record DocumentSymbolParams : ITextDocumentIdentifierParams, - IPartialItemsRequest, - IWorkDoneProgressParams + IPartialItemsRequest, + IWorkDoneProgressParams { /// /// The text document. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; } [JsonConverter(typeof(SymbolInformationOrDocumentSymbolConverter))] @@ -55,18 +54,34 @@ public SymbolInformationOrDocumentSymbol(SymbolInformation symbolInformation) public bool IsDocumentSymbol => DocumentSymbol != null; public DocumentSymbol? DocumentSymbol { get; } - public static SymbolInformationOrDocumentSymbol Create(SymbolInformation value) => value; + public static SymbolInformationOrDocumentSymbol Create(SymbolInformation value) + { + return value; + } - public static SymbolInformationOrDocumentSymbol Create(DocumentSymbol value) => value; + public static SymbolInformationOrDocumentSymbol Create(DocumentSymbol value) + { + return value; + } - public static implicit operator SymbolInformationOrDocumentSymbol(SymbolInformation value) => new SymbolInformationOrDocumentSymbol(value); + public static implicit operator SymbolInformationOrDocumentSymbol(SymbolInformation value) + { + return new SymbolInformationOrDocumentSymbol(value); + } - public static implicit operator SymbolInformationOrDocumentSymbol(DocumentSymbol value) => new SymbolInformationOrDocumentSymbol(value); + public static implicit operator SymbolInformationOrDocumentSymbol(DocumentSymbol value) + { + return new SymbolInformationOrDocumentSymbol(value); + } - private string DebuggerDisplay => IsDocumentSymbol ? DocumentSymbol!.ToString() : IsDocumentSymbolInformation ? SymbolInformation!.ToString() : string.Empty; + private string DebuggerDisplay => + IsDocumentSymbol ? DocumentSymbol!.ToString() : IsDocumentSymbolInformation ? SymbolInformation!.ToString() : string.Empty; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } /// @@ -80,7 +95,7 @@ public record DocumentSymbol /// /// The name of this symbol. /// - public string Name { get; init; } + public string Name { get; init; } = null!; /// /// More detail for this symbol, e.g the signature of a function. If not provided the @@ -113,13 +128,13 @@ public record DocumentSymbol /// like comments. This information is typically used to determine if the the clients cursor is /// inside the symbol to reveal in the symbol in the UI. /// - public Range Range { get; init; } + public Range Range { get; init; } = null!; /// /// The range that should be selected and revealed when this symbol is being picked, e.g the name of a function. /// Must be contained by the the `range`. /// - public Range SelectionRange { get; init; } + public Range SelectionRange { get; init; } = null!; /// /// Children of this symbol, e.g. properties of a class. @@ -130,7 +145,10 @@ public record DocumentSymbol private string DebuggerDisplay => $"[{Kind}] {Name} {{ range: {Range}, selection: {SelectionRange}, detail: {Detail ?? string.Empty} }}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } [GenerateRegistrationOptions(nameof(ServerCapabilities.DocumentSymbolProvider))] diff --git a/src/Protocol/Features/Document/FoldingRangeFeature.cs b/src/Protocol/Features/Document/FoldingRangeFeature.cs index e4fdb7652..344114a6c 100644 --- a/src/Protocol/Features/Document/FoldingRangeFeature.cs +++ b/src/Protocol/Features/Document/FoldingRangeFeature.cs @@ -17,18 +17,18 @@ namespace Models { [Parallel] [Method(TextDocumentNames.FoldingRange, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "FoldingRange"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(FoldingRangeRegistrationOptions)), Capability(typeof(FoldingRangeCapability))] - public partial record FoldingRangeRequestParam : ITextDocumentIdentifierParams, IPartialItemsRequest?, FoldingRange>, IWorkDoneProgressParams + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "FoldingRange")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(FoldingRangeRegistrationOptions))] + [Capability(typeof(FoldingRangeCapability))] + public partial record FoldingRangeRequestParam : ITextDocumentIdentifierParams, IPartialItemsRequest?, FoldingRange>, + IWorkDoneProgressParams { /// /// The text document. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; } /// @@ -41,7 +41,7 @@ public partial record FoldingRange /// The zero-based line number from where the folded range starts. /// /// - /// in the LSP spec + /// in the LSP spec /// public int StartLine { get; init; } @@ -49,7 +49,7 @@ public partial record FoldingRange /// The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line. /// /// - /// in the LSP spec + /// in the LSP spec /// [Optional] public int? StartCharacter { get; init; } @@ -58,7 +58,7 @@ public partial record FoldingRange /// The zero-based line number where the folded range ends. /// /// - /// in the LSP spec + /// in the LSP spec /// public int EndLine { get; init; } @@ -66,7 +66,7 @@ public partial record FoldingRange /// The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line. /// /// - /// in the LSP spec + /// in the LSP spec /// [Optional] public int? EndCharacter { get; init; } @@ -83,7 +83,10 @@ public partial record FoldingRange $"[start: (line: {StartLine}{( StartCharacter.HasValue ? $", char: {StartCharacter}" : string.Empty )}), end: (line: {EndLine}, char: {( EndCharacter.HasValue ? $", char: {EndCharacter}" : string.Empty )})]"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } /// @@ -125,7 +128,7 @@ public partial class FoldingRangeCapability : DynamicCapability /// hint, servers are free to follow the limit. /// /// - /// in the LSP spec + /// in the LSP spec /// [Optional] public int? RangeLimit { get; set; } diff --git a/src/Protocol/Features/Document/HoverFeature.cs b/src/Protocol/Features/Document/HoverFeature.cs index 5c04e61c1..beaf09bca 100644 --- a/src/Protocol/Features/Document/HoverFeature.cs +++ b/src/Protocol/Features/Document/HoverFeature.cs @@ -16,15 +16,12 @@ namespace Models { [Parallel] [Method(TextDocumentNames.Hover, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(HoverRegistrationOptions)), Capability(typeof(HoverCapability))] - public partial record HoverParams : TextDocumentPositionParams, IWorkDoneProgressParams, IRequest - { - } + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(HoverRegistrationOptions))] + [Capability(typeof(HoverCapability))] + public partial record HoverParams : TextDocumentPositionParams, IWorkDoneProgressParams, IRequest; /// /// The result of a hover request. @@ -35,7 +32,7 @@ public partial record Hover /// /// The hover's content /// - public MarkedStringsOrMarkupContent Contents { get; init; } + public MarkedStringsOrMarkupContent Contents { get; init; } = null!; /// /// An optional range is a range inside a text document @@ -47,12 +44,17 @@ public partial record Hover private string DebuggerDisplay => $"{Contents}{( Range is not null ? $" {Range}" : string.Empty )}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } [GenerateRegistrationOptions(nameof(ServerCapabilities.HoverProvider))] [RegistrationName(TextDocumentNames.Hover)] - public partial class HoverRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions { } + public partial class HoverRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions + { + } } namespace Client.Capabilities diff --git a/src/Protocol/Features/Document/ImplementationFeature.cs b/src/Protocol/Features/Document/ImplementationFeature.cs index 668af7fa1..0d0bf5394 100644 --- a/src/Protocol/Features/Document/ImplementationFeature.cs +++ b/src/Protocol/Features/Document/ImplementationFeature.cs @@ -12,18 +12,19 @@ namespace Models { [Parallel] [Method(TextDocumentNames.Implementation, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(ImplementationRegistrationOptions)), Capability(typeof(ImplementationCapability))] - public partial record ImplementationParams : TextDocumentPositionParams, IWorkDoneProgressParams, IPartialItemsRequest { } + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(ImplementationRegistrationOptions))] + [Capability(typeof(ImplementationCapability))] + public partial record ImplementationParams : TextDocumentPositionParams, IWorkDoneProgressParams, + IPartialItemsRequest; [GenerateRegistrationOptions(nameof(ServerCapabilities.ImplementationProvider))] [RegistrationName(TextDocumentNames.Implementation)] - public partial class ImplementationRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions, IStaticRegistrationOptions { } - + public partial class ImplementationRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions, IStaticRegistrationOptions + { + } } namespace Client.Capabilities diff --git a/src/Protocol/Features/Document/LinkedEditingRangeFeature.cs b/src/Protocol/Features/Document/LinkedEditingRangeFeature.cs index 56648f81a..36e2efaf5 100644 --- a/src/Protocol/Features/Document/LinkedEditingRangeFeature.cs +++ b/src/Protocol/Features/Document/LinkedEditingRangeFeature.cs @@ -14,22 +14,20 @@ namespace Models { [Parallel] [Method(TextDocumentNames.LinkedEditingRange, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(LinkedEditingRangeRegistrationOptions)), Capability(typeof(LinkedEditingRangeClientCapabilities))] - public partial record LinkedEditingRangeParams : TextDocumentPositionParams, IWorkDoneProgressParams, IRequest - { - } + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(LinkedEditingRangeRegistrationOptions))] + [Capability(typeof(LinkedEditingRangeClientCapabilities))] + public partial record LinkedEditingRangeParams : TextDocumentPositionParams, IWorkDoneProgressParams, IRequest; + public partial record LinkedEditingRanges { /// /// A list of ranges that can be renamed together. The ranges must have /// identical length and contain identical text content. The ranges cannot overlap. /// - public Container Ranges { get; init; } + public Container Ranges { get; init; } = null!; /// /// An optional word pattern (regular expression) that describes valid contents for @@ -39,16 +37,20 @@ public partial record LinkedEditingRanges [Optional] public string? WordPattern { get; init; } } + [GenerateRegistrationOptions(nameof(ServerCapabilities.LinkedEditingRangeProvider))] [RegistrationName(TextDocumentNames.LinkedEditingRange)] - public partial class LinkedEditingRangeRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions { } - + public partial class LinkedEditingRangeRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions + { + } } namespace Client.Capabilities { [CapabilityKey(nameof(ClientCapabilities.TextDocument), nameof(TextDocumentClientCapabilities.LinkedEditingRange))] - public partial class LinkedEditingRangeClientCapabilities : DynamicCapability { } + public partial class LinkedEditingRangeClientCapabilities : DynamicCapability + { + } } namespace Document diff --git a/src/Protocol/Features/Document/MonikerFeature.cs b/src/Protocol/Features/Document/MonikerFeature.cs index c01b235bf..fe9cfab03 100644 --- a/src/Protocol/Features/Document/MonikerFeature.cs +++ b/src/Protocol/Features/Document/MonikerFeature.cs @@ -23,15 +23,12 @@ namespace Models /// [Parallel] [Method(TextDocumentNames.Moniker, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(MonikerRegistrationOptions)), Capability(typeof(MonikerCapability))] - public partial record MonikerParams : TextDocumentPositionParams, IWorkDoneProgressParams, IPartialItemsRequest?, Moniker> - { - } + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(MonikerRegistrationOptions))] + [Capability(typeof(MonikerCapability))] + public partial record MonikerParams : TextDocumentPositionParams, IWorkDoneProgressParams, IPartialItemsRequest?, Moniker>; /// /// Moniker definition to match LSIF 0.5 moniker definition. @@ -41,13 +38,13 @@ public partial record Moniker /// /// The scheme of the moniker. For example tsc or .Net /// - public string Scheme { get; init; } + public string Scheme { get; init; } = null!; /// /// The identifier of the moniker. The value is opaque in LSIF however /// schema owners are allowed to define the structure if they want. /// - public string Identifier { get; init; } + public string Identifier { get; init; } = null!; /// /// The scope in which the moniker is unique @@ -70,18 +67,18 @@ public readonly partial struct MonikerKind /// /// The moniker represent a symbol that is imported into a project /// - public static readonly MonikerKind Import = new MonikerKind("import"); + public static MonikerKind Import { get; } = new MonikerKind("import"); /// /// The moniker represents a symbol that is exported from a project /// - public static readonly MonikerKind Export = new MonikerKind("export"); + public static MonikerKind Export { get; } = new MonikerKind("export"); /// /// The moniker represents a symbol that is local to a project (e.g. a local /// variable of a function, a class not visible outside the project, ...) /// - public static readonly MonikerKind Local = new MonikerKind("local"); + public static MonikerKind Local { get; } = new MonikerKind("local"); } @@ -94,28 +91,29 @@ public readonly partial struct UniquenessLevel /// /// The moniker is only unique inside a document /// - public static readonly UniquenessLevel Document = new UniquenessLevel("document"); + public static UniquenessLevel Document { get; } = new UniquenessLevel("document"); /// /// The moniker is unique inside a project for which a dump got created /// - public static readonly UniquenessLevel Project = new UniquenessLevel("project"); + public static UniquenessLevel Project { get; } = new UniquenessLevel("project"); /// /// The moniker is unique inside the group to which a project belongs /// - public static readonly UniquenessLevel Group = new UniquenessLevel("group"); + public static UniquenessLevel Group { get; } = new UniquenessLevel("group"); /// /// The moniker is unique inside the moniker scheme. /// - public static readonly UniquenessLevel Scheme = new UniquenessLevel("scheme"); + public static UniquenessLevel Scheme { get; } = new UniquenessLevel("scheme"); /// /// The moniker is globally unique /// - public static readonly UniquenessLevel Global = new UniquenessLevel("global"); + public static UniquenessLevel Global { get; } = new UniquenessLevel("global"); } + [GenerateRegistrationOptions(nameof(ServerCapabilities.MonikerProvider))] [RegistrationName(TextDocumentNames.Moniker)] public partial class MonikerRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions diff --git a/src/Protocol/Features/Document/RenameFeature.cs b/src/Protocol/Features/Document/RenameFeature.cs index 5915060e2..48ae01358 100644 --- a/src/Protocol/Features/Document/RenameFeature.cs +++ b/src/Protocol/Features/Document/RenameFeature.cs @@ -16,50 +16,46 @@ namespace Models { [Parallel] [Method(TextDocumentNames.Rename, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(RenameRegistrationOptions)), Capability(typeof(RenameCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(RenameRegistrationOptions))] + [Capability(typeof(RenameCapability))] public partial record RenameParams : ITextDocumentIdentifierParams, IRequest, IWorkDoneProgressParams { /// /// The document to format. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; /// /// The position at which this request was sent. /// - public Position Position { get; init; } + public Position Position { get; init; } = null!; /// /// The new name of the symbol. If the given name is not valid the /// request must return a [ResponseError](#ResponseError) with an /// appropriate message set. /// - public string NewName { get; init; } + public string NewName { get; init; } = null!; } [Parallel] [Method(TextDocumentNames.PrepareRename, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(RenameRegistrationOptions)), Capability(typeof(RenameCapability))] - public partial record PrepareRenameParams : TextDocumentPositionParams, IRequest - { - } + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(RenameRegistrationOptions))] + [Capability(typeof(RenameCapability))] + public partial record PrepareRenameParams : TextDocumentPositionParams, IRequest; [JsonConverter(typeof(RangeOrPlaceholderRangeConverter))] public record RangeOrPlaceholderRange { - private RenameDefaultBehavior? _renameDefaultBehavior; - private Range? _range; - private PlaceholderRange? _placeholderRange; + private readonly RenameDefaultBehavior? _renameDefaultBehavior; + private readonly Range? _range; + private readonly PlaceholderRange? _placeholderRange; public RangeOrPlaceholderRange(Range value) { @@ -81,7 +77,8 @@ public RangeOrPlaceholderRange(RenameDefaultBehavior renameDefaultBehavior) public PlaceholderRange? PlaceholderRange { get => _placeholderRange; - init { + init + { _placeholderRange = value; _renameDefaultBehavior = default; _range = null; @@ -93,7 +90,8 @@ public PlaceholderRange? PlaceholderRange public Range? Range { get => _range; - init { + init + { _placeholderRange = default; _renameDefaultBehavior = default; _range = value; @@ -105,7 +103,8 @@ public Range? Range public RenameDefaultBehavior? DefaultBehavior { get => _renameDefaultBehavior; - init { + init + { _placeholderRange = default; _renameDefaultBehavior = value; _range = default; @@ -114,7 +113,8 @@ public RenameDefaultBehavior? DefaultBehavior public object? RawValue { - get { + get + { if (IsPlaceholderRange) return PlaceholderRange; if (IsRange) return Range; if (IsDefaultBehavior) return DefaultBehavior; @@ -122,15 +122,21 @@ public object? RawValue } } - public static implicit operator RangeOrPlaceholderRange(PlaceholderRange value) => new RangeOrPlaceholderRange(value); + public static implicit operator RangeOrPlaceholderRange(PlaceholderRange value) + { + return new RangeOrPlaceholderRange(value); + } - public static implicit operator RangeOrPlaceholderRange(Range value) => new RangeOrPlaceholderRange(value); + public static implicit operator RangeOrPlaceholderRange(Range value) + { + return new RangeOrPlaceholderRange(value); + } } public record PlaceholderRange { - public Range Range { get; init; } - public string Placeholder { get; init; } + public Range Range { get; init; } = null!; + public string Placeholder { get; init; } = null!; } public record RenameDefaultBehavior diff --git a/src/Protocol/Features/Document/SelectionRangeFeature.cs b/src/Protocol/Features/Document/SelectionRangeFeature.cs index 3f5db9a38..035eea136 100644 --- a/src/Protocol/Features/Document/SelectionRangeFeature.cs +++ b/src/Protocol/Features/Document/SelectionRangeFeature.cs @@ -14,23 +14,23 @@ namespace Models { [Parallel] [Method(TextDocumentNames.SelectionRange, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(SelectionRangeRegistrationOptions)), Capability(typeof(SelectionRangeCapability))] - public partial record SelectionRangeParams : ITextDocumentIdentifierParams, IPartialItemsRequest?, SelectionRange>, IWorkDoneProgressParams + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(SelectionRangeRegistrationOptions))] + [Capability(typeof(SelectionRangeCapability))] + public partial record SelectionRangeParams : ITextDocumentIdentifierParams, IPartialItemsRequest?, SelectionRange>, + IWorkDoneProgressParams { /// /// The text document. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; /// /// The positions inside the text document. /// - public Container Positions { get; init; } + public Container Positions { get; init; } = null!; } [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] @@ -39,22 +39,27 @@ public partial record SelectionRange /// /// The [range](#Range) of this selection range. /// - public Range Range { get; init; } + public Range Range { get; init; } = null!; /// /// The parent selection range containing this range. Therefore `parent.range` must contain `this.range`. /// - public SelectionRange Parent { get; init; } + public SelectionRange Parent { get; init; } = null!; private string DebuggerDisplay => $"{Range} {{{Parent}}}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } [GenerateRegistrationOptions(nameof(ServerCapabilities.SelectionRangeProvider))] [RegistrationName(TextDocumentNames.SelectionRange)] - public partial class SelectionRangeRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions, IStaticRegistrationOptions { } + public partial class SelectionRangeRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions, IStaticRegistrationOptions + { + } } namespace Client.Capabilities diff --git a/src/Protocol/Features/Document/SemanticTokensFeature.cs b/src/Protocol/Features/Document/SemanticTokensFeature.cs index 99f1236cc..7185fdfca 100644 --- a/src/Protocol/Features/Document/SemanticTokensFeature.cs +++ b/src/Protocol/Features/Document/SemanticTokensFeature.cs @@ -30,19 +30,18 @@ namespace Models /// [Parallel] [Method(TextDocumentNames.SemanticTokensFull, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "SemanticTokensFull"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(SemanticTokensRegistrationOptions)), Capability(typeof(SemanticTokensCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document", Name = "SemanticTokensFull")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(SemanticTokensRegistrationOptions))] + [Capability(typeof(SemanticTokensCapability))] public partial record SemanticTokensParams : IWorkDoneProgressParams, ITextDocumentIdentifierParams, IPartialItemRequest { /// /// The text document. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; } /// @@ -50,24 +49,24 @@ public partial record SemanticTokensParams : IWorkDoneProgressParams, ITextDocum /// [Parallel] [Method(TextDocumentNames.SemanticTokensFullDelta, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(SemanticTokensRegistrationOptions)), Capability(typeof(SemanticTokensCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(SemanticTokensRegistrationOptions))] + [Capability(typeof(SemanticTokensCapability))] public partial record SemanticTokensDeltaParams : IWorkDoneProgressParams, ITextDocumentIdentifierParams, - IPartialItemRequest, IDoesNotParticipateInRegistration + IPartialItemRequest, + IDoesNotParticipateInRegistration { /// /// The text document. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; /// /// The previous result id. /// - public string PreviousResultId { get; init; } + public string PreviousResultId { get; init; } = null!; } /// @@ -75,34 +74,32 @@ public partial record SemanticTokensDeltaParams : IWorkDoneProgressParams, IText /// [Parallel] [Method(TextDocumentNames.SemanticTokensRange, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(SemanticTokensRegistrationOptions)), Capability(typeof(SemanticTokensCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(SemanticTokensRegistrationOptions))] + [Capability(typeof(SemanticTokensCapability))] public partial record SemanticTokensRangeParams : IWorkDoneProgressParams, ITextDocumentIdentifierParams, IPartialItemRequest, IDoesNotParticipateInRegistration { /// /// The text document. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; /// /// The range the semantic tokens are requested for. /// - public Range Range { get; init; } + public Range Range { get; init; } = null!; } [Parallel] [Method(WorkspaceNames.SemanticTokensRefresh, Direction.ServerToClient)] - [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace"), GenerateHandlerMethods, - GenerateRequestMethods(typeof(IWorkspaceLanguageServer), typeof(ILanguageServer))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageServer), typeof(ILanguageServer))] [Capability(typeof(SemanticTokensWorkspaceCapability))] - public partial record SemanticTokensRefreshParams : IRequest - { - } + public partial record SemanticTokensRefreshParams : IRequest; public interface ISemanticTokenResult { @@ -145,15 +142,19 @@ public SemanticTokens(SemanticTokensPartialResult partialResult) /// https://github.com/microsoft/vscode-extension-samples/blob/5ae1f7787122812dcc84e37427ca90af5ee09f14/semantic-tokens-sample/vscode.proposed.d.ts#L71 /// /// - /// in the LSP spec + /// in the LSP spec /// public ImmutableArray Data { get; init; } [return: NotNullIfNotNull("result")] - public static SemanticTokens? From(SemanticTokensPartialResult? result) => result switch { - not null => new SemanticTokens(result), - _ => null - }; + public static SemanticTokens? From(SemanticTokensPartialResult? result) + { + return result switch + { + not null => new SemanticTokens(result), + _ => null + }; + } } /// @@ -168,9 +169,14 @@ public partial record SemanticTokensPartialResult /// public ImmutableArray Data { get; init; } - public SemanticTokensPartialResult() {} + public SemanticTokensPartialResult() + { + } - internal SemanticTokensPartialResult(SemanticTokens? result) => Data = result?.Data ?? ImmutableArray.Empty; + internal SemanticTokensPartialResult(SemanticTokens? result) + { + Data = result?.Data ?? ImmutableArray.Empty; + } } @@ -201,7 +207,7 @@ public SemanticTokensDelta(SemanticTokensDeltaPartialResult partialResult) /// For a detailed description how these edits are structured pls see /// https://github.com/microsoft/vscode-extension-samples/blob/5ae1f7787122812dcc84e37427ca90af5ee09f14/semantic-tokens-sample/vscode.proposed.d.ts#L131 /// - public Container Edits { get; init; } + public Container Edits { get; init; } = null!; } /// @@ -214,11 +220,16 @@ public record SemanticTokensDeltaPartialResult /// structured pls see /// https://github.com/microsoft/vscode-extension-samples/blob/5ae1f7787122812dcc84e37427ca90af5ee09f14/semantic-tokens-sample/vscode.proposed.d.ts#L71 /// - public Container Edits { get; init; } - public SemanticTokensDeltaPartialResult() {} + public Container Edits { get; init; } = null!; - internal SemanticTokensDeltaPartialResult(SemanticTokensDelta? result) => Edits = result?.Edits ?? new Container(); + public SemanticTokensDeltaPartialResult() + { + } + internal SemanticTokensDeltaPartialResult(SemanticTokensDelta? result) + { + Edits = result?.Edits ?? new Container(); + } } /// @@ -230,7 +241,7 @@ public record SemanticTokensEdit /// The start index of the edit /// /// - /// in the LSP spec + /// in the LSP spec /// public int Start { get; init; } @@ -238,7 +249,7 @@ public record SemanticTokensEdit /// The number of items to delete /// /// - /// in the LSP spec + /// in the LSP spec /// public int DeleteCount { get; init; } @@ -248,7 +259,7 @@ public record SemanticTokensEdit /// https://github.com/microsoft/vscode-extension-samples/blob/5ae1f7787122812dcc84e37427ca90af5ee09f14/semantic-tokens-sample/vscode.proposed.d.ts#L71 /// /// - /// in the LSP spec + /// in the LSP spec /// [Optional] public ImmutableArray? Data { get; init; } = ImmutableArray.Empty; @@ -276,7 +287,8 @@ public SemanticTokensFullOrDelta(SemanticTokensFullOrDeltaPartialResult partialR if (partialResult.IsDelta) { - Delta = new SemanticTokensDelta(partialResult.Delta!) { + Delta = new SemanticTokensDelta(partialResult.Delta!) + { Edits = partialResult.Delta!.Edits }; } @@ -294,41 +306,64 @@ public SemanticTokensFullOrDelta(SemanticTokensFullOrDeltaPartialResult partialR public SemanticTokensDelta? Delta { get; init; } [return: NotNullIfNotNull("semanticTokensDelta")] - public static SemanticTokensFullOrDelta? From(SemanticTokensDelta? semanticTokensDelta) => semanticTokensDelta switch { - not null => new(semanticTokensDelta), - _ => null - }; + public static SemanticTokensFullOrDelta? From(SemanticTokensDelta? semanticTokensDelta) + { + return semanticTokensDelta switch + { + not null => new(semanticTokensDelta), + _ => null + }; + } [return: NotNullIfNotNull("semanticTokensDelta")] - public static implicit operator SemanticTokensFullOrDelta?(SemanticTokensDelta? semanticTokensDelta) => semanticTokensDelta switch { - not null => new(semanticTokensDelta), - _ => null - }; + public static implicit operator SemanticTokensFullOrDelta?(SemanticTokensDelta? semanticTokensDelta) + { + return semanticTokensDelta switch + { + not null => new(semanticTokensDelta), + _ => null + }; + } [return: NotNullIfNotNull("semanticTokens")] - public static SemanticTokensFullOrDelta? From(SemanticTokens? semanticTokens) => semanticTokens switch { - not null => new(semanticTokens), - _ => null - }; + public static SemanticTokensFullOrDelta? From(SemanticTokens? semanticTokens) + { + return semanticTokens switch + { + not null => new(semanticTokens), + _ => null + }; + } [return: NotNullIfNotNull("semanticTokens")] - public static implicit operator SemanticTokensFullOrDelta?(SemanticTokens? semanticTokens) => semanticTokens switch { - not null => new(semanticTokens), - _ => null - }; + public static implicit operator SemanticTokensFullOrDelta?(SemanticTokens? semanticTokens) + { + return semanticTokens switch + { + not null => new(semanticTokens), + _ => null + }; + } [return: NotNullIfNotNull("semanticTokens")] - public static SemanticTokensFullOrDelta? From(SemanticTokensFullOrDeltaPartialResult? semanticTokens) => semanticTokens switch { - not null => new(semanticTokens), - _ => null - }; + public static SemanticTokensFullOrDelta? From(SemanticTokensFullOrDeltaPartialResult? semanticTokens) + { + return semanticTokens switch + { + not null => new(semanticTokens), + _ => null + }; + } [return: NotNullIfNotNull("semanticTokens")] - public static implicit operator SemanticTokensFullOrDelta?(SemanticTokensFullOrDeltaPartialResult? semanticTokens) => - semanticTokens switch { + public static implicit operator SemanticTokensFullOrDelta?(SemanticTokensFullOrDeltaPartialResult? semanticTokens) + { + return semanticTokens switch + { not null => new(semanticTokens), _ => null }; + } } [JsonConverter(typeof(SemanticTokensFullOrDeltaPartialResultConverter))] @@ -369,14 +404,20 @@ public SemanticTokensFullOrDeltaPartialResult(SemanticTokensFullOrDelta delta) public bool IsFull => Full != null; public SemanticTokensPartialResult? Full { get; } - public static implicit operator SemanticTokensFullOrDeltaPartialResult(SemanticTokensPartialResult semanticTokensPartialResult) => - new SemanticTokensFullOrDeltaPartialResult(semanticTokensPartialResult); + public static implicit operator SemanticTokensFullOrDeltaPartialResult(SemanticTokensPartialResult semanticTokensPartialResult) + { + return new SemanticTokensFullOrDeltaPartialResult(semanticTokensPartialResult); + } - public static implicit operator SemanticTokensFullOrDeltaPartialResult(SemanticTokensDeltaPartialResult semanticTokensDeltaPartialResult) => - new SemanticTokensFullOrDeltaPartialResult(semanticTokensDeltaPartialResult); + public static implicit operator SemanticTokensFullOrDeltaPartialResult(SemanticTokensDeltaPartialResult semanticTokensDeltaPartialResult) + { + return new SemanticTokensFullOrDeltaPartialResult(semanticTokensDeltaPartialResult); + } - public static implicit operator SemanticTokensFullOrDelta(SemanticTokensFullOrDeltaPartialResult semanticTokensDeltaPartialResult) => - new SemanticTokensFullOrDelta(semanticTokensDeltaPartialResult); + public static implicit operator SemanticTokensFullOrDelta(SemanticTokensFullOrDeltaPartialResult semanticTokensDeltaPartialResult) + { + return new SemanticTokensFullOrDelta(semanticTokensDeltaPartialResult); + } } /// @@ -468,7 +509,8 @@ public int GetTokenModifiersIdentity(IEnumerable? tokenMo ); } - private void EnsureTokenTypes() => + private void EnsureTokenTypes() + { _tokenTypesData ??= TokenTypes .Select( (value, index) => ( @@ -478,8 +520,10 @@ private void EnsureTokenTypes() => ) .Where(z => !string.IsNullOrWhiteSpace(z.value)) .ToImmutableDictionary(z => z.value, z => z.index); + } - private void EnsureTokenModifiers() => + private void EnsureTokenModifiers() + { _tokenModifiersData ??= TokenModifiers .Select( (value, index) => ( @@ -489,6 +533,7 @@ private void EnsureTokenModifiers() => ) .Where(z => !string.IsNullOrWhiteSpace(z.value)) .ToImmutableDictionary(z => z.value, z => Convert.ToInt32(Math.Pow(2, z.index))); + } } /// @@ -584,7 +629,7 @@ public partial class SemanticTokensRegistrationOptions : ITextDocumentRegistrati [Optional] public BooleanOr? Full { get; set; } - class SemanticTokensRegistrationOptionsConverter : RegistrationOptionsConverterBase + private class SemanticTokensRegistrationOptionsConverter : RegistrationOptionsConverterBase { private readonly IHandlersManager _handlersManager; @@ -595,7 +640,8 @@ public SemanticTokensRegistrationOptionsConverter(IHandlersManager handlersManag public override StaticOptions Convert(SemanticTokensRegistrationOptions source) { - var result = new StaticOptions { + var result = new StaticOptions + { WorkDoneProgress = source.WorkDoneProgress, Legend = source.Legend, Full = source.Full, @@ -607,7 +653,8 @@ public override StaticOptions Convert(SemanticTokensRegistrationOptions source) if (edits) { result.Full = new BooleanOr( - new SemanticTokensCapabilityRequestFull { + new SemanticTokensCapabilityRequestFull + { Delta = true } ); @@ -724,11 +771,10 @@ public class SemanticTokensWorkspaceCapability : ICapability namespace Document { - public abstract class SemanticTokensHandlerBase : - AbstractHandlers.Base, - ISemanticTokensFullHandler, - ISemanticTokensDeltaHandler, - ISemanticTokensRangeHandler + public abstract class SemanticTokensHandlerBase : AbstractHandlers.Base, + ISemanticTokensFullHandler, + ISemanticTokensDeltaHandler, + ISemanticTokensRangeHandler { public virtual async Task Handle(SemanticTokensParams request, CancellationToken cancellationToken) { @@ -755,14 +801,20 @@ public abstract class SemanticTokensHandlerBase : } protected abstract Task Tokenize(SemanticTokensBuilder builder, ITextDocumentIdentifierParams identifier, CancellationToken cancellationToken); - protected abstract Task GetSemanticTokensDocument(ITextDocumentIdentifierParams @params, CancellationToken cancellationToken); + + protected abstract Task GetSemanticTokensDocument( + ITextDocumentIdentifierParams @params, CancellationToken cancellationToken + ); } public static partial class SemanticTokensExtensions { - private static SemanticTokensRegistrationOptions RegistrationOptionsFactory(SemanticTokensCapability capability, ClientCapabilities clientCapabilities) + private static SemanticTokensRegistrationOptions RegistrationOptionsFactory( + SemanticTokensCapability capability, ClientCapabilities clientCapabilities + ) { - var registrationOptions = new SemanticTokensRegistrationOptions { + var registrationOptions = new SemanticTokensRegistrationOptions + { Full = new SemanticTokensCapabilityRequestFull() }; registrationOptions.Range ??= new SemanticTokensCapabilityRequestRange(); @@ -772,7 +824,8 @@ private static SemanticTokensRegistrationOptions RegistrationOptionsFactory(Sema } // Ensure the legend is created properly. - registrationOptions.Legend = new SemanticTokensLegend() { + registrationOptions.Legend = new SemanticTokensLegend + { TokenModifiers = SemanticTokenModifier.Defaults.Join(capability.TokenModifiers, z => z, z => z, (a, _) => a).ToArray(), TokenTypes = SemanticTokenType.Defaults.Join(capability.TokenTypes, z => z, z => z, (a, _) => a).ToArray(), }; @@ -834,7 +887,10 @@ public static ILanguageServerRegistry OnSemanticTokens( private class DelegatingHandlerBase : SemanticTokensHandlerBase { private readonly Func _tokenize; - private readonly Func> _getSemanticTokensDocument; + + private readonly Func> + _getSemanticTokensDocument; + private readonly RegistrationOptionsDelegate _registrationOptionsFactory; public DelegatingHandlerBase( @@ -849,40 +905,54 @@ RegistrationOptionsDelegate _tokenize(builder, identifier, Capability, cancellationToken); + { + return _tokenize(builder, identifier, Capability, cancellationToken); + } - protected override Task GetSemanticTokensDocument(ITextDocumentIdentifierParams @params, CancellationToken cancellationToken) - => _getSemanticTokensDocument(@params, Capability, cancellationToken); + protected override Task GetSemanticTokensDocument( + ITextDocumentIdentifierParams @params, CancellationToken cancellationToken + ) + { + return _getSemanticTokensDocument(@params, Capability, cancellationToken); + } protected internal override SemanticTokensRegistrationOptions CreateRegistrationOptions( SemanticTokensCapability capability, ClientCapabilities clientCapabilities - ) => - _registrationOptionsFactory(capability, clientCapabilities); + ) + { + return _registrationOptionsFactory(capability, clientCapabilities); + } } public static IRequestProgressObservable RequestSemanticTokens( this ITextDocumentLanguageClient mediator, SemanticTokensParams @params, CancellationToken cancellationToken = default - ) => - mediator.ProgressManager.MonitorUntil( + ) + { + return mediator.ProgressManager.MonitorUntil( @params, - (partial, result) => new SemanticTokens { + (partial, result) => new SemanticTokens + { Data = partial.Data, ResultId = result?.ResultId }, - tokens => new SemanticTokensPartialResult(tokens)!, + tokens => new SemanticTokensPartialResult(tokens), cancellationToken ); + } public static IRequestProgressObservable RequestSemanticTokensDelta( this ITextDocumentLanguageClient mediator, SemanticTokensDeltaParams @params, CancellationToken cancellationToken = default - ) => - mediator.ProgressManager.MonitorUntil( - @params, (partial, result) => { + ) + { + return mediator.ProgressManager.MonitorUntil( + @params, (partial, result) => + { if (partial.IsDelta) { return new SemanticTokensFullOrDelta( - new SemanticTokensDelta { + new SemanticTokensDelta + { Edits = partial.Delta!.Edits, ResultId = result?.Delta?.ResultId ?? result?.Full?.ResultId } @@ -892,7 +962,8 @@ protected internal override SemanticTokensRegistrationOptions CreateRegistration if (partial.IsFull) { return new SemanticTokensFullOrDelta( - new SemanticTokens { + new SemanticTokens + { Data = partial.Full!.Data, ResultId = result?.Full?.ResultId ?? result?.Delta?.ResultId } @@ -902,20 +973,24 @@ protected internal override SemanticTokensRegistrationOptions CreateRegistration return new SemanticTokensFullOrDelta(new SemanticTokens()); }, cancellationToken ); + } public static IRequestProgressObservable RequestSemanticTokensRange( this ITextDocumentLanguageClient mediator, SemanticTokensRangeParams @params, CancellationToken cancellationToken = default - ) => - mediator.ProgressManager.MonitorUntil( + ) + { + return mediator.ProgressManager.MonitorUntil( @params, - (partial, result) => new SemanticTokens { + (partial, result) => new SemanticTokens + { Data = partial.Data, ResultId = result?.ResultId }, tokens => new SemanticTokensPartialResult(tokens)!, cancellationToken ); + } } } } diff --git a/src/Protocol/Features/Document/SignatureHelpFeature.cs b/src/Protocol/Features/Document/SignatureHelpFeature.cs index c96fd7352..9076ecba5 100644 --- a/src/Protocol/Features/Document/SignatureHelpFeature.cs +++ b/src/Protocol/Features/Document/SignatureHelpFeature.cs @@ -18,12 +18,11 @@ namespace Models { [Parallel] [Method(TextDocumentNames.SignatureHelp, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(SignatureHelpRegistrationOptions)), Capability(typeof(SignatureHelpCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(SignatureHelpRegistrationOptions))] + [Capability(typeof(SignatureHelpCapability))] public partial record SignatureHelpParams : TextDocumentPositionParams, IWorkDoneProgressParams, IRequest { /// @@ -32,7 +31,7 @@ public partial record SignatureHelpParams : TextDocumentPositionParams, IWorkDon /// /// @since 3.15.0 /// - public SignatureHelpContext Context { get; init; } + public SignatureHelpContext Context { get; init; } = null!; } /// @@ -134,7 +133,7 @@ public record SignatureInformation /// The label of this signature. Will be shown in /// the UI. /// - public string Label { get; init; } + public string Label { get; init; } = null!; /// /// The human-readable doc-comment of this signature. Will be shown @@ -162,7 +161,10 @@ public record SignatureInformation private string DebuggerDisplay => $"{Label}{Documentation?.ToString() ?? ""}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } /// @@ -176,7 +178,7 @@ public record ParameterInformation /// The label of this parameter. Will be shown in /// the UI. /// - public ParameterInformationLabel Label { get; init; } + public ParameterInformationLabel Label { get; init; } = null!; /// /// The human-readable doc-comment of this parameter. Will be shown @@ -188,30 +190,48 @@ public record ParameterInformation private string DebuggerDisplay => $"{Label}{( Documentation != null ? $" {Documentation}" : string.Empty )}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } [JsonConverter(typeof(ParameterInformationLabelConverter))] [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public record ParameterInformationLabel { - public ParameterInformationLabel((int start, int end) range) => Range = range; + public ParameterInformationLabel((int start, int end) range) + { + Range = range; + } - public ParameterInformationLabel(string label) => Label = label; + public ParameterInformationLabel(string label) + { + Label = label; + } public (int start, int end) Range { get; } public bool IsRange => Label == null; public string? Label { get; } public bool IsLabel => Label != null; - public static implicit operator ParameterInformationLabel(string label) => new ParameterInformationLabel(label); + public static implicit operator ParameterInformationLabel(string label) + { + return new ParameterInformationLabel(label); + } - public static implicit operator ParameterInformationLabel((int start, int end) range) => new ParameterInformationLabel(range); + public static implicit operator ParameterInformationLabel((int start, int end) range) + { + return new ParameterInformationLabel(range); + } private string DebuggerDisplay => IsRange ? $"(start: {Range.start}, end: {Range.end})" : IsLabel ? Label! : string.Empty; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } [GenerateRegistrationOptions(nameof(ServerCapabilities.SignatureHelpProvider))] diff --git a/src/Protocol/Features/Document/TextDocumentSyncFeature.cs b/src/Protocol/Features/Document/TextDocumentSyncFeature.cs index 084a25b1d..615df16a0 100644 --- a/src/Protocol/Features/Document/TextDocumentSyncFeature.cs +++ b/src/Protocol/Features/Document/TextDocumentSyncFeature.cs @@ -21,12 +21,11 @@ namespace Models { [Serial] [Method(TextDocumentNames.DidChange, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(TextDocumentChangeRegistrationOptions)), Capability(typeof(SynchronizationCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(TextDocumentChangeRegistrationOptions))] + [Capability(typeof(SynchronizationCapability))] public partial record DidChangeTextDocumentParams : IRequest { /// @@ -34,12 +33,12 @@ public partial record DidChangeTextDocumentParams : IRequest /// to the version after all provided content changes have /// been applied. /// - public OptionalVersionedTextDocumentIdentifier TextDocument { get; init; } + public OptionalVersionedTextDocumentIdentifier TextDocument { get; init; } = null!; /// /// The actual content changes. /// - public Container ContentChanges { get; init; } + public Container ContentChanges { get; init; } = null!; } /// @@ -71,7 +70,7 @@ public record TextDocumentContentChangeEvent /// The length of the range that got replaced. /// /// - /// in the LSP spec + /// in the LSP spec /// [Optional] public int RangeLength { get; init; } @@ -79,7 +78,7 @@ public record TextDocumentContentChangeEvent /// /// The new text of the document. /// - public string Text { get; init; } + public string Text { get; init; } = null!; } public record TextDocumentEdit @@ -87,25 +86,24 @@ public record TextDocumentEdit /// /// The text document to change. /// - public OptionalVersionedTextDocumentIdentifier TextDocument { get; init; } + public OptionalVersionedTextDocumentIdentifier TextDocument { get; init; } = null!; /// /// The edits to be applied. /// /// - /// This can contain both and + /// This can contain both and /// - public TextEditContainer Edits { get; init; } + public TextEditContainer Edits { get; init; } = null!; } [Serial] [Method(TextDocumentNames.DidOpen, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(TextDocumentOpenRegistrationOptions)), Capability(typeof(SynchronizationCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(TextDocumentOpenRegistrationOptions))] + [Capability(typeof(SynchronizationCapability))] public partial class DidOpenTextDocumentParams : IRequest { /// @@ -121,12 +119,11 @@ public partial class TextDocumentOpenRegistrationOptions : ITextDocumentRegistra [Parallel] [Method(TextDocumentNames.DidClose, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(TextDocumentCloseRegistrationOptions)), Capability(typeof(SynchronizationCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(TextDocumentCloseRegistrationOptions))] + [Capability(typeof(SynchronizationCapability))] public partial class DidCloseTextDocumentParams : ITextDocumentIdentifierParams, IRequest { /// @@ -142,12 +139,11 @@ public partial class TextDocumentCloseRegistrationOptions : ITextDocumentRegistr [Serial] [Method(TextDocumentNames.DidSave, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(TextDocumentSaveRegistrationOptions)), Capability(typeof(SynchronizationCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(TextDocumentSaveRegistrationOptions))] + [Capability(typeof(SynchronizationCapability))] public partial class DidSaveTextDocumentParams : ITextDocumentIdentifierParams, IRequest { /// @@ -199,7 +195,7 @@ public TextDocumentSyncRegistrationOptions(TextDocumentSyncKind syncKind) /// public TextDocumentSyncKind Change { get; set; } - class Converter : RegistrationOptionsConverterBase + private class Converter : RegistrationOptionsConverterBase { private readonly IHandlersManager _handlersManager; @@ -210,7 +206,8 @@ public Converter(IHandlersManager handlersManager) public override StaticOptions Convert(TextDocumentSyncRegistrationOptions source) { - return new() { + return new() + { OpenClose = _handlersManager.Descriptors.Any( z => z.HandlerType == typeof(IDidOpenTextDocumentHandler) || z.HandlerType == typeof(IDidCloseTextDocumentHandler) ), @@ -245,7 +242,8 @@ public partial class StaticOptions : ITextDocumentSyncOptions public static implicit operator TextDocumentSaveRegistrationOptions(TextDocumentSyncRegistrationOptions options) { - return new() { + return new() + { DocumentSelector = options.DocumentSelector, IncludeText = options.Save?.Value?.IncludeText == true }; @@ -253,7 +251,8 @@ public static implicit operator TextDocumentSaveRegistrationOptions(TextDocument public static implicit operator TextDocumentChangeRegistrationOptions(TextDocumentSyncRegistrationOptions options) { - return new() { + return new() + { DocumentSelector = options.DocumentSelector, SyncKind = options.Change, }; @@ -261,14 +260,16 @@ public static implicit operator TextDocumentChangeRegistrationOptions(TextDocume public static implicit operator TextDocumentOpenRegistrationOptions(TextDocumentSyncRegistrationOptions options) { - return new() { + return new() + { DocumentSelector = options.DocumentSelector, }; } public static implicit operator TextDocumentCloseRegistrationOptions(TextDocumentSyncRegistrationOptions options) { - return new() { + return new() + { DocumentSelector = options.DocumentSelector, }; } @@ -279,12 +280,11 @@ public static implicit operator TextDocumentCloseRegistrationOptions(TextDocumen /// [Parallel] [Method(TextDocumentNames.WillSave, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(TextDocumenWillSaveRegistrationOptions)), Capability(typeof(SynchronizationCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(TextDocumenWillSaveRegistrationOptions))] + [Capability(typeof(SynchronizationCapability))] public partial class WillSaveTextDocumentParams : IRequest { /// @@ -308,12 +308,11 @@ public partial class TextDocumenWillSaveRegistrationOptions : ITextDocumentRegis /// [Parallel] [Method(TextDocumentNames.WillSaveWaitUntil, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(TextDocumentWillSaveWaitUntilRegistrationOptions)), Capability(typeof(SynchronizationCapability))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(TextDocumentWillSaveWaitUntilRegistrationOptions))] + [Capability(typeof(SynchronizationCapability))] public partial class WillSaveWaitUntilTextDocumentParams : IRequest { /// @@ -376,39 +375,51 @@ public abstract class TextDocumentSyncHandlerBase : ITextDocumentSyncHandler public abstract Task Handle(DidSaveTextDocumentParams request, CancellationToken cancellationToken); public abstract Task Handle(DidCloseTextDocumentParams request, CancellationToken cancellationToken); - private TextDocumentSyncRegistrationOptions? _registrationOptions; - private ClientCapabilities? _clientCapabilities; + protected TextDocumentSyncRegistrationOptions RegistrationOptions { get; private set; } - protected TextDocumentSyncRegistrationOptions RegistrationOptions => _registrationOptions!; - protected ClientCapabilities ClientCapabilities => _clientCapabilities!; + protected ClientCapabilities ClientCapabilities { get; private set; } protected SynchronizationCapability Capability { get; private set; } = default!; - protected abstract TextDocumentSyncRegistrationOptions CreateRegistrationOptions(SynchronizationCapability capability, ClientCapabilities clientCapabilities); + protected abstract TextDocumentSyncRegistrationOptions CreateRegistrationOptions( + SynchronizationCapability capability, ClientCapabilities clientCapabilities + ); private TextDocumentSyncRegistrationOptions AssignRegistrationOptions(SynchronizationCapability capability, ClientCapabilities clientCapabilities) { Capability = capability; - if (_registrationOptions is { }) return _registrationOptions; - _clientCapabilities = clientCapabilities; - return _registrationOptions = CreateRegistrationOptions(capability, clientCapabilities); + if (RegistrationOptions is { }) return RegistrationOptions; + ClientCapabilities = clientCapabilities; + return RegistrationOptions = CreateRegistrationOptions(capability, clientCapabilities); } TextDocumentChangeRegistrationOptions IRegistration.GetRegistrationOptions( SynchronizationCapability capability, ClientCapabilities clientCapabilities - ) => _registrationOptions ?? AssignRegistrationOptions(capability, clientCapabilities); + ) + { + return RegistrationOptions ?? AssignRegistrationOptions(capability, clientCapabilities); + } TextDocumentOpenRegistrationOptions IRegistration.GetRegistrationOptions( SynchronizationCapability capability, ClientCapabilities clientCapabilities - ) => _registrationOptions ?? AssignRegistrationOptions(capability, clientCapabilities); + ) + { + return RegistrationOptions ?? AssignRegistrationOptions(capability, clientCapabilities); + } TextDocumentCloseRegistrationOptions IRegistration.GetRegistrationOptions( SynchronizationCapability capability, ClientCapabilities clientCapabilities - ) => _registrationOptions ?? AssignRegistrationOptions(capability, clientCapabilities); + ) + { + return RegistrationOptions ?? AssignRegistrationOptions(capability, clientCapabilities); + } TextDocumentSaveRegistrationOptions IRegistration.GetRegistrationOptions( SynchronizationCapability capability, ClientCapabilities clientCapabilities - ) => _registrationOptions ?? AssignRegistrationOptions(capability, clientCapabilities); + ) + { + return RegistrationOptions ?? AssignRegistrationOptions(capability, clientCapabilities); + } } @@ -782,10 +793,17 @@ public override async Task Handle(DidCloseTextDocumentParams request, Canc return Unit.Value; } - protected override TextDocumentSyncRegistrationOptions CreateRegistrationOptions(SynchronizationCapability capability, ClientCapabilities clientCapabilities) => - _registrationOptionsFactory(capability, clientCapabilities); + protected override TextDocumentSyncRegistrationOptions CreateRegistrationOptions( + SynchronizationCapability capability, ClientCapabilities clientCapabilities + ) + { + return _registrationOptionsFactory(capability, clientCapabilities); + } - public override TextDocumentAttributes GetTextDocumentAttributes(DocumentUri uri) => _getTextDocumentAttributes.Invoke(uri); + public override TextDocumentAttributes GetTextDocumentAttributes(DocumentUri uri) + { + return _getTextDocumentAttributes.Invoke(uri); + } } } } diff --git a/src/Protocol/Features/Document/TypeDefinitionFeature.cs b/src/Protocol/Features/Document/TypeDefinitionFeature.cs index aee115849..504742323 100644 --- a/src/Protocol/Features/Document/TypeDefinitionFeature.cs +++ b/src/Protocol/Features/Document/TypeDefinitionFeature.cs @@ -12,19 +12,19 @@ namespace Models { [Parallel] [Method(TextDocumentNames.TypeDefinition, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(TypeDefinitionRegistrationOptions)), Capability(typeof(TypeDefinitionCapability))] - public partial record TypeDefinitionParams : TextDocumentPositionParams, IWorkDoneProgressParams, IPartialItemsRequest - { - } + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(TypeDefinitionRegistrationOptions))] + [Capability(typeof(TypeDefinitionCapability))] + public partial record TypeDefinitionParams : TextDocumentPositionParams, IWorkDoneProgressParams, + IPartialItemsRequest; [GenerateRegistrationOptions(nameof(ServerCapabilities.TypeDefinitionProvider))] [RegistrationName(TextDocumentNames.TypeDefinition)] - public partial class TypeDefinitionRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions, IStaticRegistrationOptions { } + public partial class TypeDefinitionRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions, IStaticRegistrationOptions + { + } } namespace Client.Capabilities diff --git a/src/Protocol/Features/FileOperationsFeature.cs b/src/Protocol/Features/FileOperationsFeature.cs index ac255deb4..b9d1b6829 100644 --- a/src/Protocol/Features/FileOperationsFeature.cs +++ b/src/Protocol/Features/FileOperationsFeature.cs @@ -26,7 +26,7 @@ public abstract record FileOperationParams /// /// An array of all files/folders deleted in this operation. /// - public Container Files { get; init; } + public Container Files { get; init; } = null!; } /// @@ -37,110 +37,118 @@ public abstract record FileOperationItem /// /// A file:// URI for the location of the file/folder being created. /// - public Uri Uri { get; init; } + public Uri Uri { get; init; } = null!; } - /// + /// [Parallel] [Method(WorkspaceNames.DidCreateFiles, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(DidCreateFileRegistrationOptions)), Capability(typeof(FileOperationsWorkspaceClientCapabilities))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(DidCreateFileRegistrationOptions))] + [Capability(typeof(FileOperationsWorkspaceClientCapabilities))] public partial record DidCreateFileParams : FileOperationParams, IRequest { - public static implicit operator WillCreateFileParams(DidCreateFileParams @params) => new() { Files = @params.Files }; + public static implicit operator WillCreateFileParams(DidCreateFileParams @params) + { + return new() { Files = @params.Files }; + } } - /// + /// [Parallel] [Method(WorkspaceNames.WillCreateFiles, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(WillCreateFileRegistrationOptions)), Capability(typeof(FileOperationsWorkspaceClientCapabilities))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(WillCreateFileRegistrationOptions))] + [Capability(typeof(FileOperationsWorkspaceClientCapabilities))] public partial record WillCreateFileParams : FileOperationParams, IRequest { - public static implicit operator DidCreateFileParams(WillCreateFileParams @params) => new() { Files = @params.Files }; + public static implicit operator DidCreateFileParams(WillCreateFileParams @params) + { + return new() { Files = @params.Files }; + } } - /// - public partial record FileCreate : FileOperationItem - { - } - /// + /// + public partial record FileCreate : FileOperationItem; + + /// [Parallel] [Method(WorkspaceNames.DidRenameFiles, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(DidRenameFileRegistrationOptions)), Capability(typeof(FileOperationsWorkspaceClientCapabilities))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(DidRenameFileRegistrationOptions))] + [Capability(typeof(FileOperationsWorkspaceClientCapabilities))] public partial record DidRenameFileParams : FileOperationParams, IRequest { - public static implicit operator WillRenameFileParams(DidRenameFileParams @params) => new() { Files = @params.Files }; + public static implicit operator WillRenameFileParams(DidRenameFileParams @params) + { + return new() { Files = @params.Files }; + } } - /// + /// [Parallel] [Method(WorkspaceNames.WillRenameFiles, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(WillRenameFileRegistrationOptions)), Capability(typeof(FileOperationsWorkspaceClientCapabilities))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(WillRenameFileRegistrationOptions))] + [Capability(typeof(FileOperationsWorkspaceClientCapabilities))] public partial record WillRenameFileParams : FileOperationParams, IRequest { - public static implicit operator DidRenameFileParams(WillRenameFileParams @params) => new() { Files = @params.Files }; + public static implicit operator DidRenameFileParams(WillRenameFileParams @params) + { + return new() { Files = @params.Files }; + } } - /// - public partial record FileRename : FileOperationItem - { - } + /// + public partial record FileRename : FileOperationItem; - /// + /// [Parallel] [Method(WorkspaceNames.DidDeleteFiles, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(DidDeleteFileRegistrationOptions)), Capability(typeof(FileOperationsWorkspaceClientCapabilities))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(DidDeleteFileRegistrationOptions))] + [Capability(typeof(FileOperationsWorkspaceClientCapabilities))] public partial record DidDeleteFileParams : FileOperationParams, IRequest { - public static implicit operator WillDeleteFileParams(DidDeleteFileParams @params) => new() { Files = @params.Files }; + public static implicit operator WillDeleteFileParams(DidDeleteFileParams @params) + { + return new() { Files = @params.Files }; + } } - /// + /// [Parallel] [Method(WorkspaceNames.WillDeleteFiles, Direction.ClientToServer)] - [ - GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace"), - GenerateHandlerMethods, - GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(WillDeleteFileRegistrationOptions)), Capability(typeof(FileOperationsWorkspaceClientCapabilities))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] + [RegistrationOptions(typeof(WillDeleteFileRegistrationOptions))] + [Capability(typeof(FileOperationsWorkspaceClientCapabilities))] public partial record WillDeleteFileParams : FileOperationParams, IRequest { - public static implicit operator DidDeleteFileParams(WillDeleteFileParams @params) => new() { Files = @params.Files }; + public static implicit operator DidDeleteFileParams(WillDeleteFileParams @params) + { + return new() { Files = @params.Files }; + } } - /// - public partial record FileDelete : FileOperationItem - { - } + /// + public partial record FileDelete : FileOperationItem; - /// + /// [GenerateRegistrationOptions( - nameof(ServerCapabilities.Workspace), nameof(WorkspaceServerCapabilities.FileOperations), nameof(FileOperationsWorkspaceServerCapabilities.WillCreate) + nameof(ServerCapabilities.Workspace), nameof(WorkspaceServerCapabilities.FileOperations), + nameof(FileOperationsWorkspaceServerCapabilities.WillCreate) )] [RegistrationName(WorkspaceNames.WillCreateFiles)] public partial class WillCreateFileRegistrationOptions : IFileOperationRegistrationOptions @@ -151,9 +159,10 @@ public partial class WillCreateFileRegistrationOptions : IFileOperationRegistrat public Container Filters { get; set; } = new Container(); } - /// + /// [GenerateRegistrationOptions( - nameof(ServerCapabilities.Workspace), nameof(WorkspaceServerCapabilities.FileOperations), nameof(FileOperationsWorkspaceServerCapabilities.DidCreate) + nameof(ServerCapabilities.Workspace), nameof(WorkspaceServerCapabilities.FileOperations), + nameof(FileOperationsWorkspaceServerCapabilities.DidCreate) )] [RegistrationName(WorkspaceNames.DidCreateFiles)] public partial class DidCreateFileRegistrationOptions : IFileOperationRegistrationOptions @@ -164,9 +173,10 @@ public partial class DidCreateFileRegistrationOptions : IFileOperationRegistrati public Container Filters { get; set; } = new Container(); } - /// + /// [GenerateRegistrationOptions( - nameof(ServerCapabilities.Workspace), nameof(WorkspaceServerCapabilities.FileOperations), nameof(FileOperationsWorkspaceServerCapabilities.WillRename) + nameof(ServerCapabilities.Workspace), nameof(WorkspaceServerCapabilities.FileOperations), + nameof(FileOperationsWorkspaceServerCapabilities.WillRename) )] [RegistrationName(WorkspaceNames.WillRenameFiles)] public partial class WillRenameFileRegistrationOptions : IFileOperationRegistrationOptions @@ -177,9 +187,10 @@ public partial class WillRenameFileRegistrationOptions : IFileOperationRegistrat public Container Filters { get; set; } = new Container(); } - /// + /// [GenerateRegistrationOptions( - nameof(ServerCapabilities.Workspace), nameof(WorkspaceServerCapabilities.FileOperations), nameof(FileOperationsWorkspaceServerCapabilities.DidRename) + nameof(ServerCapabilities.Workspace), nameof(WorkspaceServerCapabilities.FileOperations), + nameof(FileOperationsWorkspaceServerCapabilities.DidRename) )] [RegistrationName(WorkspaceNames.DidRenameFiles)] public partial class DidRenameFileRegistrationOptions : IFileOperationRegistrationOptions @@ -190,9 +201,10 @@ public partial class DidRenameFileRegistrationOptions : IFileOperationRegistrati public Container Filters { get; set; } = new Container(); } - /// + /// [GenerateRegistrationOptions( - nameof(ServerCapabilities.Workspace), nameof(WorkspaceServerCapabilities.FileOperations), nameof(FileOperationsWorkspaceServerCapabilities.WillDelete) + nameof(ServerCapabilities.Workspace), nameof(WorkspaceServerCapabilities.FileOperations), + nameof(FileOperationsWorkspaceServerCapabilities.WillDelete) )] [RegistrationName(WorkspaceNames.WillDeleteFiles)] public partial class WillDeleteFileRegistrationOptions : IFileOperationRegistrationOptions @@ -203,9 +215,10 @@ public partial class WillDeleteFileRegistrationOptions : IFileOperationRegistrat public Container Filters { get; set; } = new Container(); } - /// + /// [GenerateRegistrationOptions( - nameof(ServerCapabilities.Workspace), nameof(WorkspaceServerCapabilities.FileOperations), nameof(FileOperationsWorkspaceServerCapabilities.DidDelete) + nameof(ServerCapabilities.Workspace), nameof(WorkspaceServerCapabilities.FileOperations), + nameof(FileOperationsWorkspaceServerCapabilities.DidDelete) )] [RegistrationName(WorkspaceNames.DidDeleteFiles)] public partial class DidDeleteFileRegistrationOptions : IFileOperationRegistrationOptions @@ -216,11 +229,11 @@ public partial class DidDeleteFileRegistrationOptions : IFileOperationRegistrati public Container Filters { get; set; } = new Container(); } - /// + /// /// The options to register for file operations. - /// + /// /// @since 3.16.0 - /// + /// public interface IFileOperationRegistrationOptions { /// @@ -268,12 +281,12 @@ public record FileOperationPattern /// - `?` to match on one character in a path segment /// - `**` to match any number of path segments, including none /// - `{}` to group conditions (e.g. `**​/*.{ts,js}` matches all TypeScript - /// and JavaScript files) + /// and JavaScript files) /// - `[]` to declare a range of characters to match in a path segment - /// (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) + /// (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) /// - `[!...]` to negate a range of characters to match in a path segment - /// (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but - /// not `example.0`) + /// (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but + /// not `example.0`) /// public string Glob { get; init; } diff --git a/src/Protocol/Features/General/InitializeFeature.cs b/src/Protocol/Features/General/InitializeFeature.cs index 0b337fa11..6ee578274 100644 --- a/src/Protocol/Features/General/InitializeFeature.cs +++ b/src/Protocol/Features/General/InitializeFeature.cs @@ -110,10 +110,11 @@ public record InitializeParams : IInitializeParams public string? RootPath { get => RootUri?.GetFileSystemPath(); - init { + init + { if (!string.IsNullOrEmpty(value)) { - RootUri = DocumentUri.FromFileSystemPath(value!); + RootUri = DocumentUri.FromFileSystemPath(value); } } } @@ -195,7 +196,8 @@ internal InitializeParams(IInitializeParams @params, ClientCapabilities [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.General", Name = "LanguageProtocolInitialize")] [GenerateHandlerMethods(typeof(ILanguageServerRegistry))] [GenerateRequestMethods(typeof(ILanguageClient))] - internal partial record InternalInitializeParams : IInitializeParams, IRequest // This is required for generation to work correctly. + internal partial record + InternalInitializeParams : IInitializeParams, IRequest // This is required for generation to work correctly. { /// /// The process Id of the parent process that started @@ -230,7 +232,7 @@ public string? RootPath /// folder is open. If both `rootPath` and `rootUri` are set /// `rootUri` wins. /// - public DocumentUri RootUri { get; init; } + public DocumentUri RootUri { get; init; } = null!; /// /// User provided initialization options. @@ -240,7 +242,7 @@ public string? RootPath /// /// The capabilities provided by the client (editor or tool) /// - public JObject Capabilities { get; init; } + public JObject Capabilities { get; init; } = null!; /// /// The initial trace setting. If omitted trace is disabled ('off'). diff --git a/src/Protocol/Features/General/InitializedFeature.cs b/src/Protocol/Features/General/InitializedFeature.cs index dc16fee70..fdd35713a 100644 --- a/src/Protocol/Features/General/InitializedFeature.cs +++ b/src/Protocol/Features/General/InitializedFeature.cs @@ -14,8 +14,6 @@ namespace Models [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.General", Name = "LanguageProtocolInitialized")] [GenerateHandlerMethods(typeof(ILanguageServerRegistry))] [GenerateRequestMethods(typeof(ILanguageClient))] - public partial record InitializedParams : IRequest - { - } + public partial record InitializedParams : IRequest; } } diff --git a/src/Protocol/Features/ProgressFeature.cs b/src/Protocol/Features/ProgressFeature.cs index 37e3038c0..9e971f13a 100644 --- a/src/Protocol/Features/ProgressFeature.cs +++ b/src/Protocol/Features/ProgressFeature.cs @@ -21,25 +21,29 @@ namespace Models { [Serial] [Method(GeneralNames.Progress, Direction.Bidirectional)] - [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol"), GenerateHandlerMethods, - GenerateRequestMethods(typeof(IGeneralLanguageClient), typeof(ILanguageClient), typeof(IGeneralLanguageServer), typeof(ILanguageServer))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IGeneralLanguageClient), typeof(ILanguageClient), typeof(IGeneralLanguageServer), typeof(ILanguageServer))] public record ProgressParams : IRequest { - public static ProgressParams Create(ProgressToken token, T value, JsonSerializer jsonSerializer) => - new ProgressParams { + public static ProgressParams Create(ProgressToken token, T value, JsonSerializer jsonSerializer) + { + return new ProgressParams + { Token = token, Value = JToken.FromObject(value, jsonSerializer) }; + } /// /// The progress token provided by the client or server. /// - public ProgressToken Token { get; init; } + public ProgressToken Token { get; init; } = null!; /// /// The progress data. /// - public JToken Value { get; init; } + public JToken Value { get; init; } = null!; } [JsonConverter(typeof(ProgressTokenConverter))] @@ -66,7 +70,8 @@ public ProgressToken(string value) public long Long { get => _long ?? 0; - set { + set + { String = null; _long = value; } @@ -77,26 +82,45 @@ public long Long public string? String { get => _string; - set { + set + { _string = value; _long = null; } } - public static implicit operator ProgressToken(long value) => new ProgressToken(value); + public static implicit operator ProgressToken(long value) + { + return new ProgressToken(value); + } - public static implicit operator ProgressToken(string value) => new ProgressToken(value); + public static implicit operator ProgressToken(string value) + { + return new ProgressToken(value); + } - public ProgressParams Create(T value, JsonSerializer jsonSerializer) => ProgressParams.Create(this, value, jsonSerializer); + public ProgressParams Create(T value, JsonSerializer jsonSerializer) + { + return ProgressParams.Create(this, value, jsonSerializer); + } - public bool Equals(long other) => IsLong && Long == other; + public bool Equals(long other) + { + return IsLong && Long == other; + } - public bool Equals(string other) => IsString && String == other; + public bool Equals(string other) + { + return IsString && String == other; + } private string DebuggerDisplay => IsString ? String! : IsLong ? Long.ToString() : ""; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } } @@ -125,7 +149,8 @@ public static IRequestProgressObservable, TResponse> RequestP return requestRouter.ProgressManager.MonitorUntil(@params, factory, cancellationToken); } - private static readonly PropertyInfo PartialResultTokenProperty = typeof(IPartialResultParams).GetProperty(nameof(IPartialResultParams.PartialResultToken))!; + private static readonly PropertyInfo PartialResultTokenProperty = + typeof(IPartialResultParams).GetProperty(nameof(IPartialResultParams.PartialResultToken))!; internal static ProgressToken SetPartialResultToken(this IPartialResultParams @params, ProgressToken? progressToken = null) { diff --git a/src/Protocol/Features/Window/LogMessageFeature.cs b/src/Protocol/Features/Window/LogMessageFeature.cs index bd2f7539f..2fe2edfcd 100644 --- a/src/Protocol/Features/Window/LogMessageFeature.cs +++ b/src/Protocol/Features/Window/LogMessageFeature.cs @@ -11,7 +11,9 @@ namespace Models { [Parallel] [Method(WindowNames.LogMessage, Direction.ServerToClient)] - [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Window"), GenerateHandlerMethods, GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Window")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] public record LogMessageParams : IRequest { /// @@ -22,7 +24,7 @@ public record LogMessageParams : IRequest /// /// The actual message /// - public string Message { get; init; } + public string Message { get; init; } = null!; } } @@ -30,32 +32,55 @@ namespace Window { public static partial class LogMessageExtensions { - public static void Log(this ILanguageServer mediator, LogMessageParams @params) => mediator.SendNotification(@params); + public static void Log(this ILanguageServer mediator, LogMessageParams @params) + { + mediator.SendNotification(@params); + } - public static void LogError(this ILanguageServer mediator, string message) => + public static void LogError(this ILanguageServer mediator, string message) + { mediator.SendNotification(new LogMessageParams { Type = MessageType.Error, Message = message }); + } - public static void Log(this ILanguageServer mediator, string message) => mediator.SendNotification(new LogMessageParams { Type = MessageType.Log, Message = message }); + public static void Log(this ILanguageServer mediator, string message) + { + mediator.SendNotification(new LogMessageParams { Type = MessageType.Log, Message = message }); + } - public static void LogWarning(this ILanguageServer mediator, string message) => + public static void LogWarning(this ILanguageServer mediator, string message) + { mediator.SendNotification(new LogMessageParams { Type = MessageType.Warning, Message = message }); + } - public static void LogInfo(this ILanguageServer mediator, string message) => + public static void LogInfo(this ILanguageServer mediator, string message) + { mediator.SendNotification(new LogMessageParams { Type = MessageType.Info, Message = message }); + } - public static void Log(this IWindowLanguageServer mediator, LogMessageParams @params) => mediator.SendNotification(@params); + public static void Log(this IWindowLanguageServer mediator, LogMessageParams @params) + { + mediator.SendNotification(@params); + } - public static void LogError(this IWindowLanguageServer mediator, string message) => + public static void LogError(this IWindowLanguageServer mediator, string message) + { mediator.SendNotification(new LogMessageParams { Type = MessageType.Error, Message = message }); + } - public static void Log(this IWindowLanguageServer mediator, string message) => + public static void Log(this IWindowLanguageServer mediator, string message) + { mediator.SendNotification(new LogMessageParams { Type = MessageType.Log, Message = message }); + } - public static void LogWarning(this IWindowLanguageServer mediator, string message) => + public static void LogWarning(this IWindowLanguageServer mediator, string message) + { mediator.SendNotification(new LogMessageParams { Type = MessageType.Warning, Message = message }); + } - public static void LogInfo(this IWindowLanguageServer mediator, string message) => + public static void LogInfo(this IWindowLanguageServer mediator, string message) + { mediator.SendNotification(new LogMessageParams { Type = MessageType.Info, Message = message }); + } } } } diff --git a/src/Protocol/Features/Window/ShowDocumentRequestFeature.cs b/src/Protocol/Features/Window/ShowDocumentRequestFeature.cs index 5872696d3..7a3ed66f9 100644 --- a/src/Protocol/Features/Window/ShowDocumentRequestFeature.cs +++ b/src/Protocol/Features/Window/ShowDocumentRequestFeature.cs @@ -9,7 +9,6 @@ // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.LanguageServer.Protocol { - namespace Models { /// @@ -19,14 +18,16 @@ namespace Models /// [Parallel] [Method(WindowNames.ShowDocument, Direction.ServerToClient)] - [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Window"), GenerateHandlerMethods, GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Window")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] [Capability(typeof(ShowDocumentClientCapabilities))] public record ShowDocumentParams : IRequest { /// /// The document uri to show. /// - public DocumentUri Uri { get; init; } + public DocumentUri Uri { get; init; } = null!; /// /// Indicates to show the resource in an external program. @@ -77,7 +78,7 @@ namespace Client.Capabilities /// @since 3.16.0 /// [CapabilityKey(nameof(ClientCapabilities.Window), nameof(WindowClientCapabilities.ShowDocument))] - public class ShowDocumentClientCapabilities: ICapability + public class ShowDocumentClientCapabilities : ICapability { /// /// Capabilities specific to the `MessageActionItem` type. diff --git a/src/Protocol/Features/Window/ShowMessageFeature.cs b/src/Protocol/Features/Window/ShowMessageFeature.cs index 46f302731..f116c56dd 100644 --- a/src/Protocol/Features/Window/ShowMessageFeature.cs +++ b/src/Protocol/Features/Window/ShowMessageFeature.cs @@ -7,8 +7,6 @@ // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.LanguageServer.Protocol { - - namespace Models { /// @@ -16,7 +14,9 @@ namespace Models /// [Parallel] [Method(WindowNames.ShowMessage, Direction.ServerToClient)] - [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Window"), GenerateHandlerMethods, GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Window")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] public record ShowMessageParams : IRequest { /// @@ -27,7 +27,7 @@ public record ShowMessageParams : IRequest /// /// The actual message. /// - public string Message { get; init; } + public string Message { get; init; } = null!; } } @@ -35,29 +35,55 @@ namespace Window { public static partial class ShowMessageExtensions { - public static void Show(this ILanguageServer mediator, ShowMessageParams @params) => mediator.SendNotification(@params); + public static void Show(this ILanguageServer mediator, ShowMessageParams @params) + { + mediator.SendNotification(@params); + } - public static void ShowError(this ILanguageServer mediator, string message) => mediator.SendNotification(new ShowMessageParams { Type = MessageType.Error, Message = message }); + public static void ShowError(this ILanguageServer mediator, string message) + { + mediator.SendNotification(new ShowMessageParams { Type = MessageType.Error, Message = message }); + } - public static void Show(this ILanguageServer mediator, string message) => mediator.SendNotification(new ShowMessageParams { Type = MessageType.Log, Message = message }); + public static void Show(this ILanguageServer mediator, string message) + { + mediator.SendNotification(new ShowMessageParams { Type = MessageType.Log, Message = message }); + } - public static void ShowWarning(this ILanguageServer mediator, string message) => + public static void ShowWarning(this ILanguageServer mediator, string message) + { mediator.SendNotification(new ShowMessageParams { Type = MessageType.Warning, Message = message }); + } - public static void ShowInfo(this ILanguageServer mediator, string message) => mediator.SendNotification(new ShowMessageParams { Type = MessageType.Info, Message = message }); + public static void ShowInfo(this ILanguageServer mediator, string message) + { + mediator.SendNotification(new ShowMessageParams { Type = MessageType.Info, Message = message }); + } - public static void Show(this IWindowLanguageServer mediator, ShowMessageParams @params) => mediator.SendNotification(@params); + public static void Show(this IWindowLanguageServer mediator, ShowMessageParams @params) + { + mediator.SendNotification(@params); + } - public static void ShowError(this IWindowLanguageServer mediator, string message) => + public static void ShowError(this IWindowLanguageServer mediator, string message) + { mediator.SendNotification(new ShowMessageParams { Type = MessageType.Error, Message = message }); + } - public static void Show(this IWindowLanguageServer mediator, string message) => mediator.SendNotification(new ShowMessageParams { Type = MessageType.Log, Message = message }); + public static void Show(this IWindowLanguageServer mediator, string message) + { + mediator.SendNotification(new ShowMessageParams { Type = MessageType.Log, Message = message }); + } - public static void ShowWarning(this IWindowLanguageServer mediator, string message) => + public static void ShowWarning(this IWindowLanguageServer mediator, string message) + { mediator.SendNotification(new ShowMessageParams { Type = MessageType.Warning, Message = message }); + } - public static void ShowInfo(this IWindowLanguageServer mediator, string message) => + public static void ShowInfo(this IWindowLanguageServer mediator, string message) + { mediator.SendNotification(new ShowMessageParams { Type = MessageType.Info, Message = message }); + } } } } diff --git a/src/Protocol/Features/Window/ShowMessageRequestFeature.cs b/src/Protocol/Features/Window/ShowMessageRequestFeature.cs index d3ca50f7e..d68c6aa64 100644 --- a/src/Protocol/Features/Window/ShowMessageRequestFeature.cs +++ b/src/Protocol/Features/Window/ShowMessageRequestFeature.cs @@ -12,17 +12,18 @@ // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.LanguageServer.Protocol { - - namespace Models { /// - /// The show message request is sent from a server to a client to ask the client to display a particular message in the user interface. In addition to the show message notification + /// The show message request is sent from a server to a client to ask the client to display a particular message in the user interface. In addition to the show + /// message notification /// the request allows to pass actions and to wait for an answer from the client. /// [Parallel] [Method(WindowNames.ShowMessageRequest, Direction.ServerToClient)] - [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Window"), GenerateHandlerMethods, GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] + [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Window")] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] public record ShowMessageRequestParams : IRequest { /// @@ -33,7 +34,7 @@ public record ShowMessageRequestParams : IRequest /// /// The actual message /// - public string Message { get; init; } + public string Message { get; init; } = null!; /// /// The message action items to present. @@ -48,10 +49,10 @@ public record MessageActionItem /// /// A short title like 'Retry', 'Open Log' etc. /// - public string Title { get; init; } + public string Title { get; init; } = null!; /// - /// Extension data that may contain additional properties based on + /// Extension data that may contain additional properties based on /// [JsonExtensionData] public IDictionary ExtensionData { get; init; } = new Dictionary(); @@ -59,7 +60,10 @@ public record MessageActionItem private string DebuggerDisplay => Title; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } } @@ -79,6 +83,7 @@ public class ShowMessageRequestClientCapabilities [Optional] public ShowMessageRequestMessageActionItemClientCapabilities? MessageActionItem { get; set; } } + public class ShowMessageRequestMessageActionItemClientCapabilities { /// @@ -93,6 +98,5 @@ public class ShowMessageRequestMessageActionItemClientCapabilities namespace Window { - } } diff --git a/src/Protocol/Features/Window/WorkDoneProgressFeature.cs b/src/Protocol/Features/Window/WorkDoneProgressFeature.cs index d53fc071c..f99bb1bd6 100644 --- a/src/Protocol/Features/Window/WorkDoneProgressFeature.cs +++ b/src/Protocol/Features/Window/WorkDoneProgressFeature.cs @@ -87,7 +87,7 @@ public WorkDoneProgressBegin() : base(WorkDoneProgressKind.Begin) /// /// Examples: "Indexing" or "Linking dependencies". /// - public string Title { get; init; } + public string Title { get; init; } = null!; /// /// Controls if a cancel button should show to allow the user to cancel the diff --git a/src/Protocol/Features/Workspace/WorkspaceFoldersFeature.cs b/src/Protocol/Features/Workspace/WorkspaceFoldersFeature.cs index 9e27d2bae..13b49b0df 100644 --- a/src/Protocol/Features/Workspace/WorkspaceFoldersFeature.cs +++ b/src/Protocol/Features/Workspace/WorkspaceFoldersFeature.cs @@ -26,7 +26,7 @@ public partial record DidChangeWorkspaceFoldersParams : IRequest /// /// The actual workspace folder change event. /// - public WorkspaceFoldersChangeEvent Event { get; init; } + public WorkspaceFoldersChangeEvent Event { get; init; } = null!; } /// @@ -63,12 +63,12 @@ public partial record WorkspaceFolder /// /// The associated URI for this workspace folder. /// - public DocumentUri Uri { get; init; } + public DocumentUri Uri { get; init; } = null!; /// /// The name of the workspace folder. Defaults to the uri's basename. /// - public string Name { get; init; } + public string Name { get; init; } = null!; private string DebuggerDisplay => $"{Name} ({Uri})"; diff --git a/src/Protocol/LanguageProtocolProxy.cs b/src/Protocol/LanguageProtocolProxy.cs index 17402ca00..df5ca6584 100644 --- a/src/Protocol/LanguageProtocolProxy.cs +++ b/src/Protocol/LanguageProtocolProxy.cs @@ -18,7 +18,8 @@ internal abstract class LanguageProtocolProxy : ILanguageProtocolProxy private readonly ILanguageProtocolSettings _languageProtocolSettings; public LanguageProtocolProxy( - IResponseRouter requestRouter, IResolverContext resolverContext, IProgressManager progressManager, ILanguageProtocolSettings languageProtocolSettings + IResponseRouter requestRouter, IResolverContext resolverContext, IProgressManager progressManager, + ILanguageProtocolSettings languageProtocolSettings ) { ProgressManager = progressManager; @@ -32,20 +33,44 @@ public LanguageProtocolProxy( public InitializeResult ServerSettings => _languageProtocolSettings.ServerSettings; - public void SendNotification(string method) => _responseRouter.SendNotification(method); + public void SendNotification(string method) + { + _responseRouter.SendNotification(method); + } - public void SendNotification(string method, T @params) => _responseRouter.SendNotification(method, @params); + public void SendNotification(string method, T @params) + { + _responseRouter.SendNotification(method, @params); + } - public void SendNotification(IRequest request) => _responseRouter.SendNotification(request); + public void SendNotification(IRequest request) + { + _responseRouter.SendNotification(request); + } - public IResponseRouterReturns SendRequest(string method, T @params) => _responseRouter.SendRequest(method, @params); + public IResponseRouterReturns SendRequest(string method, T @params) + { + return _responseRouter.SendRequest(method, @params); + } - public IResponseRouterReturns SendRequest(string method) => _responseRouter.SendRequest(method); + public IResponseRouterReturns SendRequest(string method) + { + return _responseRouter.SendRequest(method); + } + + public Task SendRequest(IRequest request, CancellationToken cancellationToken) + { + return _responseRouter.SendRequest(request, cancellationToken); + } - public Task SendRequest(IRequest request, CancellationToken cancellationToken) => _responseRouter.SendRequest(request, cancellationToken); + bool IResponseRouter.TryGetRequest(long id, [NotNullWhen(true)] out string? method, [NotNullWhen(true)] out TaskCompletionSource? pendingTask) + { + return _responseRouter.TryGetRequest(id, out method, out pendingTask); + } - bool IResponseRouter.TryGetRequest(long id, [NotNullWhen(true)] out string method, [NotNullWhen(true)]out TaskCompletionSource pendingTask) => - _responseRouter.TryGetRequest(id, out method, out pendingTask); - object IServiceProvider.GetService(Type serviceType) => ResolverContext.GetService(serviceType); + object IServiceProvider.GetService(Type serviceType) + { + return ResolverContext.GetService(serviceType); + } } } diff --git a/src/Protocol/LanguageProtocolRpcOptionsBase.cs b/src/Protocol/LanguageProtocolRpcOptionsBase.cs index 9ad85e0d9..6f5339b15 100644 --- a/src/Protocol/LanguageProtocolRpcOptionsBase.cs +++ b/src/Protocol/LanguageProtocolRpcOptionsBase.cs @@ -6,7 +6,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using ISerializer = OmniSharp.Extensions.JsonRpc.ISerializer; namespace OmniSharp.Extensions.LanguageServer.Protocol { diff --git a/src/Protocol/Models/ClientInfo.cs b/src/Protocol/Models/ClientInfo.cs index 9e7624689..debce3189 100644 --- a/src/Protocol/Models/ClientInfo.cs +++ b/src/Protocol/Models/ClientInfo.cs @@ -14,7 +14,7 @@ public record ClientInfo /// /// The name of the client as defined by the client. /// - public string Name { get; init; } + public string Name { get; init; } = null!; /// /// The client's version as defined by the client. @@ -25,6 +25,9 @@ public record ClientInfo private string DebuggerDisplay => string.IsNullOrWhiteSpace(Version) ? Name : $"{Name} ({Version})"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } } diff --git a/src/Protocol/Models/Command.cs b/src/Protocol/Models/Command.cs index 2b4221c3c..b21328eb5 100644 --- a/src/Protocol/Models/Command.cs +++ b/src/Protocol/Models/Command.cs @@ -12,13 +12,13 @@ public record Command /// /// Title of the command, like `save`. /// - public string Title { get; init; } + public string Title { get; init; } = null!; /// /// The identifier of the actual command handler. /// [JsonProperty("command")] - public string Name { get; init; } + public string Name { get; init; } = null!; /// /// Arguments that the command handler should be @@ -30,9 +30,19 @@ public record Command private string DebuggerDisplay => $"{Title}{( string.IsNullOrWhiteSpace(Name) ? "" : $" {Name}" )}{( Arguments == null ? "" : string.Join(", ", Arguments.Select(z => z.ToString().Trim('"'))) )}"; - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } - public Command WithArguments(params object[] args) => this with { Arguments = JArray.FromObject(args) }; - public static Command Create(string name, params object[] args) => new() { Name = name, Arguments = JArray.FromObject(args) }; + public Command WithArguments(params object[] args) + { + return this with { Arguments = JArray.FromObject(args) }; + } + + public static Command Create(string name, params object[] args) + { + return new() { Name = name, Arguments = JArray.FromObject(args) }; + } } } diff --git a/src/Protocol/Models/CreateFile.cs b/src/Protocol/Models/CreateFile.cs index 8f4340478..4ddfce1cc 100644 --- a/src/Protocol/Models/CreateFile.cs +++ b/src/Protocol/Models/CreateFile.cs @@ -15,7 +15,7 @@ public record CreateFile : IFile /// /// The resource to create. /// - public DocumentUri Uri { get; init; } + public DocumentUri Uri { get; init; } = null!; /// /// Additional Options diff --git a/src/Protocol/Models/DeleteFile.cs b/src/Protocol/Models/DeleteFile.cs index 0ced6d278..5a9438caf 100644 --- a/src/Protocol/Models/DeleteFile.cs +++ b/src/Protocol/Models/DeleteFile.cs @@ -15,7 +15,7 @@ public record DeleteFile : IFile /// /// The file to delete. /// - public DocumentUri Uri { get; init; } + public DocumentUri Uri { get; init; } = null!; /// /// Delete Options. diff --git a/src/Protocol/Models/Diagnostic.cs b/src/Protocol/Models/Diagnostic.cs index 1c546008d..b8bac7195 100644 --- a/src/Protocol/Models/Diagnostic.cs +++ b/src/Protocol/Models/Diagnostic.cs @@ -16,7 +16,7 @@ public partial record Diagnostic : ICanHaveData /// /// The range at which the message applies. /// - public Range Range { get; init; } + public Range Range { get; init; } = null!; /// /// The diagnostic's severity. Can be omitted. If omitted it is up to the @@ -49,7 +49,7 @@ public partial record Diagnostic : ICanHaveData /// /// The diagnostic's message. /// - public string Message { get; init; } + public string Message { get; init; } = null!; /// /// Additional metadata about the diagnostic. @@ -97,17 +97,29 @@ public DiagnosticCode(string value) } public bool IsLong => String == null; - public long Long { get; } + public long Long { get; } public bool IsString => String != null; - public string? String { get; } + public string? String { get; } - public static implicit operator DiagnosticCode(long value) => new DiagnosticCode(value); + public static implicit operator DiagnosticCode(long value) + { + return new DiagnosticCode(value); + } - public static implicit operator DiagnosticCode(string value) => new DiagnosticCode(value); + public static implicit operator DiagnosticCode(string value) + { + return new DiagnosticCode(value); + } - public static implicit operator long(DiagnosticCode value) => value.IsLong ? value.Long : 0; + public static implicit operator long(DiagnosticCode value) + { + return value.IsLong ? value.Long : 0; + } - public static implicit operator string?(DiagnosticCode value) => value.IsString ? value.String : null; + public static implicit operator string?(DiagnosticCode value) + { + return value.IsString ? value.String : null; + } } [JsonConverter(typeof(NumberEnumConverter))] @@ -168,7 +180,7 @@ public record CodeDescription /// /// An URI to open with more information about the diagnostic error. /// - public Uri Href { get; init; } + public Uri Href { get; init; } = null!; } /// @@ -181,11 +193,11 @@ public record DiagnosticRelatedInformation /// /// The location of this related diagnostic information. /// - public Location Location { get; init; } + public Location Location { get; init; } = null!; /// /// The message of this related diagnostic information. /// - public string Message { get; init; } + public string Message { get; init; } = null!; } } diff --git a/src/Protocol/Models/FileEvent.cs b/src/Protocol/Models/FileEvent.cs index 5b96342d8..9d9f7a413 100644 --- a/src/Protocol/Models/FileEvent.cs +++ b/src/Protocol/Models/FileEvent.cs @@ -11,7 +11,7 @@ public record FileEvent /// /// The file's URI. /// - public DocumentUri Uri { get; init; } + public DocumentUri Uri { get; init; } = null!; /// /// The change type. @@ -21,6 +21,9 @@ public record FileEvent private string DebuggerDisplay => $"[{Type}] {Uri}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } } diff --git a/src/Protocol/Models/FileSystemWatcher.cs b/src/Protocol/Models/FileSystemWatcher.cs index 22cc7ef76..96ca17de4 100644 --- a/src/Protocol/Models/FileSystemWatcher.cs +++ b/src/Protocol/Models/FileSystemWatcher.cs @@ -16,7 +16,7 @@ public record FileSystemWatcher /// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) /// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) /// - public string GlobPattern { get; init; } + public string GlobPattern { get; init; } = null!; /// /// The kind of events of interest. If omitted it defaults @@ -28,6 +28,9 @@ public record FileSystemWatcher private string DebuggerDisplay => $"[{Kind}] {GlobPattern}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } } diff --git a/src/Protocol/Models/Location.cs b/src/Protocol/Models/Location.cs index d5729823b..29814a3dd 100644 --- a/src/Protocol/Models/Location.cs +++ b/src/Protocol/Models/Location.cs @@ -10,16 +10,19 @@ public record Location /// /// The uri of the document /// - public DocumentUri Uri { get; init; } + public DocumentUri Uri { get; init; } = null!; /// /// The range in side the document given by the uri /// - public Range Range { get; init; } + public Range Range { get; init; } = null!; private string DebuggerDisplay => $"{{{Range} {Uri}}}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } } diff --git a/src/Protocol/Models/LocationLink.cs b/src/Protocol/Models/LocationLink.cs index f1cb745e7..506b4a7da 100644 --- a/src/Protocol/Models/LocationLink.cs +++ b/src/Protocol/Models/LocationLink.cs @@ -16,19 +16,19 @@ public record LocationLink /// /// The target resource identifier of this link. /// - public DocumentUri TargetUri { get; init; } + public DocumentUri TargetUri { get; init; } = null!; /// /// The full target range of this link. If the target for example is a symbol then target range is the /// range enclosing this symbol not including leading/trailing whitespace but everything else /// like comments. This information is typically used to highlight the range in the editor. /// - public Range TargetRange { get; init; } + public Range TargetRange { get; init; } = null!; /// /// The range that should be selected and revealed when this link is being followed, e.g the name of a function. /// Must be contained by the the `targetRange`. See also `DocumentSymbol#range` /// - public Range TargetSelectionRange { get; init; } + public Range TargetSelectionRange { get; init; } = null!; } } diff --git a/src/Protocol/Models/MarkupContent.cs b/src/Protocol/Models/MarkupContent.cs index c59da7c41..95d0043a3 100644 --- a/src/Protocol/Models/MarkupContent.cs +++ b/src/Protocol/Models/MarkupContent.cs @@ -37,11 +37,14 @@ public record MarkupContent /// /// The content itself /// - public string Value { get; init; } + public string Value { get; init; } = null!; private string DebuggerDisplay => $"[{Kind}] {Value}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } } diff --git a/src/Protocol/Models/Range.cs b/src/Protocol/Models/Range.cs index 4875704ac..d0816fbf8 100644 --- a/src/Protocol/Models/Range.cs +++ b/src/Protocol/Models/Range.cs @@ -21,16 +21,22 @@ public Range(int startLine, int startCharacter, int endLine, int endCharacter) /// /// The range's start position. /// - public Position Start { get; init; } + public Position Start { get; init; } = null!; /// /// The range's end position. /// - public Position End { get; init; } + public Position End { get; init; } = null!; - public static implicit operator Range((Position start, Position end) value) => new Range(value.start, value.end); + public static implicit operator Range((Position start, Position end) value) + { + return new Range(value.start, value.end); + } /// - public override string ToString() => $"[start: ({Start?.Line}, {Start?.Character}), end: ({End?.Line}, {End?.Character})]"; + public override string ToString() + { + return $"[start: ({Start?.Line}, {Start?.Character}), end: ({End?.Line}, {End?.Character})]"; + } } } diff --git a/src/Protocol/Models/RenameFile.cs b/src/Protocol/Models/RenameFile.cs index 3503b0377..4964dd22a 100644 --- a/src/Protocol/Models/RenameFile.cs +++ b/src/Protocol/Models/RenameFile.cs @@ -15,12 +15,12 @@ public record RenameFile : IFile /// /// The old (existing) location. /// - public DocumentUri OldUri { get; init; } + public DocumentUri OldUri { get; init; } = null!; /// /// The new location. /// - public DocumentUri NewUri { get; init; } + public DocumentUri NewUri { get; init; } = null!; /// /// Rename Options. diff --git a/src/Protocol/Models/ServerInfo.cs b/src/Protocol/Models/ServerInfo.cs index 8e1ecb1c8..c263e32cd 100644 --- a/src/Protocol/Models/ServerInfo.cs +++ b/src/Protocol/Models/ServerInfo.cs @@ -14,7 +14,7 @@ public record ServerInfo /// /// The name of the server as defined by the server. /// - public string Name { get; init; } + public string Name { get; init; } = null!; /// /// The servers's version as defined by the server. @@ -25,6 +25,9 @@ public record ServerInfo private string DebuggerDisplay => string.IsNullOrWhiteSpace(Version) ? Name : $"{Name} ({Version})"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } } diff --git a/src/Protocol/Models/TextDocumentIdentifier.cs b/src/Protocol/Models/TextDocumentIdentifier.cs index fa0d92cc7..8f071be02 100644 --- a/src/Protocol/Models/TextDocumentIdentifier.cs +++ b/src/Protocol/Models/TextDocumentIdentifier.cs @@ -5,23 +5,37 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public record TextDocumentIdentifier { - public TextDocumentIdentifier() { } + public TextDocumentIdentifier() + { + } - public TextDocumentIdentifier(DocumentUri uri) => Uri = uri; + public TextDocumentIdentifier(DocumentUri uri) + { + Uri = uri; + } /// /// The text document's URI. /// - public DocumentUri Uri { get; init; } + public DocumentUri Uri { get; init; } = null!; - public static implicit operator TextDocumentIdentifier(DocumentUri uri) => new TextDocumentIdentifier { Uri = uri }; + public static implicit operator TextDocumentIdentifier(DocumentUri uri) + { + return new TextDocumentIdentifier { Uri = uri }; + } - public static implicit operator TextDocumentIdentifier(string uri) => new TextDocumentIdentifier { Uri = uri }; + public static implicit operator TextDocumentIdentifier(string uri) + { + return new TextDocumentIdentifier { Uri = uri }; + } // ReSharper disable once ConstantConditionalAccessQualifier private string DebuggerDisplay => Uri?.ToString() ?? string.Empty; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } } diff --git a/src/Protocol/Models/TextDocumentItem.cs b/src/Protocol/Models/TextDocumentItem.cs index e3d04bda8..0a51cedf3 100644 --- a/src/Protocol/Models/TextDocumentItem.cs +++ b/src/Protocol/Models/TextDocumentItem.cs @@ -8,7 +8,7 @@ public record TextDocumentItem : TextDocumentIdentifier /// /// The text document's language identifier. /// - public string LanguageId { get; init; } + public string LanguageId { get; init; } = null!; /// /// The version number of this document (it will strictly increase after each @@ -19,11 +19,14 @@ public record TextDocumentItem : TextDocumentIdentifier /// /// The content of the opened text document. /// - public string Text { get; init; } + public string Text { get; init; } = null!; private string DebuggerDisplay => $"({LanguageId}@{Version}) {Uri}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } } diff --git a/src/Protocol/Models/TextDocumentPositionParams.cs b/src/Protocol/Models/TextDocumentPositionParams.cs index deef59a09..0d3c6eb26 100644 --- a/src/Protocol/Models/TextDocumentPositionParams.cs +++ b/src/Protocol/Models/TextDocumentPositionParams.cs @@ -5,11 +5,11 @@ public record TextDocumentPositionParams : ITextDocumentIdentifierParams /// /// The text document. /// - public TextDocumentIdentifier TextDocument { get; init; } + public TextDocumentIdentifier TextDocument { get; init; } = null!; /// /// The position inside the text document. /// - public Position Position { get; init; } + public Position Position { get; init; } = null!; } } diff --git a/src/Protocol/Models/TextEdit.cs b/src/Protocol/Models/TextEdit.cs index 8ce7dbbca..4b6ac9fff 100644 --- a/src/Protocol/Models/TextEdit.cs +++ b/src/Protocol/Models/TextEdit.cs @@ -15,18 +15,22 @@ public record TextEdit /// The range of the text document to be manipulated. To insert /// text into a document create a range where start === end. /// - public Range Range { get; init; } + public Range Range { get; init; } = null!; /// /// The string to be inserted. For delete operations use an /// empty string. /// - public string NewText { get; init; } + public string NewText { get; init; } = null!; - private string DebuggerDisplay => $"{Range} {( string.IsNullOrWhiteSpace(NewText) ? string.Empty : NewText.Length > 30 ? NewText.Substring(0, 30) : NewText )}"; + private string DebuggerDisplay => + $"{Range} {( string.IsNullOrWhiteSpace(NewText) ? string.Empty : NewText.Length > 30 ? NewText.Substring(0, 30) : NewText )}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } /// @@ -40,23 +44,26 @@ public record InsertReplaceEdit /// /// The string to be inserted. /// - public string NewText { get; init; } + public string NewText { get; init; } = null!; /// /// The range if the insert is requested /// - public Range Insert { get; init; } + public Range Insert { get; init; } = null!; /// /// The range if the replace is requested. /// - public Range Replace { get; init; } + public Range Replace { get; init; } = null!; private string DebuggerDisplay => $"{Insert} / {Replace} {( string.IsNullOrWhiteSpace(NewText) ? string.Empty : NewText.Length > 30 ? NewText.Substring(0, 30) : NewText )}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } [JsonConverter(typeof(TextEditOrInsertReplaceEditConverter))] @@ -84,7 +91,8 @@ public TextEditOrInsertReplaceEdit(InsertReplaceEdit value) public InsertReplaceEdit? InsertReplaceEdit { get => _insertReplaceEdit; - set { + set + { _insertReplaceEdit = value; _textEdit = null; } @@ -95,7 +103,8 @@ public InsertReplaceEdit? InsertReplaceEdit public TextEdit? TextEdit { get => _textEdit; - set { + set + { _insertReplaceEdit = default; _textEdit = value; } @@ -103,23 +112,41 @@ public TextEdit? TextEdit public object? RawValue { - get { + get + { if (IsTextEdit) return TextEdit!; if (IsInsertReplaceEdit) return InsertReplaceEdit!; return default; } } - public static TextEditOrInsertReplaceEdit From(TextEdit value) => new(value); - public static implicit operator TextEditOrInsertReplaceEdit(TextEdit value) => new(value); + public static TextEditOrInsertReplaceEdit From(TextEdit value) + { + return new(value); + } + + public static implicit operator TextEditOrInsertReplaceEdit(TextEdit value) + { + return new(value); + } - public static TextEditOrInsertReplaceEdit From(InsertReplaceEdit value) => new(value); - public static implicit operator TextEditOrInsertReplaceEdit(InsertReplaceEdit value) => new(value); + public static TextEditOrInsertReplaceEdit From(InsertReplaceEdit value) + { + return new(value); + } + + public static implicit operator TextEditOrInsertReplaceEdit(InsertReplaceEdit value) + { + return new(value); + } private string DebuggerDisplay => $"{( IsInsertReplaceEdit ? $"insert: {InsertReplaceEdit}" : IsTextEdit ? $"edit: {TextEdit}" : "..." )}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } /// @@ -133,7 +160,7 @@ public record ChangeAnnotation /// A human-readable string describing the actual change. The string /// is rendered prominent in the user interface. /// - public string Label { get; init; } + public string Label { get; init; } = null!; /// /// A flag which indicates that user confirmation is needed @@ -157,11 +184,17 @@ public record ChangeAnnotationIdentifier /// /// @since 3.16.0 /// - public string Identifier { get; init; } + public string Identifier { get; init; } = null!; - public static implicit operator string(ChangeAnnotationIdentifier identifier) => identifier.Identifier; + public static implicit operator string(ChangeAnnotationIdentifier identifier) + { + return identifier.Identifier; + } - public static implicit operator ChangeAnnotationIdentifier(string identifier) => new() { Identifier = identifier }; + public static implicit operator ChangeAnnotationIdentifier(string identifier) + { + return new() { Identifier = identifier }; + } } /// @@ -176,12 +209,15 @@ public record AnnotatedTextEdit : TextEdit /// /// The actual annotation /// - public ChangeAnnotationIdentifier AnnotationId { get; init; } + public ChangeAnnotationIdentifier AnnotationId { get; init; } = null!; private string DebuggerDisplay => $"annotationId: {Range} {( string.IsNullOrWhiteSpace(NewText) ? string.Empty : NewText.Length > 30 ? NewText.Substring(0, 30) : NewText )}"; /// - public override string ToString() => DebuggerDisplay; + public override string ToString() + { + return DebuggerDisplay; + } } } diff --git a/src/Protocol/Progress/PartialItemRequestProgressObservable.cs b/src/Protocol/Progress/PartialItemRequestProgressObservable.cs index 439e672b3..5e921134d 100644 --- a/src/Protocol/Progress/PartialItemRequestProgressObservable.cs +++ b/src/Protocol/Progress/PartialItemRequestProgressObservable.cs @@ -1,5 +1,4 @@ using System; -using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; @@ -8,7 +7,6 @@ using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Models; @@ -35,14 +33,16 @@ Action onCompleteAction { _serializer = serializer; _dataSubject = new ReplaySubject(1, Scheduler.Immediate); - _disposable = new CompositeDisposable() { _dataSubject }; + _disposable = new CompositeDisposable { _dataSubject }; _task = Observable.Create( - observer => new CompositeDisposable() { + observer => new CompositeDisposable + { _dataSubject .ForkJoin( requestResult .Do( - _ => { + _ => + { if (_receivedPartialData) return; _dataSubject.OnNext(reverseFactory(_)); }, @@ -63,8 +63,15 @@ Action onCompleteAction public ProgressToken ProgressToken { get; } public Type ParamsType { get; } = typeof(TItem); - void IObserver.OnCompleted() => OnCompleted(); - void IObserver.OnError(Exception error) => OnError(error); + void IObserver.OnCompleted() + { + OnCompleted(); + } + + void IObserver.OnError(Exception error) + { + OnError(error); + } private void OnCompleted() { @@ -91,11 +98,20 @@ public void Dispose() _disposable.Dispose(); } - public IDisposable Subscribe(IObserver observer) => _dataSubject.Subscribe(observer); + public IDisposable Subscribe(IObserver observer) + { + return _dataSubject.Subscribe(observer); + } #pragma warning disable VSTHRD003 - public Task AsTask() => _task; + public Task AsTask() + { + return _task; + } #pragma warning restore VSTHRD003 - public TaskAwaiter GetAwaiter() => _task.GetAwaiter(); + public TaskAwaiter GetAwaiter() + { + return _task.GetAwaiter(); + } } } diff --git a/src/Protocol/Progress/PartialItemsRequestProgressObservable.cs b/src/Protocol/Progress/PartialItemsRequestProgressObservable.cs index 79a4fa040..3ca17fe7d 100644 --- a/src/Protocol/Progress/PartialItemsRequestProgressObservable.cs +++ b/src/Protocol/Progress/PartialItemsRequestProgressObservable.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; @@ -17,7 +16,8 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Progress { - internal class PartialItemsRequestProgressObservable : IRequestProgressObservable, TResult>, IObserver, IDisposable + internal class PartialItemsRequestProgressObservable : IRequestProgressObservable, TResult>, IObserver, + IDisposable where TResult : IEnumerable? { private readonly ISerializer _serializer; @@ -37,13 +37,15 @@ Action onCompleteAction { _serializer = serializer; _dataSubject = new ReplaySubject>(int.MaxValue, Scheduler.Immediate); - _disposable = new CompositeDisposable() { _dataSubject }; + _disposable = new CompositeDisposable { _dataSubject }; _task = Observable.Create( - observer => new CompositeDisposable() { + observer => new CompositeDisposable + { _dataSubject .Aggregate( new List(), - (acc, data) => { + (acc, data) => + { acc.AddRange(data); return acc; } @@ -70,8 +72,15 @@ Action onCompleteAction public ProgressToken ProgressToken { get; } public Type ParamsType { get; } = typeof(TItem); - void IObserver.OnCompleted() => OnCompleted(); - void IObserver.OnError(Exception error) => OnError(error); + void IObserver.OnCompleted() + { + OnCompleted(); + } + + void IObserver.OnError(Exception error) + { + OnError(error); + } private void OnCompleted() { @@ -99,15 +108,25 @@ public void Dispose() } // public IDisposable Subscribe(IObserver> observer) => _disposable.IsDisposed ? Disposable.Empty : _dataSubject.Subscribe(observer); - public IDisposable Subscribe(IObserver> observer) => _dataSubject.Subscribe(observer); + public IDisposable Subscribe(IObserver> observer) + { + return _dataSubject.Subscribe(observer); + } #pragma warning disable VSTHRD003 - public Task AsTask() => _task; + public Task AsTask() + { + return _task; + } #pragma warning restore VSTHRD003 - public TaskAwaiter GetAwaiter() => _task.GetAwaiter(); + public TaskAwaiter GetAwaiter() + { + return _task.GetAwaiter(); + } } - internal class PartialItemsRequestProgressObservable : PartialItemsRequestProgressObservable?>, IRequestProgressObservable + internal class PartialItemsRequestProgressObservable : PartialItemsRequestProgressObservable?>, + IRequestProgressObservable { public PartialItemsRequestProgressObservable( ISerializer serializer, diff --git a/src/Protocol/Serialization/Converters/ChangeAnnotationIdentifierConverter.cs b/src/Protocol/Serialization/Converters/ChangeAnnotationIdentifierConverter.cs index 8e85870a9..d4756e846 100644 --- a/src/Protocol/Serialization/Converters/ChangeAnnotationIdentifierConverter.cs +++ b/src/Protocol/Serialization/Converters/ChangeAnnotationIdentifierConverter.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - internal class ChangeAnnotationIdentifierConverter : JsonConverter + internal class ChangeAnnotationIdentifierConverter : JsonConverter { public override ChangeAnnotationIdentifier? ReadJson( JsonReader reader, Type objectType, ChangeAnnotationIdentifier? existingValue, diff --git a/src/Protocol/Server/Capabilities/IServerCapabilities.cs b/src/Protocol/Server/Capabilities/IServerCapabilities.cs index a94a44e6c..b441b237c 100644 --- a/src/Protocol/Server/Capabilities/IServerCapabilities.cs +++ b/src/Protocol/Server/Capabilities/IServerCapabilities.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Protocol.Models; diff --git a/src/Protocol/Server/Capabilities/IWorkspaceServerCapabilities.cs b/src/Protocol/Server/Capabilities/IWorkspaceServerCapabilities.cs index cdf221094..276e1c510 100644 --- a/src/Protocol/Server/Capabilities/IWorkspaceServerCapabilities.cs +++ b/src/Protocol/Server/Capabilities/IWorkspaceServerCapabilities.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; -using Newtonsoft.Json.Linq; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { diff --git a/src/Protocol/Shared/LspHandlerDescriptor.cs b/src/Protocol/Shared/LspHandlerDescriptor.cs index 870dd9fc2..dd3888669 100644 --- a/src/Protocol/Shared/LspHandlerDescriptor.cs +++ b/src/Protocol/Shared/LspHandlerDescriptor.cs @@ -32,7 +32,8 @@ public LspHandlerDescriptor( ILspHandlerTypeDescriptor? typeDescriptor ) : this( index, - method, key, handler, handlerType, @params, registrationType, registrationMethod, registrationOptions, capabilityType, requestProcessType, disposeAction, + method, key, handler, handlerType, @params, registrationType, registrationMethod, registrationOptions, capabilityType, requestProcessType, + disposeAction, typeDescriptor, null ) { @@ -73,7 +74,7 @@ public LspHandlerDescriptor( .Select(x => x.GetGenericArguments()[0]) .OrderBy(x => x == typeof(Unit)) .FirstOrDefault() - ?? typeDescriptor?.ResponseType ?? typeof(Unit); + ?? typeDescriptor?.ResponseType ?? typeof(Unit); // If multiple are implemented this behavior is unknown CanBeResolvedHandlerType = handler.GetType().GetTypeInfo() @@ -88,7 +89,8 @@ public LspHandlerDescriptor( typeof(DelegatingNotification<>).IsAssignableFrom(@params.GetGenericTypeDefinition()) ); - IsNotification = handlerType.GetInterfaces().Any(z => z.IsGenericType && typeof(IJsonRpcNotificationHandler<>).IsAssignableFrom(z.GetGenericTypeDefinition())); + IsNotification = handlerType.GetInterfaces() + .Any(z => z.IsGenericType && typeof(IJsonRpcNotificationHandler<>).IsAssignableFrom(z.GetGenericTypeDefinition())); IsRequest = !IsNotification; RequestProcessType = requestProcessType; TypeDescriptor = typeDescriptor; @@ -101,7 +103,8 @@ public LspHandlerDescriptor( string key, object? registrationOptions ) : this( - descriptor.Index, descriptor.Method, key, descriptor.Handler, descriptor.HandlerType, descriptor.Params, descriptor.RegistrationType, descriptor.RegistrationMethod, + descriptor.Index, descriptor.Method, key, descriptor.Handler, descriptor.HandlerType, descriptor.Params, descriptor.RegistrationType, + descriptor.RegistrationMethod, registrationOptions, descriptor.CapabilityType, descriptor.RequestProcessType, descriptor._disposeAction, descriptor.TypeDescriptor, descriptor.Id ) { @@ -137,35 +140,54 @@ public LspHandlerDescriptor( public RequestProcessType? RequestProcessType { get; } public ILspHandlerTypeDescriptor? TypeDescriptor { get; } - public void Dispose() => _disposeAction(); + public void Dispose() + { + _disposeAction(); + } - public override bool Equals(object? obj) => Equals(obj as LspHandlerDescriptor); + public override bool Equals(object? obj) + { + return Equals(obj as LspHandlerDescriptor); + } - public bool Equals(LspHandlerDescriptor? other) => - other is not null && + public bool Equals(LspHandlerDescriptor? other) + { + return other is not null && // EqualityComparer.Default.Equals(HandlerType, other.HandlerType) && - Method == other.Method && - Key == other.Key; + Method == other.Method && + Key == other.Key; + } public override int GetHashCode() { var hashCode = -45133801; // hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(HandlerType); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(Method); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(Key); + hashCode = ( hashCode * -1521134295 ) + EqualityComparer.Default.GetHashCode(Method); + hashCode = ( hashCode * -1521134295 ) + EqualityComparer.Default.GetHashCode(Key); return hashCode; } - public static bool operator ==(LspHandlerDescriptor descriptor1, LspHandlerDescriptor descriptor2) => - EqualityComparer.Default.Equals(descriptor1, descriptor2); + public static bool operator ==(LspHandlerDescriptor descriptor1, LspHandlerDescriptor descriptor2) + { + return EqualityComparer.Default.Equals(descriptor1, descriptor2); + } - public static bool operator !=(LspHandlerDescriptor descriptor1, LspHandlerDescriptor descriptor2) => !( descriptor1 == descriptor2 ); + public static bool operator !=(LspHandlerDescriptor descriptor1, LspHandlerDescriptor descriptor2) + { + return !( descriptor1 == descriptor2 ); + } internal class AllowAllEqualityComparer : IEqualityComparer { - public bool Equals(LspHandlerDescriptor x, LspHandlerDescriptor y) => x.Id == y.Id; - - public int GetHashCode(LspHandlerDescriptor obj) => obj.Id.GetHashCode(); + public bool Equals(LspHandlerDescriptor x, LspHandlerDescriptor y) + { + return x.Id == y.Id; + } + + public int GetHashCode(LspHandlerDescriptor obj) + { + return obj.Id.GetHashCode(); + } } } } diff --git a/src/Protocol/Shared/LspHandlerTypeDescriptorProvider.cs b/src/Protocol/Shared/LspHandlerTypeDescriptorProvider.cs index aa921f0ca..877ed5e31 100644 --- a/src/Protocol/Shared/LspHandlerTypeDescriptorProvider.cs +++ b/src/Protocol/Shared/LspHandlerTypeDescriptorProvider.cs @@ -46,14 +46,27 @@ internal LspHandlerTypeDescriptorProvider(IEnumerable assemblies, bool .FirstOrDefault()?.Method; } - public Type? GetRegistrationType(string method) => KnownHandlers - .SelectMany(z => z) - .FirstOrDefault(z => z.HasRegistration && z.RegistrationMethod == method)?.RegistrationType; + public Type? GetRegistrationType(string method) + { + return KnownHandlers + .SelectMany(z => z) + .FirstOrDefault(z => z.HasRegistration && z.RegistrationMethod == method)?.RegistrationType; + } - public ILspHandlerTypeDescriptor? GetHandlerTypeDescriptor() => GetHandlerTypeDescriptor(typeof(TA)); - IHandlerTypeDescriptor? IHandlerTypeDescriptorProvider.GetHandlerTypeDescriptor(Type type) => GetHandlerTypeDescriptor(type); + public ILspHandlerTypeDescriptor? GetHandlerTypeDescriptor() + { + return GetHandlerTypeDescriptor(typeof(TA)); + } - IHandlerTypeDescriptor? IHandlerTypeDescriptorProvider.GetHandlerTypeDescriptor() => GetHandlerTypeDescriptor(); + IHandlerTypeDescriptor? IHandlerTypeDescriptorProvider.GetHandlerTypeDescriptor(Type type) + { + return GetHandlerTypeDescriptor(type); + } + + IHandlerTypeDescriptor? IHandlerTypeDescriptorProvider.GetHandlerTypeDescriptor() + { + return GetHandlerTypeDescriptor(); + } public ILspHandlerTypeDescriptor? GetHandlerTypeDescriptor(Type type) { @@ -69,12 +82,18 @@ internal LspHandlerTypeDescriptorProvider(IEnumerable assemblies, bool } var methodName = GetMethodName(type); - return string.IsNullOrWhiteSpace(methodName) ? null : KnownHandlers[methodName!].FirstOrDefault(); + return string.IsNullOrWhiteSpace(methodName) ? null : KnownHandlers[methodName].FirstOrDefault(); } - public string? GetMethodName() where T : IJsonRpcHandler => GetMethodName(typeof(T)); + public string? GetMethodName() where T : IJsonRpcHandler + { + return GetMethodName(typeof(T)); + } - public bool IsMethodName(string name, params Type[] types) => types.Any(z => GetMethodName(z)?.Equals(name) == true); + public bool IsMethodName(string name, params Type[] types) + { + return types.Any(z => GetMethodName(z)?.Equals(name) == true); + } public string? GetMethodName(Type type) { diff --git a/src/Server/ClientCapabilityProvider.cs b/src/Server/ClientCapabilityProvider.cs index 1992dcad3..9a560cda7 100644 --- a/src/Server/ClientCapabilityProvider.cs +++ b/src/Server/ClientCapabilityProvider.cs @@ -1,12 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Reflection; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Shared; using OmniSharp.Extensions.LanguageServer.Shared; namespace OmniSharp.Extensions.LanguageServer.Server @@ -17,8 +15,9 @@ internal class ClientCapabilityProvider private readonly bool _supportsProgress; public ClientCapabilityProvider( - IHandlerCollection collection, - bool supportsProgress) + IHandlerCollection collection, + bool supportsProgress + ) { _collection = collection; _supportsProgress = supportsProgress; @@ -31,11 +30,13 @@ public bool HasStaticHandler(Supports capability) // However if the client does not tell us it's capabilities we should just assume that they do not support // dynamic registrations but we should report any capabilities statically if (capability.IsSupported && capability.Value != null && capability.Value.DynamicRegistration) return false; - return _collection.Any(z => z.HasCapability &&z.CapabilityType == typeof(T)); + return _collection.Any(z => z.HasCapability && z.CapabilityType == typeof(T)); } public IOptionsGetter GetStaticOptions(Supports capability) where T : DynamicCapability - => !HasStaticHandler(capability) ? Null : new OptionsGetter(_collection, _supportsProgress); + { + return !HasStaticHandler(capability) ? Null : new OptionsGetter(_collection, _supportsProgress); + } private static readonly IOptionsGetter Null = new NullOptionsGetter(); @@ -68,11 +69,17 @@ private class NullOptionsGetter : IOptionsGetter { public TOptions? Get(Func, TOptions> action) where TOptions : class - where TInterface : notnull => null; + where TInterface : notnull + { + return null; + } public TOptions? Reduce(Func, IEnumerable, TOptions> action) where TOptions : class - where TInterface : notnull => null; + where TInterface : notnull + { + return null; + } } private class OptionsGetter : IOptionsGetter diff --git a/src/Server/LanguageServer.cs b/src/Server/LanguageServer.cs index 6838a50c0..ef81d70d8 100644 --- a/src/Server/LanguageServer.cs +++ b/src/Server/LanguageServer.cs @@ -25,7 +25,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; -using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; using OmniSharp.Extensions.LanguageServer.Server.Abstractions; using OmniSharp.Extensions.LanguageServer.Server.Logging; using OmniSharp.Extensions.LanguageServer.Shared; @@ -35,7 +34,8 @@ namespace OmniSharp.Extensions.LanguageServer.Server { [BuiltIn] - public partial class LanguageServer : JsonRpcServerBase, ILanguageServer, ILanguageProtocolInitializeHandler, ILanguageProtocolInitializedHandler, IAwaitableTermination + public partial class LanguageServer : JsonRpcServerBase, ILanguageServer, ILanguageProtocolInitializeHandler, ILanguageProtocolInitializedHandler, + IAwaitableTermination { private readonly Connection _connection; private ClientVersion? _clientVersion; @@ -63,12 +63,21 @@ public partial class LanguageServer : JsonRpcServerBase, ILanguageServer, ILangu private readonly ILookup _capabilityTypes; private readonly IResolverContext _resolverContext; - internal static IContainer CreateContainer(LanguageServerOptions options, IServiceProvider? outerServiceProvider) => - JsonRpcServerContainer.Create(outerServiceProvider) - .AddLanguageServerInternals(options, outerServiceProvider); + internal static IContainer CreateContainer(LanguageServerOptions options, IServiceProvider? outerServiceProvider) + { + return JsonRpcServerContainer.Create(outerServiceProvider) + .AddLanguageServerInternals(options, outerServiceProvider); + } - public static LanguageServer Create(LanguageServerOptions options) => Create(options, null); - public static LanguageServer Create(Action optionsAction) => Create(optionsAction, null); + public static LanguageServer Create(LanguageServerOptions options) + { + return Create(options, null); + } + + public static LanguageServer Create(Action optionsAction) + { + return Create(optionsAction, null); + } public static LanguageServer Create(Action optionsAction, IServiceProvider? outerServiceProvider) { @@ -77,28 +86,53 @@ public static LanguageServer Create(Action optionsAction, return Create(options, outerServiceProvider); } - public static LanguageServer Create(LanguageServerOptions options, IServiceProvider? outerServiceProvider) => - CreateContainer(options, outerServiceProvider).Resolve(); + public static LanguageServer Create(LanguageServerOptions options, IServiceProvider? outerServiceProvider) + { + return CreateContainer(options, outerServiceProvider).Resolve(); + } + + public static Task From(LanguageServerOptions options) + { + return From(options, null, CancellationToken.None); + } - public static Task From(LanguageServerOptions options) => From(options, null, CancellationToken.None); - public static Task From(Action optionsAction) => From(optionsAction, null, CancellationToken.None); - public static Task From(LanguageServerOptions options, CancellationToken cancellationToken) => From(options, null, cancellationToken); - public static Task From(Action optionsAction, CancellationToken cancellationToken) => From(optionsAction, null, cancellationToken); + public static Task From(Action optionsAction) + { + return From(optionsAction, null, CancellationToken.None); + } - public static Task From(LanguageServerOptions options, IServiceProvider? outerServiceProvider) => - From(options, outerServiceProvider, CancellationToken.None); + public static Task From(LanguageServerOptions options, CancellationToken cancellationToken) + { + return From(options, null, cancellationToken); + } - public static Task From(Action optionsAction, IServiceProvider? outerServiceProvider) => - From(optionsAction, outerServiceProvider, CancellationToken.None); + public static Task From(Action optionsAction, CancellationToken cancellationToken) + { + return From(optionsAction, null, cancellationToken); + } - public static Task From(Action optionsAction, IServiceProvider? outerServiceProvider, CancellationToken cancellationToken) + public static Task From(LanguageServerOptions options, IServiceProvider? outerServiceProvider) + { + return From(options, outerServiceProvider, CancellationToken.None); + } + + public static Task From(Action optionsAction, IServiceProvider? outerServiceProvider) + { + return From(optionsAction, outerServiceProvider, CancellationToken.None); + } + + public static Task From( + Action optionsAction, IServiceProvider? outerServiceProvider, CancellationToken cancellationToken + ) { var options = new LanguageServerOptions(); optionsAction(options); return From(options, outerServiceProvider, cancellationToken); } - public static async Task From(LanguageServerOptions options, IServiceProvider? outerServiceProvider, CancellationToken cancellationToken) + public static async Task From( + LanguageServerOptions options, IServiceProvider? outerServiceProvider, CancellationToken cancellationToken + ) { var server = Create(options, outerServiceProvider); await server.Initialize(cancellationToken).ConfigureAwait(false); @@ -112,7 +146,10 @@ public static async Task From(LanguageServerOptions options, ISe /// /// /// - public static LanguageServer PreInit(Action optionsAction) => Create(optionsAction); + public static LanguageServer PreInit(Action optionsAction) + { + return Create(optionsAction); + } /// /// Create the server without connecting to the client @@ -121,7 +158,10 @@ public static async Task From(LanguageServerOptions options, ISe /// /// /// - public static LanguageServer PreInit(LanguageServerOptions options) => Create(options); + public static LanguageServer PreInit(LanguageServerOptions options) + { + return Create(options); + } internal LanguageServer( Connection connection, @@ -358,9 +398,9 @@ out GeneralClientCapabilities generalCapabilities _supportedCapabilities.Initialize(clientCapabilities); foreach (var group in _capabilityTypes) { - foreach (var capabilityType in @group) + foreach (var capabilityType in group) { - if (request.Capabilities.SelectToken(@group.Key) is JObject capabilityData) + if (request.Capabilities.SelectToken(group.Key) is JObject capabilityData) { var capability = capabilityData.ToObject(capabilityType) as ICapability; _supportedCapabilities.Add(capability!); @@ -461,7 +501,9 @@ private InitializeResult ReadServerCapabilities( .Select(x => x.Handler) .OfType() .Select( - x => ( (TextDocumentChangeRegistrationOptions?) x.GetRegistrationOptions(textDocumentCapabilities.Synchronization!, clientCapabilities) ) + x => ( (TextDocumentChangeRegistrationOptions?)x.GetRegistrationOptions( + textDocumentCapabilities.Synchronization!, clientCapabilities + ) ) ?.SyncKind ?? TextDocumentSyncKind.None ) @@ -479,7 +521,8 @@ private InitializeResult ReadServerCapabilities( } else { - serverCapabilities.TextDocumentSync = new TextDocumentSyncOptions { + serverCapabilities.TextDocumentSync = new TextDocumentSyncOptions + { Change = textDocumentSyncKind, OpenClose = _collection.ContainsHandler(typeof(IDidOpenTextDocumentHandler)) || _collection.ContainsHandler(typeof(IDidCloseTextDocumentHandler)), @@ -495,7 +538,8 @@ private InitializeResult ReadServerCapabilities( // TODO: Need a call back here // serverCapabilities.Experimental; - var result = ServerSettings = new InitializeResult { + var result = ServerSettings = new InitializeResult + { Capabilities = serverCapabilities, ServerInfo = _serverInfo }; @@ -523,10 +567,15 @@ public IDisposable Register(Action registryAction) LanguageServerHelpers.InitHandlers(this, result, _supportedCapabilities); } - return LanguageServerHelpers.RegisterHandlers(_initializeComplete.Select(_ => System.Reactive.Unit.Default), Client, WorkDoneManager, _supportedCapabilities, result); + return LanguageServerHelpers.RegisterHandlers( + _initializeComplete.Select(_ => System.Reactive.Unit.Default), Client, WorkDoneManager, _supportedCapabilities, result + ); // return LanguageServerHelpers.RegisterHandlers(_initializingTask ?? _initializeComplete.ToTask(), Client, WorkDoneManager, _supportedCapabilities, result); } - object IServiceProvider.GetService(Type serviceType) => Services.GetService(serviceType); + object IServiceProvider.GetService(Type serviceType) + { + return Services.GetService(serviceType); + } } } diff --git a/src/Server/Pipelines/SemanticTokensDeltaPipeline.cs b/src/Server/Pipelines/SemanticTokensDeltaPipeline.cs index 13240bf60..377e430a9 100644 --- a/src/Server/Pipelines/SemanticTokensDeltaPipeline.cs +++ b/src/Server/Pipelines/SemanticTokensDeltaPipeline.cs @@ -3,12 +3,11 @@ using System.Threading; using System.Threading.Tasks; using MediatR; -using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace OmniSharp.Extensions.LanguageServer.Server.Pipelines { - class SemanticTokensDeltaPipeline : IPipelineBehavior + internal class SemanticTokensDeltaPipeline : IPipelineBehavior where TRequest : notnull { public async Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) @@ -33,9 +32,9 @@ class SemanticTokensDeltaPipeline : IPipelineBehavior(this IContainer container, LanguageProtocolRpcOptionsBase options) where T : IJsonRpcHandlerRegistry + internal static IContainer AddLanguageProtocolInternals(this IContainer container, LanguageProtocolRpcOptionsBase options) + where T : IJsonRpcHandlerRegistry { options.RequestProcessIdentifier ??= options.SupportsContentModified ? new RequestProcessIdentifier(RequestProcessType.Parallel) @@ -29,7 +28,7 @@ internal static IContainer AddLanguageProtocolInternals(this IContainer conta options.Services.AddLogging(builder => options.LoggingBuilderAction?.Invoke(builder)); container = container.AddJsonRpcServerCore(options); - container.RegisterInstanceMany(new LspHandlerTypeDescriptorProvider(options.Assemblies, options.UseAssemblyAttributeScanning), nonPublicServiceTypes: true); + container.RegisterInstanceMany(new LspHandlerTypeDescriptorProvider(options.Assemblies, options.UseAssemblyAttributeScanning), true); container.RegisterInstanceMany(options.Serializer); container.RegisterInstance(options.RequestProcessIdentifier); @@ -38,11 +37,14 @@ internal static IContainer AddLanguageProtocolInternals(this IContainer conta container.RegisterMany(Reuse.Singleton); container.RegisterMany(nonPublicServiceTypes: true, reuse: Reuse.Singleton); container.Register(Reuse.Singleton); - container.RegisterInitializer((identifiers, context) => { identifiers.Add(context.GetServices().ToArray()); }); + container.RegisterInitializer( + (identifiers, context) => { identifiers.Add(context.GetServices().ToArray()); } + ); container.RegisterMany(Reuse.Singleton); container.RegisterMany(nonPublicServiceTypes: true, reuse: Reuse.Singleton); container.RegisterInitializer( - (manager, context) => { + (manager, context) => + { var descriptions = context.Resolve(); descriptions.Populate(context, manager); } @@ -59,7 +61,7 @@ internal static IContainer AddLanguageProtocolInternals(this IContainer conta .SelectMany(z => z.GetCustomAttributes()) .Select(z => z.ConverterType) .Where(z => typeof(IRegistrationOptionsConverter).IsAssignableFrom(z)), - reuse: Reuse.Singleton + Reuse.Singleton ); } else @@ -69,7 +71,7 @@ internal static IContainer AddLanguageProtocolInternals(this IContainer conta .SelectMany(z => z.GetTypes()) .Where(z => z.IsClass && !z.IsAbstract) .Where(z => typeof(IRegistrationOptionsConverter).IsAssignableFrom(z)), - reuse: Reuse.Singleton + Reuse.Singleton ); } diff --git a/test/.editorconfig b/test/.editorconfig index f508dbdfa..c810d8b12 100644 --- a/test/.editorconfig +++ b/test/.editorconfig @@ -1,10 +1,22 @@ [*] dotnet_diagnostic.CA2007.severity = none dotnet_diagnostic.CS0618.severity = none +dotnet_diagnostic.CS0168.severity = none +dotnet_diagnostic.CS0105.severity = none dotnet_diagnostic.CS4014.severity = none +dotnet_diagnostic.CS0162.severity = none +dotnet_diagnostic.CS8602.severity = none +dotnet_diagnostic.CS8604.severity = none +dotnet_diagnostic.CS8618.severity = none +dotnet_diagnostic.CS8619.severity = none +dotnet_diagnostic.CS8620.severity = none +dotnet_diagnostic.CS8625.severity = none +dotnet_diagnostic.CS8762.severity = none +dotnet_diagnostic.CS8767.severity = none dotnet_diagnostic.CS1998.severity = none dotnet_diagnostic.VSTHRD003.severity = none dotnet_diagnostic.VSTHRD103.severity = none dotnet_diagnostic.VSTHRD105.severity = none dotnet_diagnostic.VSTHRD110.severity = none dotnet_diagnostic.VSTHRD200.severity = none +resharper_unused_parameter_local_highlighting = none diff --git a/test/Client.Tests/ClientTests.cs b/test/Client.Tests/ClientTests.cs index e435f3bb9..650968289 100644 --- a/test/Client.Tests/ClientTests.cs +++ b/test/Client.Tests/ClientTests.cs @@ -7,7 +7,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using TestingUtils; using Xunit; using Xunit.Abstractions; using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; @@ -46,16 +45,20 @@ public async Task Hover_Success() var expectedHoverContent = new MarkedStringsOrMarkupContent("123", "456", "789"); var (client, _) = await Initialize( - clientOptions => { + clientOptions => + { clientOptions.WithCapability( - new HoverCapability { + new HoverCapability + { ContentFormat = new Container(MarkupKind.Markdown, MarkupKind.PlainText), } ); }, - serverOptions => { + serverOptions => + { serverOptions.OnHover( - (request, _) => { + (request, _) => + { Assert.NotNull(request.TextDocument); Assert.Equal( @@ -67,9 +70,11 @@ public async Task Hover_Success() Assert.Equal(column, request.Position.Character); return Task.FromResult( - new Hover { + new Hover + { Contents = expectedHoverContent, - Range = new Range { + Range = new Range + { Start = request.Position, End = request.Position } @@ -81,7 +86,8 @@ public async Task Hover_Success() ); var hover = await client.TextDocument.RequestHover( - new HoverParams { + new HoverParams + { TextDocument = AbsoluteDocumentPath, Position = ( line, column ) } @@ -118,11 +124,14 @@ public async Task Completions_Success() const int column = 5; var expectedDocumentPath = AbsoluteDocumentPath; var expectedDocumentUri = DocumentUri.FromFileSystemPath(expectedDocumentPath); - var expectedCompletionItems = new[] { - new CompletionItem { + var expectedCompletionItems = new[] + { + new CompletionItem + { Kind = CompletionItemKind.Class, Label = "Class1", - TextEdit = new TextEdit { + TextEdit = new TextEdit + { Range = ( ( line, column ), ( line, column ) ), NewText = "Class1", } @@ -130,15 +139,19 @@ public async Task Completions_Success() }; var (client, _) = await Initialize( - clientOptions => { + clientOptions => + { clientOptions.WithCapability( - new CompletionCapability { - CompletionItem = new CompletionItemCapabilityOptions { + new CompletionCapability + { + CompletionItem = new CompletionItemCapabilityOptions + { DeprecatedSupport = true, DocumentationFormat = new Container(MarkupKind.Markdown, MarkupKind.PlainText), PreselectSupport = true, SnippetSupport = true, - TagSupport = new CompletionItemTagSupportCapabilityOptions { + TagSupport = new CompletionItemTagSupportCapabilityOptions + { ValueSet = new[] { CompletionItemTag.Deprecated } }, CommitCharactersSupport = true @@ -146,9 +159,11 @@ public async Task Completions_Success() } ); }, - serverOptions => { + serverOptions => + { serverOptions.OnCompletion( - (request, _) => { + (request, _) => + { Assert.NotNull(request.TextDocument); Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); @@ -168,7 +183,8 @@ public async Task Completions_Success() ); var actualCompletions = await client.TextDocument.RequestCompletion( - new CompletionParams { + new CompletionParams + { TextDocument = AbsoluteDocumentPath, Position = ( line, column ), }, CancellationToken @@ -179,7 +195,8 @@ public async Task Completions_Success() var actualCompletionItems = actualCompletions.Items.ToArray(); Assert.Collection( - actualCompletionItems, actualCompletionItem => { + actualCompletionItems, actualCompletionItem => + { var expectedCompletionItem = expectedCompletionItems[0]; Assert.Equal(expectedCompletionItem.Kind, actualCompletionItem.Kind); @@ -223,15 +240,20 @@ public async Task SignatureHelp_Success() var expectedDocumentPath = AbsoluteDocumentPath; var expectedDocumentUri = DocumentUri.FromFileSystemPath(expectedDocumentPath); - var expectedSignatureHelp = new SignatureHelp { + var expectedSignatureHelp = new SignatureHelp + { ActiveParameter = 0, ActiveSignature = 0, - Signatures = new[] { - new SignatureInformation { + Signatures = new[] + { + new SignatureInformation + { Documentation = new StringOrMarkupContent("test documentation"), Label = "TestSignature", - Parameters = new[] { - new ParameterInformation { + Parameters = new[] + { + new ParameterInformation + { Documentation = "test parameter documentation", Label = "parameter label" } @@ -241,22 +263,28 @@ public async Task SignatureHelp_Success() }; var (client, _) = await Initialize( - clientOptions => { + clientOptions => + { clientOptions.WithCapability( - new SignatureHelpCapability { + new SignatureHelpCapability + { ContextSupport = true, - SignatureInformation = new SignatureInformationCapabilityOptions { + SignatureInformation = new SignatureInformationCapabilityOptions + { DocumentationFormat = new Container(MarkupKind.Markdown), - ParameterInformation = new SignatureParameterInformationCapabilityOptions { + ParameterInformation = new SignatureParameterInformationCapabilityOptions + { LabelOffsetSupport = true } } } ); }, - serverOptions => { + serverOptions => + { serverOptions.OnSignatureHelp( - (request, cancellationToken) => { + (request, cancellationToken) => + { Assert.NotNull(request.TextDocument); Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); @@ -271,7 +299,8 @@ public async Task SignatureHelp_Success() ); var actualSignatureHelp = await client.TextDocument.RequestSignatureHelp( - new SignatureHelpParams { + new SignatureHelpParams + { TextDocument = AbsoluteDocumentPath, Position = ( line, column ), }, CancellationToken @@ -282,7 +311,8 @@ public async Task SignatureHelp_Success() var actualSignatures = actualSignatureHelp.Signatures.ToArray(); Assert.Collection( - actualSignatures, actualSignature => { + actualSignatures, actualSignature => + { var expectedSignature = expectedSignatureHelp.Signatures.ToArray()[0]; Assert.True(actualSignature.Documentation!.HasString); @@ -294,7 +324,8 @@ public async Task SignatureHelp_Success() var actualParameters = actualSignature.Parameters!.ToArray(); Assert.Collection( - actualParameters, actualParameter => { + actualParameters, actualParameter => + { var expectedParameter = expectedParameters[0]; Assert.True(actualParameter.Documentation!.HasString); Assert.Equal(expectedParameter.Documentation!.String, actualParameter.Documentation.String); @@ -318,7 +349,8 @@ public async Task Definition_Success() var expectedDefinitions = new LocationOrLocationLinks( new LocationOrLocationLink( - new Location { + new Location + { Uri = expectedDocumentUri, Range = ( ( line, column ), ( line, column ) ), } @@ -326,16 +358,20 @@ public async Task Definition_Success() ); var (client, _) = await Initialize( - clientOptions => { + clientOptions => + { clientOptions.WithCapability( - new DefinitionCapability { + new DefinitionCapability + { LinkSupport = true } ); }, - serverOptions => { + serverOptions => + { serverOptions.OnDefinition( - (request, cancellationToken) => { + (request, cancellationToken) => + { Assert.NotNull(request.TextDocument); Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); @@ -350,7 +386,8 @@ public async Task Definition_Success() ); var definitions = await client.TextDocument.RequestDefinition( - new DefinitionParams { + new DefinitionParams + { TextDocument = AbsoluteDocumentPath, Position = ( line, column ), }, CancellationToken @@ -358,7 +395,8 @@ public async Task Definition_Success() var actualDefinitions = definitions.ToArray(); Assert.Collection( - actualDefinitions, actualDefinition => { + actualDefinitions, actualDefinition => + { var expectedDefinition = expectedDefinitions.Single(); Assert.NotNull(actualDefinition.Location); @@ -393,21 +431,25 @@ public async Task DocumentHighlights_Success() var expectedDocumentUri = DocumentUri.FromFileSystemPath(expectedDocumentPath); var expectedHighlights = new DocumentHighlightContainer( - new DocumentHighlight { + new DocumentHighlight + { Kind = DocumentHighlightKind.Write, Range = ( ( line, column ), ( line, column ) ), } ); var (client, _) = await Initialize( - clientOptions => { + clientOptions => + { clientOptions.WithCapability( new DocumentHighlightCapability() ); }, - serverOptions => { + serverOptions => + { serverOptions.OnDocumentHighlight( - (request, cancellationToken) => { + (request, cancellationToken) => + { Assert.NotNull(request.TextDocument); Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); @@ -422,7 +464,8 @@ public async Task DocumentHighlights_Success() ); var definitions = await client.TextDocument.RequestDocumentHighlight( - new DocumentHighlightParams { + new DocumentHighlightParams + { TextDocument = AbsoluteDocumentPath, Position = ( line, column ), }, CancellationToken @@ -430,7 +473,8 @@ public async Task DocumentHighlights_Success() var actualDefinitions = definitions!.ToArray(); Assert.Collection( - actualDefinitions, actualHighlight => { + actualDefinitions, actualHighlight => + { var expectedHighlight = expectedHighlights.Single(); Assert.Equal(DocumentHighlightKind.Write, expectedHighlight.Kind); @@ -458,7 +502,8 @@ public async Task DocumentSymbols_DocumentSymbol_Success() var expectedDocumentUri = DocumentUri.FromFileSystemPath(expectedDocumentPath); var detail = "some detail"; - var documentSymbol = new DocumentSymbol { + var documentSymbol = new DocumentSymbol + { Detail = detail, Kind = SymbolKind.Class, Range = new Range(new Position(line, character), new Position(line, character)) @@ -468,26 +513,32 @@ public async Task DocumentSymbols_DocumentSymbol_Success() ); var (client, _) = await Initialize( - clientOptions => { + clientOptions => + { clientOptions.WithCapability( - new DocumentSymbolCapability { + new DocumentSymbolCapability + { DynamicRegistration = true, - SymbolKind = new SymbolKindCapabilityOptions { + SymbolKind = new SymbolKindCapabilityOptions + { ValueSet = new Container( Enum.GetValues(typeof(SymbolKind)).Cast() .ToArray() ) }, - TagSupport = new TagSupportCapabilityOptions { + TagSupport = new TagSupportCapabilityOptions + { ValueSet = new[] { SymbolTag.Deprecated } }, HierarchicalDocumentSymbolSupport = true } ); }, - serverOptions => { + serverOptions => + { serverOptions.OnDocumentSymbol( - (request, cancellationToken) => { + (request, cancellationToken) => + { Assert.NotNull(request.TextDocument); Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); @@ -499,14 +550,16 @@ public async Task DocumentSymbols_DocumentSymbol_Success() ); var symbols = await client.TextDocument.RequestDocumentSymbol( - new DocumentSymbolParams { + new DocumentSymbolParams + { TextDocument = expectedDocumentUri }, CancellationToken ); var actualSymbols = symbols.ToArray(); Assert.Collection( - actualSymbols, actualSymbol => { + actualSymbols, actualSymbol => + { var expectedSymbol = expectedSymbols.Single(); Assert.True(expectedSymbol.IsDocumentSymbol); @@ -541,7 +594,8 @@ public async Task FoldingRanges_Success() var expectedDocumentUri = DocumentUri.FromFileSystemPath(expectedDocumentPath); var expectedFoldingRanges = new Container( - new FoldingRange { + new FoldingRange + { Kind = FoldingRangeKind.Region, StartLine = 5, StartCharacter = 1, @@ -551,17 +605,21 @@ public async Task FoldingRanges_Success() ); var (client, _) = await Initialize( - clientOptions => { + clientOptions => + { clientOptions.WithCapability( - new FoldingRangeCapability { + new FoldingRangeCapability + { RangeLimit = 100, LineFoldingOnly = true } ); }, - serverOptions => { + serverOptions => + { serverOptions.OnFoldingRange( - (request, cancellationToken) => { + (request, cancellationToken) => + { Assert.NotNull(request.TextDocument); Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); return Task.FromResult(expectedFoldingRanges)!; @@ -571,14 +629,16 @@ public async Task FoldingRanges_Success() ); var foldingRanges = await client.TextDocument.RequestFoldingRange( - new FoldingRangeRequestParam { + new FoldingRangeRequestParam + { TextDocument = AbsoluteDocumentPath }, CancellationToken ); var actualFoldingRanges = foldingRanges!.ToArray(); Assert.Collection( - actualFoldingRanges, actualFoldingRange => { + actualFoldingRanges, actualFoldingRange => + { var expectedFoldingRange = expectedFoldingRanges.Single(); Assert.Equal(FoldingRangeKind.Region, expectedFoldingRange.Kind); @@ -599,17 +659,22 @@ public async Task Diagnostics_Success() { var documentPath = AbsoluteDocumentPath; var expectedDocumentUri = DocumentUri.FromFileSystemPath(documentPath); - var expectedDiagnostics = new List { - new Diagnostic { + var expectedDiagnostics = new List + { + new Diagnostic + { Source = "Test", Code = new DiagnosticCode(1234), Message = "This is a diagnostic message.", - Range = new Range { - Start = new Position { + Range = new Range + { + Start = new Position + { Line = 2, Character = 5 }, - End = new Position { + End = new Position + { Line = 3, Character = 7 } @@ -624,9 +689,11 @@ public async Task Diagnostics_Success() List? actualDiagnostics = null; var (_, server) = await Initialize( - clientOptions => { + clientOptions => + { clientOptions.OnPublishDiagnostics( - request => { + request => + { actualDocumentUri = request.Uri; actualDiagnostics = request.Diagnostics.ToList(); @@ -639,7 +706,8 @@ public async Task Diagnostics_Success() ); server.TextDocument.PublishDiagnostics( - new PublishDiagnosticsParams { + new PublishDiagnosticsParams + { Uri = DocumentUri.FromFileSystemPath(documentPath), Diagnostics = expectedDiagnostics } diff --git a/test/Dap.Tests/DapOutputHandlerTests.cs b/test/Dap.Tests/DapOutputHandlerTests.cs index b86d17e1c..05f336aaa 100644 --- a/test/Dap.Tests/DapOutputHandlerTests.cs +++ b/test/Dap.Tests/DapOutputHandlerTests.cs @@ -5,8 +5,6 @@ using FluentAssertions; using Microsoft.Extensions.Logging.Abstractions; using Newtonsoft.Json.Linq; -using NSubstitute; -using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Client; @@ -20,7 +18,9 @@ public class DapOutputHandlerTests { private static OutputHandler NewHandler(PipeWriter writer) { - return new OutputHandler(writer, new DapProtocolSerializer(), new []{ new AlwaysOutputFilter()}, Scheduler.Immediate, NullLogger.Instance); + return new OutputHandler( + writer, new DapProtocolSerializer(), new[] { new AlwaysOutputFilter() }, Scheduler.Immediate, NullLogger.Instance + ); } [Fact] @@ -51,7 +51,8 @@ public async Task ShouldSerializeNotifications() var pipe = new Pipe(new PipeOptions()); using var handler = NewHandler(pipe.Writer); - var value = new OutgoingNotification { + var value = new OutgoingNotification + { Method = "method", Params = new object() }; @@ -73,7 +74,8 @@ public async Task ShouldSerializeRequests() var pipe = new Pipe(new PipeOptions()); using var handler = NewHandler(pipe.Writer); - var value = new OutgoingRequest { + var value = new OutgoingRequest + { Method = "method", Id = 1, Params = new object(), diff --git a/test/Dap.Tests/DebugAdapterSpecifictionRecieverTests.cs b/test/Dap.Tests/DebugAdapterSpecifictionRecieverTests.cs index 9ea0d05f5..8abb164cf 100644 --- a/test/Dap.Tests/DebugAdapterSpecifictionRecieverTests.cs +++ b/test/Dap.Tests/DebugAdapterSpecifictionRecieverTests.cs @@ -4,7 +4,6 @@ using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; -using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.JsonRpc.Server.Messages; using Xunit; @@ -39,7 +38,8 @@ public void Should_Camel_Case_As_Expected() { var serializer = new DapProtocolSerializer(); var response = serializer.SerializeObject( - new InitializeResponse() { + new InitializeResponse + { SupportsCancelRequest = true } ); @@ -53,42 +53,48 @@ public SpecificationMessages() { Add( @"{""seq"": ""0"", ""type"": ""request"", ""command"": ""attach"", ""arguments"": { ""__restart"": 3 }}", - new Renor[] { + new Renor[] + { new Request(0, "attach", new JObject { { "__restart", 3 } }) } ); Add( @"{""seq"": ""1"", ""type"": ""request"", ""command"": ""attach""}", - new Renor[] { + new Renor[] + { new Request(1, "attach", new JObject()) } ); Add( @"{""seq"": ""0"", ""type"": ""event"", ""event"": ""breakpoint"", ""body"": { ""reason"": ""new"" }}", - new Renor[] { + new Renor[] + { new Notification("breakpoint", new JObject { { "reason", "new" } }), } ); Add( @"{""seq"": ""1"", ""type"": ""event"", ""event"": ""breakpoint""}", - new Renor[] { + new Renor[] + { new Notification("breakpoint", null) } ); Add( @"{""seq"": ""1"", ""type"": ""response"", ""request_seq"": 3, ""success"": true, ""command"": ""attach"", ""body"": { }}", - new Renor[] { + new Renor[] + { new ServerResponse(3, new JObject()), } ); Add( @"{""seq"": ""1"", ""type"": ""response"", ""request_seq"": 3, ""success"": true, ""command"": ""attach"", ""body"": null}", - new Renor[] { + new Renor[] + { new ServerResponse(3, null), } ); @@ -103,14 +109,16 @@ public SpecificationMessages() Add( @"{""seq"": ""1"", ""type"": ""response"", ""request_seq"": 3, ""success"": false, ""command"": ""attach"", ""body"": null}", - new Renor[] { + new Renor[] + { new ServerError(3, new ServerErrorResult(-1, "Unknown Error", new JObject())), } ); Add( @"[1]", - new Renor[] { + new Renor[] + { new InvalidRequest(string.Empty, "Not an object") } ); diff --git a/test/Dap.Tests/EnumLikeConverterTests.cs b/test/Dap.Tests/EnumLikeConverterTests.cs index 00e7b5465..293b0c202 100644 --- a/test/Dap.Tests/EnumLikeConverterTests.cs +++ b/test/Dap.Tests/EnumLikeConverterTests.cs @@ -1,6 +1,5 @@ using System; using FluentAssertions; -using OmniSharp.Extensions.DebugAdapter.Client; using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; @@ -13,19 +12,22 @@ public class EnumLikeConverterTests [Fact] public void PathFormat_Should_Be_Serializable() { - var options = new InitializeRequestArguments() { + var options = new InitializeRequestArguments + { PathFormat = PathFormat.Uri }; Action a = () => new DapSerializer().SerializeObject(options); a.Should().NotThrow(); } + [Fact] public void PathFormat_Should_Be_Deserializable() { - Func a = () => new DapSerializer().DeserializeObject("{\"pathformat\": \"Uri\"}"); + var a = () => new DapSerializer().DeserializeObject("{\"pathformat\": \"Uri\"}"); a.Should().NotThrow().Subject.PathFormat.Should().NotBeNull(); } + [Fact] public void PathFormat_Should_Be_Deserializable_When_Null() { diff --git a/test/Dap.Tests/Integration/ConnectionAndDisconnectionTests.cs b/test/Dap.Tests/Integration/ConnectionAndDisconnectionTests.cs index 6e58eba5f..b0d8b3d2d 100644 --- a/test/Dap.Tests/Integration/ConnectionAndDisconnectionTests.cs +++ b/test/Dap.Tests/Integration/ConnectionAndDisconnectionTests.cs @@ -7,9 +7,9 @@ using OmniSharp.Extensions.DebugAdapter.Testing; using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.JsonRpc.Testing; -using TestingUtils; using Xunit; using Xunit.Abstractions; + #pragma warning disable CS0162 namespace Dap.Tests.Integration @@ -30,7 +30,7 @@ public async Task Server_Should_Stay_Alive_When_Requests_Throw_An_Exception() var result = await client.SendRequest("keepalive").Returning(CancellationToken); result.Should().BeTrue(); - Func a = () => client.SendRequest("throw").ReturningVoid(CancellationToken); + var a = () => client.SendRequest("throw").ReturningVoid(CancellationToken); await a.Should().ThrowAsync(); result = await client.SendRequest("keepalive").Returning(CancellationToken); @@ -45,7 +45,7 @@ public async Task Client_Should_Stay_Alive_When_Requests_Throw_An_Exception() var result = await server.SendRequest("keepalive").Returning(CancellationToken); result.Should().BeTrue(); - Func a = () => server.SendRequest("throw").ReturningVoid(CancellationToken); + var a = () => server.SendRequest("throw").ReturningVoid(CancellationToken); await a.Should().ThrowAsync(); result = await server.SendRequest("keepalive").Returning(CancellationToken); @@ -60,7 +60,7 @@ public async Task Server_Should_Support_Links() var result = await client.SendRequest("ka").Returning(CancellationToken); result.Should().BeTrue(); - Func a = () => client.SendRequest("t").ReturningVoid(CancellationToken); + var a = () => client.SendRequest("t").ReturningVoid(CancellationToken); await a.Should().ThrowAsync(); result = await client.SendRequest("ka").Returning(CancellationToken); @@ -75,7 +75,7 @@ public async Task Client_Should_Support_Links() var result = await server.SendRequest("ka").Returning(CancellationToken); result.Should().BeTrue(); - Func a = () => server.SendRequest("t").ReturningVoid(CancellationToken); + var a = () => server.SendRequest("t").ReturningVoid(CancellationToken); await a.Should().ThrowAsync(); result = await server.SendRequest("ka").Returning(CancellationToken); @@ -88,7 +88,8 @@ private void ConfigureClient(DebugAdapterClientOptions options) options.WithLink("keepalive", "ka"); options.WithLink("throw", "t"); options.OnRequest( - "throw", async ct => { + "throw", async ct => + { throw new NotSupportedException(); return Task.CompletedTask; } @@ -101,7 +102,8 @@ private void ConfigureServer(DebugAdapterServerOptions options) options.WithLink("keepalive", "ka"); options.WithLink("throw", "t"); options.OnRequest( - "throw", async ct => { + "throw", async ct => + { throw new NotSupportedException(); return Task.CompletedTask; } diff --git a/test/Dap.Tests/Integration/CustomRequestsTests.cs b/test/Dap.Tests/Integration/CustomRequestsTests.cs index 0d254ee7e..aab4566ae 100644 --- a/test/Dap.Tests/Integration/CustomRequestsTests.cs +++ b/test/Dap.Tests/Integration/CustomRequestsTests.cs @@ -8,7 +8,6 @@ using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; using OmniSharp.Extensions.DebugAdapter.Testing; using OmniSharp.Extensions.JsonRpc.Testing; -using TestingUtils; using Xunit; using Xunit.Abstractions; @@ -27,7 +26,8 @@ public async Task Should_Support_Custom_Attach_Request_Using_Base_Class() var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); }); await client.Attach( - new CustomAttachRequestArguments { + new CustomAttachRequestArguments + { ComputerName = "computer", RunspaceId = "1234", ProcessId = "4321" @@ -49,7 +49,8 @@ public async Task Should_Support_Custom_Attach_Request_Receiving_Regular_Request var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); }); await client.Attach( - new CustomAttachRequestArguments { + new CustomAttachRequestArguments + { ComputerName = "computer", RunspaceId = "1234", ProcessId = "4321" @@ -71,8 +72,10 @@ public async Task Should_Support_Custom_Attach_Request_Using_Extension_Data_Usin var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); }); await client.Attach( - new AttachRequestArguments { - ExtensionData = new Dictionary { + new AttachRequestArguments + { + ExtensionData = new Dictionary + { ["ComputerName"] = "computer", ["RunspaceId"] = "1234", ["ProcessId"] = "4321" @@ -95,7 +98,8 @@ public async Task Should_Support_Custom_Launch_Request_Using_Base_Class() var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); }); await client.Launch( - new CustomLaunchRequestArguments { + new CustomLaunchRequestArguments + { Script = "build.ps1" } ); @@ -113,7 +117,8 @@ public async Task Should_Support_Custom_Launch_Request_Receiving_Regular_Request var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); }); await client.Launch( - new CustomLaunchRequestArguments { + new CustomLaunchRequestArguments + { Script = "build.ps1" } ); @@ -131,8 +136,10 @@ public async Task Should_Support_Custom_Launch_Request_Using_Extension_Data_Base var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); }); await client.Launch( - new CustomLaunchRequestArguments { - ExtensionData = new Dictionary { + new CustomLaunchRequestArguments + { + ExtensionData = new Dictionary + { ["Script"] = "build.ps1" } } @@ -151,7 +158,8 @@ public async Task Should_Support_Custom_Attach_Request_Using_Delegate() var (client, _) = await Initialize(options => { }, options => { options.OnAttach(fake); }); await client.Attach( - new CustomAttachRequestArguments { + new CustomAttachRequestArguments + { ComputerName = "computer", RunspaceId = "1234", ProcessId = "4321" @@ -173,7 +181,8 @@ public async Task Should_Support_Custom_Attach_Request_Receiving_Regular_Request var (client, _) = await Initialize(options => { }, options => { options.OnAttach(fake); }); await client.Attach( - new CustomAttachRequestArguments { + new CustomAttachRequestArguments + { ComputerName = "computer", RunspaceId = "1234", ProcessId = "4321" @@ -195,8 +204,10 @@ public async Task Should_Support_Custom_Attach_Request_Using_Extension_Data_Usin var (client, _) = await Initialize(options => { }, options => { options.OnAttach(fake); }); await client.Attach( - new AttachRequestArguments { - ExtensionData = new Dictionary { + new AttachRequestArguments + { + ExtensionData = new Dictionary + { ["ComputerName"] = "computer", ["RunspaceId"] = "1234", ["ProcessId"] = "4321" @@ -219,7 +230,8 @@ public async Task Should_Support_Custom_Launch_Request_Using_Delegate() var (client, _) = await Initialize(options => { }, options => { options.OnLaunch(fake); }); await client.Launch( - new CustomLaunchRequestArguments { + new CustomLaunchRequestArguments + { Script = "build.ps1" } ); @@ -237,7 +249,8 @@ public async Task Should_Support_Custom_Launch_Request_Receiving_Regular_Request var (client, _) = await Initialize(options => { }, options => { options.OnLaunch(fake); }); await client.Launch( - new CustomLaunchRequestArguments { + new CustomLaunchRequestArguments + { Script = "build.ps1" } ); @@ -255,8 +268,10 @@ public async Task Should_Support_Custom_Launch_Request_Using_Extension_Data_Usin var (client, _) = await Initialize(options => { }, options => { options.OnLaunch(fake); }); await client.Launch( - new CustomLaunchRequestArguments { - ExtensionData = new Dictionary { + new CustomLaunchRequestArguments + { + ExtensionData = new Dictionary + { ["Script"] = "build.ps1" } } @@ -270,11 +285,11 @@ await client.Launch( public record CustomAttachRequestArguments : AttachRequestArguments { - public string ComputerName { get; init; } + public string ComputerName { get; init; } = null!; - public string ProcessId { get; init; } + public string ProcessId { get; init; } = null!; - public string RunspaceId { get; init; } + public string RunspaceId { get; init; } = null!; } public record CustomLaunchRequestArguments : LaunchRequestArguments @@ -282,7 +297,7 @@ public record CustomLaunchRequestArguments : LaunchRequestArguments /// /// Gets or sets the absolute path to the script to debug. /// - public string Script { get; init; } + public string Script { get; init; } = null!; } } } diff --git a/test/Dap.Tests/Integration/GenericDapServerTests.cs b/test/Dap.Tests/Integration/GenericDapServerTests.cs index da531ceff..c56c62729 100644 --- a/test/Dap.Tests/Integration/GenericDapServerTests.cs +++ b/test/Dap.Tests/Integration/GenericDapServerTests.cs @@ -5,7 +5,6 @@ using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; using OmniSharp.Extensions.DebugAdapter.Testing; using OmniSharp.Extensions.JsonRpc.Testing; -using TestingUtils; using Xunit; using Xunit.Abstractions; diff --git a/test/Dap.Tests/Integration/HandlersManagerIntegrationTests.cs b/test/Dap.Tests/Integration/HandlersManagerIntegrationTests.cs index 035394490..e0bce3483 100644 --- a/test/Dap.Tests/Integration/HandlersManagerIntegrationTests.cs +++ b/test/Dap.Tests/Integration/HandlersManagerIntegrationTests.cs @@ -7,7 +7,6 @@ using OmniSharp.Extensions.DebugAdapter.Testing; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Testing; -using TestingUtils; using Xunit; using Xunit.Abstractions; @@ -22,7 +21,7 @@ public HandlersManagerIntegrationTests(ITestOutputHelper testOutputHelper) : bas [Fact] public async Task Should_Return_Default_Handlers() { - var (_, server) = await Initialize(options => {}, options => {}); + var (_, server) = await Initialize(options => { }, options => { }); var handlersManager = server.GetRequiredService(); handlersManager.Descriptors.Should().HaveCount(2); @@ -32,24 +31,27 @@ public async Task Should_Return_Default_Handlers() [Fact] public async Task Link_Should_Fail_If_No_Handler_Is_Defined() { - var (_, server) = await Initialize(options => {}, options => {}); + var (_, server) = await Initialize(options => { }, options => { }); var handlersManager = server.GetRequiredService(); - Action a = () => handlersManager.AddLink(RequestNames.Completions, "my/completions"); + Action a = () => handlersManager.AddLink(RequestNames.Completions, "my/completions"); a.Should().Throw().Which.Message.Should().Contain("Descriptors must be registered before links can be created"); } [Fact] public async Task Link_Should_Fail_If_Link_Is_On_The_Wrong_Side() { - var (_, server) = await Initialize(options => {}, options => {}); + var (_, server) = await Initialize(options => { }, options => { }); var handlersManager = server.GetRequiredService(); - handlersManager.Add((Substitute.For(new[] { typeof(ICompletionsHandler) }, Array.Empty()) as IJsonRpcHandler)!, new JsonRpcHandlerOptions()); + handlersManager.Add( + ( Substitute.For(new[] { typeof(ICompletionsHandler) }, Array.Empty()) as IJsonRpcHandler )!, new JsonRpcHandlerOptions() + ); - Action a = () => handlersManager.AddLink("my/completions", RequestNames.Completions); - a.Should().Throw().Which.Message.Should().Contain($"Did you mean to link '{RequestNames.Completions}' to 'my/completions' instead"); + Action a = () => handlersManager.AddLink("my/completions", RequestNames.Completions); + a.Should().Throw().Which.Message.Should() + .Contain($"Did you mean to link '{RequestNames.Completions}' to 'my/completions' instead"); } } } diff --git a/test/Dap.Tests/Integration/RequestCancellationTests.cs b/test/Dap.Tests/Integration/RequestCancellationTests.cs index b39fa8c77..59db785a8 100644 --- a/test/Dap.Tests/Integration/RequestCancellationTests.cs +++ b/test/Dap.Tests/Integration/RequestCancellationTests.cs @@ -9,7 +9,6 @@ using OmniSharp.Extensions.DebugAdapter.Testing; using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.JsonRpc.Testing; -using TestingUtils; using Xunit; using Xunit.Abstractions; @@ -26,7 +25,8 @@ public async Task Should_Cancel_Pending_Requests() { var (client, _) = await Initialize(ConfigureClient, ConfigureServer); - Func> action = () => { + var action = () => + { var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); CancellationToken.Register(cts.Cancel); return client.RequestCompletions(new CompletionsArguments(), cts.Token); @@ -37,9 +37,11 @@ public async Task Should_Cancel_Pending_Requests() [Fact(Skip = "Needs Work")] public async Task Should_Cancel_Requests_After_Timeout() { - Func> action = async () => { + Func> action = async () => + { var (client, _) = await Initialize( - ConfigureClient, x => { + ConfigureClient, x => + { ConfigureServer(x); x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(1000)); } @@ -54,12 +56,15 @@ private void ConfigureClient(DebugAdapterClientOptions options) { } - private void ConfigureServer(DebugAdapterServerOptions options) => + private void ConfigureServer(DebugAdapterServerOptions options) + { options.OnCompletions( - async (x, ct) => { + async (x, ct) => + { await Task.Delay(50000, ct); return new CompletionsResponse(); } ); + } } } diff --git a/test/Generation.Tests/AutoImplementParamsGeneratorTests.cs b/test/Generation.Tests/AutoImplementParamsGeneratorTests.cs index 7d5298c70..3565b53ae 100644 --- a/test/Generation.Tests/AutoImplementParamsGeneratorTests.cs +++ b/test/Generation.Tests/AutoImplementParamsGeneratorTests.cs @@ -30,6 +30,8 @@ public partial class DeclarationParams : TextDocumentPositionParams, IWorkDonePr using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; +using Newtonsoft.Json; +using System.ComponentModel; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace Test diff --git a/test/Generation.Tests/EnumLikeStringGeneratorTests.cs b/test/Generation.Tests/EnumLikeStringGeneratorTests.cs index ea2e0b94a..320a396fc 100644 --- a/test/Generation.Tests/EnumLikeStringGeneratorTests.cs +++ b/test/Generation.Tests/EnumLikeStringGeneratorTests.cs @@ -39,7 +39,7 @@ namespace Test { private static readonly Lazy> _defaults = new Lazy>(() => { - return typeof(ThreadEventReason).GetProperties(BindingFlags.Static | BindingFlags.Public).Where(z => z.Name != nameof(Defaults)).Select(z => z.GetValue(null)).Cast().ToArray(); + return new ThreadEventReason[]{Started, Exited}; }); public static IEnumerable Defaults => _defaults.Value; private readonly string _value; diff --git a/test/Generation.Tests/GeneratedRegistrationOptionsTests.cs b/test/Generation.Tests/GeneratedRegistrationOptionsTests.cs index 02ecefce5..4c22321db 100644 --- a/test/Generation.Tests/GeneratedRegistrationOptionsTests.cs +++ b/test/Generation.Tests/GeneratedRegistrationOptionsTests.cs @@ -1,6 +1,5 @@ using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc.Generators; -using TestingUtils; using Xunit; namespace Generation.Tests @@ -60,6 +59,7 @@ public partial class StaticOptions : OmniSharp.Extensions.LanguageServer.Protoco #nullable restore"; await GenerationHelpers.AssertGeneratedAsExpected(source, expected); } + [Fact] public async Task Supports_Generating_Strongly_Typed_WorkDone_Registration_Options_Interface() { diff --git a/test/Generation.Tests/GenerationHelpers.cs b/test/Generation.Tests/GenerationHelpers.cs index 7f5f38918..5dc0da1a2 100644 --- a/test/Generation.Tests/GenerationHelpers.cs +++ b/test/Generation.Tests/GenerationHelpers.cs @@ -11,13 +11,13 @@ using Microsoft.CodeAnalysis.Text; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.DebugAdapter.Protocol.Client; -//using OmniSharp.Extensions.DebugAdapter.Protocol.Client; using OmniSharp.Extensions.JsonRpc.Generation; -using OmniSharp.Extensions.JsonRpc.Generators; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -//using OmniSharp.Extensions.LanguageServer.Protocol.Server; using Xunit; +//using OmniSharp.Extensions.DebugAdapter.Protocol.Client; +//using OmniSharp.Extensions.LanguageServer.Protocol.Server; + namespace Generation.Tests { public static class GenerationHelpers @@ -82,7 +82,10 @@ static GenerationHelpers() return generatedText; } - public static string NormalizeToLf(string input) => input.Replace(CrLf, Lf); + public static string NormalizeToLf(string input) + { + return input.Replace(CrLf, Lf); + } public static async Task> GenerateAsync(string source) where T : IIncrementalGenerator, new() { @@ -154,7 +157,7 @@ public static Project CreateProject(params string[] sources) } } - class NotSureWhatToCallYou : CSharpSyntaxWalker + internal class NotSureWhatToCallYou : CSharpSyntaxWalker { private readonly ISyntaxReceiver _syntaxReceiver; diff --git a/test/Generation.Tests/JsonRpcGenerationTests.cs b/test/Generation.Tests/JsonRpcGenerationTests.cs index 4c2ffe04f..496e8eed2 100644 --- a/test/Generation.Tests/JsonRpcGenerationTests.cs +++ b/test/Generation.Tests/JsonRpcGenerationTests.cs @@ -1,8 +1,6 @@ -using System; using System.Threading.Tasks; using FluentAssertions; using OmniSharp.Extensions.JsonRpc.Generators; -using TestingUtils; using Xunit; using Xunit.Sdk; using static Generation.Tests.GenerationHelpers; @@ -205,7 +203,7 @@ public interface IExitHandler : IJsonRpcNotificationHandler } }"; - Func a = () => AssertGeneratedAsExpected(source, ""); + var a = () => AssertGeneratedAsExpected(source, ""); await a.Should().ThrowAsync().WithMessage("*Could not infer the request router(s)*"); await a.Should().ThrowAsync("cache").WithMessage("*Could not infer the request router(s)*"); } diff --git a/test/Generation.Tests/LspFeatureTests.cs b/test/Generation.Tests/LspFeatureTests.cs index 04b2377ef..da2ff3dec 100644 --- a/test/Generation.Tests/LspFeatureTests.cs +++ b/test/Generation.Tests/LspFeatureTests.cs @@ -1,6 +1,5 @@ using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc.Generators; -using TestingUtils; using Xunit; namespace Generation.Tests diff --git a/test/Generation.Tests/TypedCanBeResolvedTests.cs b/test/Generation.Tests/TypedCanBeResolvedTests.cs index e34a0b47c..2544f5fd7 100644 --- a/test/Generation.Tests/TypedCanBeResolvedTests.cs +++ b/test/Generation.Tests/TypedCanBeResolvedTests.cs @@ -1,6 +1,5 @@ using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc.Generators; -using TestingUtils; using Xunit; namespace Generation.Tests diff --git a/test/JsonRpc.Tests/HandlerResolverTests.cs b/test/JsonRpc.Tests/HandlerResolverTests.cs index db0b069b5..d9d706558 100644 --- a/test/JsonRpc.Tests/HandlerResolverTests.cs +++ b/test/JsonRpc.Tests/HandlerResolverTests.cs @@ -2,7 +2,6 @@ using System.Linq; using DryIoc; using FluentAssertions; -using FluentAssertions.Common; using MediatR; using NSubstitute; using OmniSharp.Extensions.JsonRpc; @@ -45,8 +44,14 @@ public interface IJsonRpcNotificationDataHandler : IJsonRpcNotificationHandler(), new AssemblyScanningHandlerTypeDescriptorProvider(new [] { typeof(AssemblyScanningHandlerTypeDescriptorProvider).Assembly, typeof(HandlerResolverTests).Assembly })) { - (IJsonRpcHandler) Substitute.For(new[] { requestHandler }, Array.Empty()) + var handler = new HandlerCollection( + Substitute.For(), + new AssemblyScanningHandlerTypeDescriptorProvider( + new[] { typeof(AssemblyScanningHandlerTypeDescriptorProvider).Assembly, typeof(HandlerResolverTests).Assembly } + ) + ) + { + (IJsonRpcHandler)Substitute.For(new[] { requestHandler }, Array.Empty()) }; handler.Should().Contain(x => x.Method == key); } @@ -57,8 +62,14 @@ public void Should_Contain_AllDefinedMethods(Type requestHandler, string key) [InlineData(typeof(IJsonRpcNotificationDataHandler), "notificationdata", null)] public void Should_Have_CorrectParams(Type requestHandler, string key, Type expected) { - var handler = new HandlerCollection(Substitute.For(), new AssemblyScanningHandlerTypeDescriptorProvider(new [] { typeof(AssemblyScanningHandlerTypeDescriptorProvider).Assembly, typeof(HandlerResolverTests).Assembly })) { - (IJsonRpcHandler) Substitute.For(new[] { requestHandler }, Array.Empty()) + var handler = new HandlerCollection( + Substitute.For(), + new AssemblyScanningHandlerTypeDescriptorProvider( + new[] { typeof(AssemblyScanningHandlerTypeDescriptorProvider).Assembly, typeof(HandlerResolverTests).Assembly } + ) + ) + { + (IJsonRpcHandler)Substitute.For(new[] { requestHandler }, Array.Empty()) }; handler.First(x => x.Method == key).Params.Should().Be(expected); } diff --git a/test/JsonRpc.Tests/InputHandlerTests.cs b/test/JsonRpc.Tests/InputHandlerTests.cs index 6efb24bdf..ba93492d7 100644 --- a/test/JsonRpc.Tests/InputHandlerTests.cs +++ b/test/JsonRpc.Tests/InputHandlerTests.cs @@ -2,7 +2,6 @@ using System.IO; using System.IO.Pipelines; using System.Linq; -using System.Reactive.Concurrency; using System.Reflection; using System.Text; using System.Threading; @@ -27,7 +26,10 @@ public class InputHandlerTests private readonly TestLoggerFactory _loggerFactory; private readonly OnUnhandledExceptionHandler _unhandledException = Substitute.For(); - public InputHandlerTests(ITestOutputHelper testOutputHelper) => _loggerFactory = new TestLoggerFactory(testOutputHelper); + public InputHandlerTests(ITestOutputHelper testOutputHelper) + { + _loggerFactory = new TestLoggerFactory(testOutputHelper); + } private InputHandler NewHandler( PipeReader inputStream, @@ -37,8 +39,9 @@ private InputHandler NewHandler( ILoggerFactory loggerFactory, IResponseRouter responseRouter, RequestInvoker requestInvoker - ) => - new InputHandler( + ) + { + return new InputHandler( inputStream, outputHandler, receiver, @@ -49,6 +52,7 @@ RequestInvoker requestInvoker _unhandledException, null ); + } [Fact] public async Task Should_Pass_In_Requests() @@ -258,7 +262,9 @@ public async Task Should_Handle_Multiple_Chunked_Requests(string content) [Fact] public async Task Should_Handle_Header_Terminiator_Being_Incomplete() { - var pipe = new Pipe(new PipeOptions(readerScheduler: PipeScheduler.ThreadPool, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false)); + var pipe = new Pipe( + new PipeOptions(readerScheduler: PipeScheduler.ThreadPool, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false) + ); var outputHandler = Substitute.For(); var receiver = Substitute.For(); @@ -407,7 +413,8 @@ public JsonRpcLogs() var msgTypes = data .Select( - z => { + z => + { if (z.MsgKind.EndsWith("response")) { return ( type: "response", kind: z.MsgType ); @@ -426,7 +433,7 @@ public JsonRpcLogs() return ( type: null, kind: null ); } ) - .Where(z => z.type != null) + .Where(z => z.type != null!) .ToLookup(z => z.kind!, z => z.type!); Add(streamName, () => CreateReader(data), msgTypes!); @@ -446,7 +453,8 @@ private PipeReader CreateReader(DataItem[] data) { var outputData = data .Select( - z => { + z => + { if (z.MsgKind.EndsWith("response")) { return new OutgoingResponse(z.MsgId, z.Arg, new Request(z.MsgId, z.MsgType, JValue.CreateNull())); @@ -454,7 +462,8 @@ private PipeReader CreateReader(DataItem[] data) if (z.MsgKind.EndsWith("request")) { - return new OutgoingRequest { + return new OutgoingRequest + { Id = z.MsgId, Method = z.MsgType, Params = z.Arg @@ -463,7 +472,8 @@ private PipeReader CreateReader(DataItem[] data) if (z.MsgKind.EndsWith("notification")) { - return new OutgoingNotification { + return new OutgoingNotification + { Method = z.MsgType, Params = z.Arg }; @@ -478,7 +488,8 @@ private PipeReader CreateReader(DataItem[] data) var serializer = new JsonRpcSerializer(); Task.Run( - async () => { + async () => + { foreach (var item in outputData) { var content = serializer.SerializeObject(item); diff --git a/test/JsonRpc.Tests/IntegrationTests.cs b/test/JsonRpc.Tests/IntegrationTests.cs index 5d912722b..37d5b4341 100644 --- a/test/JsonRpc.Tests/IntegrationTests.cs +++ b/test/JsonRpc.Tests/IntegrationTests.cs @@ -9,7 +9,6 @@ using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.JsonRpc.Testing; -using TestingUtils; using Xunit; using Xunit.Abstractions; @@ -50,13 +49,16 @@ public async Task Should_throw_when_sending_requests() { var (client, server) = await Initialize( clientOptions => { clientOptions.OnRequest("myrequest", async (Request request) => new Data { Value = "myresponse" }); }, - serverOptions => { serverOptions.OnRequest("myrequest", async (Request request) => new Data { Value = string.Join("", "myresponse".Reverse()) }); } + serverOptions => + { + serverOptions.OnRequest("myrequest", async (Request request) => new Data { Value = string.Join("", "myresponse".Reverse()) }); + } ); - Func clientRequest = () => client.SendRequest("myrequest", (Request) null!).Returning(CancellationToken); + Func clientRequest = () => client.SendRequest("myrequest", (Request)null!).Returning(CancellationToken); await clientRequest.Should().ThrowAsync(); - Func serverRequest = () => server.SendRequest("myrequest", (Request) null!).Returning(CancellationToken); + Func serverRequest = () => server.SendRequest("myrequest", (Request)null!).Returning(CancellationToken); await serverRequest.Should().ThrowAsync(); } @@ -64,8 +66,8 @@ public async Task Should_throw_when_sending_requests() public async Task Should_throw_when_receiving_requests() { var (client, server) = await Initialize( - clientOptions => { clientOptions.OnRequest("myrequest", async (Request request) => (Data) null!); }, - serverOptions => { serverOptions.OnRequest("myrequest", async (Request request) => (Data) null!); } + clientOptions => { clientOptions.OnRequest("myrequest", async (Request request) => (Data)null!); }, + serverOptions => { serverOptions.OnRequest("myrequest", async (Request request) => (Data)null!); } ); Func clientRequest = () => client.SendRequest("myrequest", new Request()).Returning(CancellationToken); @@ -81,17 +83,21 @@ public async Task Should_Send_and_receive_notifications() var clientNotification = new AsyncSubject(); var serverNotification = new AsyncSubject(); var (client, server) = await Initialize( - clientOptions => { + clientOptions => + { clientOptions.OnNotification( - "mynotification", (Data data) => { + "mynotification", (Data data) => + { clientNotification.OnNext(data); clientNotification.OnCompleted(); } ); }, - serverOptions => { + serverOptions => + { serverOptions.OnNotification( - "mynotification", (Data data) => { + "mynotification", (Data data) => + { serverNotification.OnNext(data); serverNotification.OnCompleted(); } @@ -112,17 +118,21 @@ public async Task Should_Send_and_receive_notifications() public async Task Should_Send_and_cancel_requests_immediate() { var (client, server) = await Initialize( - clientOptions => { + clientOptions => + { clientOptions.OnRequest( - "myrequest", async ct => { + "myrequest", async ct => + { await Task.Delay(TimeSpan.FromMinutes(1), ct); return new Data { Value = "myresponse" }; } ); }, - serverOptions => { + serverOptions => + { serverOptions.OnRequest( - "myrequest", async ct => { + "myrequest", async ct => + { await Task.Delay(TimeSpan.FromMinutes(1), ct); return new Data { Value = string.Join("", "myresponse".Reverse()) }; } @@ -148,17 +158,21 @@ public async Task Should_Send_and_cancel_requests_immediate() public async Task Should_Send_and_cancel_requests_from_otherside() { var (client, server) = await Initialize( - clientOptions => { + clientOptions => + { clientOptions.OnRequest( - "myrequest", async ct => { + "myrequest", async ct => + { await Task.Delay(TimeSpan.FromMinutes(1), ct); return new Data { Value = "myresponse" }; } ); }, - serverOptions => { + serverOptions => + { serverOptions.OnRequest( - "myrequest", async ct => { + "myrequest", async ct => + { await Task.Delay(TimeSpan.FromMinutes(1), ct); return new Data { Value = string.Join("", "myresponse".Reverse()) }; } @@ -185,10 +199,12 @@ public async Task Should_Send_and_cancel_requests_from_otherside() public async Task Should_Cancel_Parallel_Requests_When_Options_Are_Given() { var (client, server) = await Initialize( - clientOptions => { + clientOptions => + { clientOptions.OnRequest( "parallelrequest", - async ct => { + async ct => + { await Task.Delay(TimeSpan.FromSeconds(10), ct); return new Data { Value = "myresponse" }; }, @@ -200,10 +216,12 @@ public async Task Should_Cancel_Parallel_Requests_When_Options_Are_Given() new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial } ); }, - serverOptions => { + serverOptions => + { serverOptions.OnRequest( "parallelrequest", - async ct => { + async ct => + { await Task.Delay(TimeSpan.FromSeconds(10), ct); return new Data { Value = "myresponse" }; }, @@ -236,13 +254,15 @@ public async Task Should_Cancel_Parallel_Requests_When_Options_Are_Given() public async Task Should_Link_Request_A_to_Request_B() { var (client, server) = await Initialize( - clientOptions => { + clientOptions => + { clientOptions .OnRequest("myrequest", async () => new Data { Value = "myresponse" }) .WithLink("myrequest", "myrequest2") ; }, - serverOptions => { + serverOptions => + { serverOptions .OnRequest("myrequest", async () => new Data { Value = string.Join("", "myresponse".Reverse()) }) .WithLink("myrequest", "myrequest2") diff --git a/test/JsonRpc.Tests/RecursiveResolutionTests.cs b/test/JsonRpc.Tests/RecursiveResolutionTests.cs index 4132326d4..0769ad859 100644 --- a/test/JsonRpc.Tests/RecursiveResolutionTests.cs +++ b/test/JsonRpc.Tests/RecursiveResolutionTests.cs @@ -8,7 +8,6 @@ using NSubstitute; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Testing; -using TestingUtils; using Xunit; using Xunit.Abstractions; @@ -23,7 +22,8 @@ public RecursiveResolutionTests(ITestOutputHelper testOutputHelper) : base(new J [Fact(Skip = "appears to cause a deadlock")] public async Task Server_Can_Be_Injected_Into_Handler_After_Creation_Using_Registration() { - Func a = async () => { + Func a = async () => + { var (_, server) = await Initialize( options => { }, options => { } @@ -82,7 +82,7 @@ public async Task Server_Facade_Can_Be_Injected_Into_Handler_During_Creation_Usi Func a = () => Initialize( options => { }, options => options - .AddHandler>() + .AddHandler>() ); await a.Should().NotThrowAsync(); } @@ -115,7 +115,7 @@ public class ClassRequest : IRequest } [Method(nameof(ClassRequest))] - class ClassHandler : IJsonRpcRequestHandler where T : IJsonRpcServerFacade + private class ClassHandler : IJsonRpcRequestHandler where T : IJsonRpcServerFacade { // ReSharper disable once NotAccessedField.Local private readonly T _jsonRpcServer; @@ -125,7 +125,10 @@ public ClassHandler(T jsonRpcServer) _jsonRpcServer = jsonRpcServer; } - public Task Handle(ClassRequest classRequest, CancellationToken cancellationToken) => throw new NotImplementedException(); + public Task Handle(ClassRequest classRequest, CancellationToken cancellationToken) + { + throw new NotImplementedException(); + } } [Method(nameof(InterfaceRequest))] @@ -134,7 +137,7 @@ public class InterfaceRequest : IRequest } [Method(nameof(InterfaceRequest))] - class InterfaceHandler : IJsonRpcRequestHandler where T : IJsonRpcServerFacade + private class InterfaceHandler : IJsonRpcRequestHandler where T : IJsonRpcServerFacade { // ReSharper disable once NotAccessedField.Local private readonly T _jsonRpcServer; @@ -144,7 +147,10 @@ public InterfaceHandler(T jsonRpcServer) _jsonRpcServer = jsonRpcServer; } - public Task Handle(InterfaceRequest request, CancellationToken cancellationToken) => throw new NotImplementedException(); + public Task Handle(InterfaceRequest request, CancellationToken cancellationToken) + { + throw new NotImplementedException(); + } } } } diff --git a/test/Lsp.Integration.Tests/ActivityTracingTests.cs b/test/Lsp.Integration.Tests/ActivityTracingTests.cs index 6e9547cc9..4ce70d497 100644 --- a/test/Lsp.Integration.Tests/ActivityTracingTests.cs +++ b/test/Lsp.Integration.Tests/ActivityTracingTests.cs @@ -1,7 +1,6 @@ using System; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Testing; @@ -10,7 +9,7 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class ActivityTracingTests : LanguageProtocolTestBase { @@ -46,10 +45,10 @@ public async Task Should_Have_Activity_Information_Exchanging_Data() var (client, server) = await Initialize( options => options .WithActivityTracingStrategy(clientStub) - .OnRequest("test", (Func) ( ct => Task.CompletedTask )), + .OnRequest("test", (Func)( ct => Task.CompletedTask )), options => options .WithActivityTracingStrategy(serverStub) - .OnRequest("test", (Func) ( ct => Task.CompletedTask )) + .OnRequest("test", (Func)( ct => Task.CompletedTask )) ); await client.SendRequest("test").ReturningVoid(CancellationToken); diff --git a/test/Lsp.Integration.Tests/ConnectionAndDisconnectionTests.cs b/test/Lsp.Integration.Tests/ConnectionAndDisconnectionTests.cs index 7ccfd30b7..09733cf6b 100644 --- a/test/Lsp.Integration.Tests/ConnectionAndDisconnectionTests.cs +++ b/test/Lsp.Integration.Tests/ConnectionAndDisconnectionTests.cs @@ -7,12 +7,12 @@ using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Server; -using TestingUtils; using Xunit; using Xunit.Abstractions; + #pragma warning disable CS0162 -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class ConnectionAndDisconnectionTests : LanguageProtocolTestBase { @@ -30,7 +30,7 @@ public async Task Server_Should_Stay_Alive_When_Requests_Throw_An_Exception() var result = await client.SendRequest("keepalive").Returning(CancellationToken); result.Should().BeTrue(); - Func a = () => client.SendRequest("throw").ReturningVoid(CancellationToken); + var a = () => client.SendRequest("throw").ReturningVoid(CancellationToken); await a.Should().ThrowAsync(); result = await client.SendRequest("keepalive").Returning(CancellationToken); @@ -45,7 +45,7 @@ public async Task Client_Should_Stay_Alive_When_Requests_Throw_An_Exception() var result = await server.SendRequest("keepalive").Returning(CancellationToken); result.Should().BeTrue(); - Func a = () => server.SendRequest("throw").ReturningVoid(CancellationToken); + var a = () => server.SendRequest("throw").ReturningVoid(CancellationToken); await a.Should().ThrowAsync(); result = await server.SendRequest("keepalive").Returning(CancellationToken); @@ -60,7 +60,7 @@ public async Task Server_Should_Support_Links() var result = await client.SendRequest("ka").Returning(CancellationToken); result.Should().BeTrue(); - Func a = () => client.SendRequest("t").ReturningVoid(CancellationToken); + var a = () => client.SendRequest("t").ReturningVoid(CancellationToken); await a.Should().ThrowAsync(); result = await client.SendRequest("ka").Returning(CancellationToken); @@ -75,7 +75,7 @@ public async Task Client_Should_Support_Links() var result = await server.SendRequest("ka").Returning(CancellationToken); result.Should().BeTrue(); - Func a = () => server.SendRequest("t").ReturningVoid(CancellationToken); + var a = () => server.SendRequest("t").ReturningVoid(CancellationToken); await a.Should().ThrowAsync(); result = await server.SendRequest("ka").Returning(CancellationToken); @@ -88,7 +88,8 @@ private void ConfigureClient(LanguageClientOptions options) options.WithLink("keepalive", "ka"); options.WithLink("throw", "t"); options.OnRequest( - "throw", async ct => { + "throw", async ct => + { throw new NotSupportedException(); return Task.CompletedTask; } @@ -101,7 +102,8 @@ private void ConfigureServer(LanguageServerOptions options) options.WithLink("keepalive", "ka"); options.WithLink("throw", "t"); options.OnRequest( - "throw", async ct => { + "throw", async ct => + { throw new NotSupportedException(); return Task.CompletedTask; } diff --git a/test/Lsp.Integration.Tests/CustomRequestsTests.cs b/test/Lsp.Integration.Tests/CustomRequestsTests.cs index 042480be5..e6316fd9a 100644 --- a/test/Lsp.Integration.Tests/CustomRequestsTests.cs +++ b/test/Lsp.Integration.Tests/CustomRequestsTests.cs @@ -13,7 +13,7 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class CustomRequestsTests : LanguageProtocolTestBase { @@ -27,7 +27,8 @@ public async Task Should_Support_Custom_Telemetry_Using_Base_Class() var fake = Substitute.For>(); var (_, server) = await Initialize(options => { options.AddHandler(fake); }, options => { }); - var @event = new CustomTelemetryEventParams { + var @event = new CustomTelemetryEventParams + { CodeFolding = true, ProfileLoading = false, ScriptAnalysis = true, @@ -51,7 +52,8 @@ public async Task Should_Support_Custom_Telemetry_Receiving_Regular_Telemetry_Us var fake = Substitute.For(); var (_, server) = await Initialize(options => { options.AddHandler(fake); }, options => { }); - var @event = new CustomTelemetryEventParams { + var @event = new CustomTelemetryEventParams + { CodeFolding = true, ProfileLoading = false, ScriptAnalysis = true, @@ -78,8 +80,10 @@ public async Task Should_Support_Custom_Telemetry_Using_Extension_Data_Using_Bas var (_, server) = await Initialize(options => { options.AddHandler(fake); }, options => { }); server.SendTelemetryEvent( - new TelemetryEventParams { - ExtensionData = new Dictionary { + new TelemetryEventParams + { + ExtensionData = new Dictionary + { ["CodeFolding"] = true, ["ProfileLoading"] = false, ["ScriptAnalysis"] = true, @@ -106,7 +110,8 @@ public async Task Should_Support_Custom_Telemetry_Using_Delegate() var fake = Substitute.For>(); var (_, server) = await Initialize(options => { options.OnTelemetryEvent(fake); }, options => { }); - var @event = new CustomTelemetryEventParams { + var @event = new CustomTelemetryEventParams + { CodeFolding = true, ProfileLoading = false, ScriptAnalysis = true, @@ -130,7 +135,8 @@ public async Task Should_Support_Custom_Telemetry_Receiving_Regular_Telemetry_Us var fake = Substitute.For>(); var (_, server) = await Initialize(options => { options.OnTelemetryEvent(fake); }, options => { }); - var @event = new CustomTelemetryEventParams { + var @event = new CustomTelemetryEventParams + { CodeFolding = true, ProfileLoading = false, ScriptAnalysis = true, @@ -157,8 +163,10 @@ public async Task Should_Support_Custom_Telemetry_Using_Extension_Data_Using_Del var (_, server) = await Initialize(options => { options.OnTelemetryEvent(fake); }, options => { }); server.SendTelemetryEvent( - new TelemetryEventParams { - ExtensionData = new Dictionary { + new TelemetryEventParams + { + ExtensionData = new Dictionary + { ["CodeFolding"] = true, ["ProfileLoading"] = false, ["ScriptAnalysis"] = true, diff --git a/test/Lsp.Integration.Tests/DisableDefaultsTests.cs b/test/Lsp.Integration.Tests/DisableDefaultsTests.cs index 87a0998f1..12dae2e72 100644 --- a/test/Lsp.Integration.Tests/DisableDefaultsTests.cs +++ b/test/Lsp.Integration.Tests/DisableDefaultsTests.cs @@ -21,7 +21,7 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class DisableDefaultsTests : LanguageProtocolTestBase { @@ -55,7 +55,7 @@ public async Task Should_Disable_Workspace_Folder_Manager() var serverAction = Substitute.For>(); var (client, server) = await Initialize( options => options.OnWorkspaceFolders(clientAction), - options => options.OnDidChangeWorkspaceFolders(serverAction, x => new () { Supported = x.Workspace?.WorkspaceFolders.IsSupported == true}) + options => options.OnDidChangeWorkspaceFolders(serverAction, x => new() { Supported = x.Workspace?.WorkspaceFolders.IsSupported == true }) ); var clientManager = client.Services.GetRequiredService(); @@ -63,7 +63,9 @@ public async Task Should_Disable_Workspace_Folder_Manager() clientManager.Descriptors.Should().ContainSingle(f => f.Method == WorkspaceNames.WorkspaceFolders); var serverManager = server.Services.GetRequiredService(); - serverManager.Descriptors.Should().Contain(f => f.Handler is LanguageProtocolDelegatingHandlers.Notification); + serverManager.Descriptors.Should().Contain( + f => f.Handler is LanguageProtocolDelegatingHandlers.Notification + ); serverManager.Descriptors.Should().ContainSingle(f => f.Method == WorkspaceNames.DidChangeWorkspaceFolders); } @@ -74,16 +76,17 @@ public async Task Should_Allow_Custom_Workspace_Folder_Manager_Delegate() var (client, server) = await Initialize( options => { }, options => options - .OnDidChangeWorkspaceFolders(action, x => new () { Supported = x.Workspace?.WorkspaceFolders.IsSupported == true}) + .OnDidChangeWorkspaceFolders(action, x => new() { Supported = x.Workspace?.WorkspaceFolders.IsSupported == true }) ); var config = client.Services.GetRequiredService(); - config.Update("mysection", new Dictionary() { ["data"] = "value" }); + config.Update("mysection", new Dictionary { ["data"] = "value" }); - client.WorkspaceFoldersManager.Add(new WorkspaceFolder() { Name = "foldera", Uri = "/some/path" }); + client.WorkspaceFoldersManager.Add(new WorkspaceFolder { Name = "foldera", Uri = "/some/path" }); await TestHelper.DelayUntil( - () => { + () => + { try { action.Received(1).Invoke(Arg.Any()); @@ -117,7 +120,7 @@ public async Task Should_Allow_Custom_Configuration_Delegate() var action = Substitute.For>(); var (client, server) = await Initialize( options => options - .WithCapability(new DidChangeConfigurationCapability() { DynamicRegistration = true }) + .WithCapability(new DidChangeConfigurationCapability { DynamicRegistration = true }) .WithServices(z => z.AddSingleton()), options => options .WithConfigurationSection("mysection") @@ -131,10 +134,11 @@ public async Task Should_Allow_Custom_Configuration_Delegate() serverManager.ContainsHandler(typeof(IDidChangeConfigurationHandler)).Should().BeTrue(); var config = client.Services.GetRequiredService(); - config.Update("mysection", new Dictionary() { ["data"] = "value" }); + config.Update("mysection", new Dictionary { ["data"] = "value" }); await TestHelper.DelayUntil( - () => { + () => + { try { action.Received(1).Invoke(Arg.Is(z => Equals(z.Settings, JValue.CreateNull()))); diff --git a/test/Lsp.Integration.Tests/DynamicRegistrationTests.cs b/test/Lsp.Integration.Tests/DynamicRegistrationTests.cs index d5059a3cb..f7787981d 100644 --- a/test/Lsp.Integration.Tests/DynamicRegistrationTests.cs +++ b/test/Lsp.Integration.Tests/DynamicRegistrationTests.cs @@ -4,25 +4,21 @@ using System.Reactive.Linq; using System.Threading.Tasks; using FluentAssertions; -using ImTools; -using Lsp.Tests.Integration.Fixtures; +using Lsp.Integration.Tests.Fixtures; using NSubstitute; -using NSubstitute.ReceivedExtensions; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Server; using TestingUtils; using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public static class DynamicRegistration { @@ -61,7 +57,8 @@ public async Task Should_Register_Dynamically_While_Server_Is_Running() x => x .OnCompletion( (@params, token) => Task.FromResult(new CompletionList()), - (_, _) => new CompletionRegistrationOptions { + (_, _) => new CompletionRegistrationOptions + { DocumentSelector = DocumentSelector.ForLanguage("vb") } ) @@ -110,7 +107,8 @@ public async Task Should_Unregister_Dynamically_While_Server_Is_Running() var disposable = server.Register( x => x.OnCompletion( (@params, token) => Task.FromResult(new CompletionList()), - (_, _) => new CompletionRegistrationOptions { + (_, _) => new CompletionRegistrationOptions + { DocumentSelector = DocumentSelector.ForLanguage("vb") } ) @@ -146,10 +144,13 @@ public async Task Should_Only_Register_Semantic_Tokens_Registration_Once() var tokens = Substitute.For(); tokens.CreateRegistrationOptions(Arg.Any(), Arg.Any()) .Returns(new SemanticTokensRegistrationOptions()); - var (client, server) = await Initialize(new ConfigureClient().Configure, options => { - new ConfigureServer().Configure(options); - options.AddHandler(tokens); - }); + var (client, server) = await Initialize( + new ConfigureClient().Configure, options => + { + new ConfigureServer().Configure(options); + options.AddHandler(tokens); + } + ); await TestHelper.DelayUntil( () => client.RegistrationManager.CurrentRegistrations, @@ -162,7 +163,10 @@ await TestHelper.DelayUntil( client.RegistrationManager.CurrentRegistrations.Should().ContainSingle(x => x.Method == TextDocumentNames.SemanticTokensRegistration); } - private bool SelectorMatches(Registration registration, Func documentFilter) => SelectorMatches(registration.RegisterOptions!, documentFilter); + private bool SelectorMatches(Registration registration, Func documentFilter) + { + return SelectorMatches(registration.RegisterOptions!, documentFilter); + } private bool SelectorMatches(object options, Func documentFilter) { @@ -193,9 +197,11 @@ public async Task Should_Gather_Static_Registrations() { var (client, _) = await Initialize( new ConfigureClient().Configure, - options => { + options => + { new ConfigureServer().Configure(options); - var semanticRegistrationOptions = new SemanticTokensRegistrationOptions { + var semanticRegistrationOptions = new SemanticTokensRegistrationOptions + { Id = Guid.NewGuid().ToString(), Legend = new SemanticTokensLegend(), Full = new SemanticTokensCapabilityRequestFull { Delta = true }, @@ -206,8 +212,10 @@ public async Task Should_Gather_Static_Registrations() // Our server only statically registers when it detects a server that does not support dynamic capabilities // This forces it to do that. options.OnInitialized( - (server, request, response, token) => { - response.Capabilities.SemanticTokensProvider = new SemanticTokensRegistrationOptions.StaticOptions { Id = semanticRegistrationOptions.Id }; + (server, request, response, token) => + { + response.Capabilities.SemanticTokensProvider = new SemanticTokensRegistrationOptions.StaticOptions + { Id = semanticRegistrationOptions.Id }; return Task.CompletedTask; } ); @@ -227,35 +235,42 @@ await TestHelper.DelayUntil( public async Task Should_Register_Static_When_Dynamic_Is_Disabled() { var (client, server) = await Initialize( - options => { + options => + { new ConfigureClient().Configure(options); options.DisableDynamicRegistration(); }, new ConfigureServer().Configure ); client.ServerSettings.Capabilities.CompletionProvider.Should().BeEquivalentTo( - new CompletionRegistrationOptions.StaticOptions { + new CompletionRegistrationOptions.StaticOptions + { ResolveProvider = true, TriggerCharacters = new Container("a", "b"), AllCommitCharacters = new Container("1", "2"), }, x => x.Excluding(z => z.WorkDoneProgress) ); server.ClientSettings.Capabilities!.TextDocument!.Completion.Value.Should().BeEquivalentTo( - new CompletionCapability { - CompletionItem = new CompletionItemCapabilityOptions { + new CompletionCapability + { + CompletionItem = new CompletionItemCapabilityOptions + { DeprecatedSupport = true, DocumentationFormat = new[] { MarkupKind.Markdown }, PreselectSupport = true, SnippetSupport = true, - TagSupport = new CompletionItemTagSupportCapabilityOptions { - ValueSet = new[] { + TagSupport = new CompletionItemTagSupportCapabilityOptions + { + ValueSet = new[] + { CompletionItemTag.Deprecated } }, CommitCharactersSupport = true }, ContextSupport = true, - CompletionItemKind = new CompletionItemKindCapabilityOptions { + CompletionItemKind = new CompletionItemKindCapabilityOptions + { ValueSet = new Container( Enum.GetValues(typeof(CompletionItemKind)) .Cast() @@ -264,21 +279,26 @@ public async Task Should_Register_Static_When_Dynamic_Is_Disabled() }, x => x.ConfigureForSupports().Excluding(z => z.DynamicRegistration) ); client.ClientSettings.Capabilities!.TextDocument!.Completion.Value.Should().BeEquivalentTo( - new CompletionCapability { - CompletionItem = new CompletionItemCapabilityOptions { + new CompletionCapability + { + CompletionItem = new CompletionItemCapabilityOptions + { DeprecatedSupport = true, DocumentationFormat = new[] { MarkupKind.Markdown }, PreselectSupport = true, SnippetSupport = true, - TagSupport = new CompletionItemTagSupportCapabilityOptions { - ValueSet = new[] { + TagSupport = new CompletionItemTagSupportCapabilityOptions + { + ValueSet = new[] + { CompletionItemTag.Deprecated } }, CommitCharactersSupport = true }, ContextSupport = true, - CompletionItemKind = new CompletionItemKindCapabilityOptions { + CompletionItemKind = new CompletionItemKindCapabilityOptions + { ValueSet = new Container( Enum.GetValues(typeof(CompletionItemKind)) .Cast() @@ -298,21 +318,26 @@ public void Configure(LanguageClientOptions options) { options.EnableDynamicRegistration(); options.WithCapability( - new CompletionCapability { - CompletionItem = new CompletionItemCapabilityOptions { + new CompletionCapability + { + CompletionItem = new CompletionItemCapabilityOptions + { DeprecatedSupport = true, DocumentationFormat = new[] { MarkupKind.Markdown }, PreselectSupport = true, SnippetSupport = true, - TagSupport = new CompletionItemTagSupportCapabilityOptions { - ValueSet = new[] { + TagSupport = new CompletionItemTagSupportCapabilityOptions + { + ValueSet = new[] + { CompletionItemTag.Deprecated } }, CommitCharactersSupport = true }, ContextSupport = true, - CompletionItemKind = new CompletionItemKindCapabilityOptions { + CompletionItemKind = new CompletionItemKindCapabilityOptions + { ValueSet = new Container( Enum.GetValues(typeof(CompletionItemKind)) .Cast() @@ -322,7 +347,8 @@ public void Configure(LanguageClientOptions options) ); options.WithCapability( - new SemanticTokensCapability { + new SemanticTokensCapability + { TokenModifiers = SemanticTokenModifier.Defaults.ToArray(), TokenTypes = SemanticTokenType.Defaults.ToArray() } @@ -336,7 +362,8 @@ public void Configure(LanguageServerOptions options) { options.OnCompletion( (@params, token) => Task.FromResult(new CompletionList()), - (_, _) => new CompletionRegistrationOptions { + (_, _) => new CompletionRegistrationOptions + { DocumentSelector = DocumentSelector.ForLanguage("csharp"), ResolveProvider = true, TriggerCharacters = new Container("a", "b"), diff --git a/test/Lsp.Integration.Tests/ErroringHandlingTests.cs b/test/Lsp.Integration.Tests/ErroringHandlingTests.cs index cc8edf89a..ef8b12034 100644 --- a/test/Lsp.Integration.Tests/ErroringHandlingTests.cs +++ b/test/Lsp.Integration.Tests/ErroringHandlingTests.cs @@ -1,5 +1,4 @@ using System; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using NSubstitute; @@ -8,14 +7,13 @@ using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Protocol; -using OmniSharp.Extensions.LanguageServer.Server; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using TestingUtils; +using OmniSharp.Extensions.LanguageServer.Server; using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class ErroringHandlingTests : LanguageProtocolTestBase { @@ -28,15 +26,19 @@ public async Task Should_Handle_Malformed_Request() { var (client, server) = await Initialize(ConfigureClient, ConfigureServer); - var codeActionParams = new { - Range = new { + var codeActionParams = new + { + Range = new + { Start = new { Line = 1, Character = double.Parse("1.0E300") }, End = new { Line = 2, Character = 9999999999999999999 } }, - TextDocument = new { + TextDocument = new + { Uri = DocumentUri.From("/path/to/file") }, - Context = new { + Context = new + { Diagnostics = new Container() } }; @@ -51,22 +53,27 @@ public async Task Should_Handle_Malformed_Notification() { var (client, server) = await Initialize(ConfigureClient, ConfigureServer); - var notification = new { - ContentChanges = new[] { - new { + var notification = new + { + ContentChanges = new[] + { + new + { Text = "Text change", - Range = new { + Range = new + { Start = new { Line = 1, Character = double.Parse("1.0E300") }, End = new { Line = 2, Character = 9999999999999999999 } }, } }, - TextDocument = new { + TextDocument = new + { Uri = DocumentUri.From("/path/to/file") }, }; - Action a = () => client.SendNotification(TextDocumentNames.DidChange, notification); + var a = () => client.SendNotification(TextDocumentNames.DidChange, notification); a.Should().NotThrow(); } @@ -77,7 +84,9 @@ private void ConfigureClient(LanguageClientOptions options) private void ConfigureServer(LanguageServerOptions options) { - options.OnCodeAction(@params => Task.FromResult(new CommandOrCodeActionContainer()), (capability, capabilities) => new CodeActionRegistrationOptions()); + options.OnCodeAction( + @params => Task.FromResult(new CommandOrCodeActionContainer()), (capability, capabilities) => new CodeActionRegistrationOptions() + ); } } } diff --git a/test/Lsp.Integration.Tests/EventingTests.cs b/test/Lsp.Integration.Tests/EventingTests.cs index 1a9cc5164..482b409a5 100644 --- a/test/Lsp.Integration.Tests/EventingTests.cs +++ b/test/Lsp.Integration.Tests/EventingTests.cs @@ -10,16 +10,14 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; using OmniSharp.Extensions.LanguageServer.Server; using Serilog.Events; -using TestingUtils; using Xunit; using Xunit.Abstractions; -using Arg = NSubstitute.Arg; + // ReSharper disable SuspiciousTypeConversion.Global -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class EventingTests : LanguageProtocolTestBase { @@ -59,12 +57,14 @@ public async Task Initialize_Delegate_Is_Supported() public async Task Initialize_Interface_Is_Supported_On_Handlers() { var onLanguageClientInitialize = - (IOnLanguageClientInitialize) Substitute.For(new[] { typeof(IOnLanguageClientInitialize), typeof(PublishDiagnosticsHandlerBase) }, Array.Empty()); + (IOnLanguageClientInitialize)Substitute.For( + new[] { typeof(IOnLanguageClientInitialize), typeof(PublishDiagnosticsHandlerBase) }, Array.Empty() + ); var onLanguageServerInitialize = - (IOnLanguageServerInitialize) Substitute.For(new[] { typeof(IOnLanguageServerInitialize), typeof(CompletionHandlerBase) }, new object[] { }); + (IOnLanguageServerInitialize)Substitute.For(new[] { typeof(IOnLanguageServerInitialize), typeof(CompletionHandlerBase) }, new object[] { }); var (client, server) = await Initialize( - options => options.AddHandler((IJsonRpcHandler) onLanguageClientInitialize!), - options => options.AddHandler((IJsonRpcHandler) onLanguageServerInitialize!) + options => options.AddHandler((IJsonRpcHandler)onLanguageClientInitialize), + options => options.AddHandler((IJsonRpcHandler)onLanguageServerInitialize) ); await onLanguageClientInitialize.Received(1).OnInitialize(client, client.ClientSettings, Arg.Any()); @@ -75,16 +75,18 @@ public async Task Initialize_Interface_Is_Supported_On_Handlers() public async Task Initialize_Interface_Is_Supported_On_Handlers_After_Startup() { var onLanguageClientInitialize = - (IOnLanguageClientInitialize) Substitute.For(new[] { typeof(IOnLanguageClientInitialize), typeof(PublishDiagnosticsHandlerBase) }, Array.Empty()); + (IOnLanguageClientInitialize)Substitute.For( + new[] { typeof(IOnLanguageClientInitialize), typeof(PublishDiagnosticsHandlerBase) }, Array.Empty() + ); var onLanguageServerInitialize = - (IOnLanguageServerInitialize) Substitute.For(new[] { typeof(IOnLanguageServerInitialize), typeof(CompletionHandlerBase) }, new object[] { }); + (IOnLanguageServerInitialize)Substitute.For(new[] { typeof(IOnLanguageServerInitialize), typeof(CompletionHandlerBase) }, new object[] { }); var (client, server) = await Initialize(o => { }, o => { }); await onLanguageClientInitialize.Received(0).OnInitialize(client, client.ClientSettings, Arg.Any()); await onLanguageServerInitialize.Received(0).OnInitialize(server, server.ClientSettings, Arg.Any()); - client.Register(r => r.AddHandler((IJsonRpcHandler) onLanguageClientInitialize!)); - server.Register(r => r.AddHandler((IJsonRpcHandler) onLanguageServerInitialize!)); + client.Register(r => r.AddHandler((IJsonRpcHandler)onLanguageClientInitialize)); + server.Register(r => r.AddHandler((IJsonRpcHandler)onLanguageServerInitialize)); await onLanguageClientInitialize.Received(1).OnInitialize(client, client.ClientSettings, Arg.Any()); await onLanguageServerInitialize.Received(1).OnInitialize(server, server.ClientSettings, Arg.Any()); @@ -122,12 +124,14 @@ public async Task Initialized_Delegate_Is_Supported() public async Task Initialized_Interface_Is_Supported_On_Handlers() { var onLanguageClientInitialized = - (IOnLanguageClientInitialized) Substitute.For(new[] { typeof(IOnLanguageClientInitialized), typeof(PublishDiagnosticsHandlerBase) }, Array.Empty()); + (IOnLanguageClientInitialized)Substitute.For( + new[] { typeof(IOnLanguageClientInitialized), typeof(PublishDiagnosticsHandlerBase) }, Array.Empty() + ); var onLanguageServerInitialized = - (IOnLanguageServerInitialized) Substitute.For(new[] { typeof(IOnLanguageServerInitialized), typeof(CompletionHandlerBase) }, new object[] { }); + (IOnLanguageServerInitialized)Substitute.For(new[] { typeof(IOnLanguageServerInitialized), typeof(CompletionHandlerBase) }, new object[] { }); var (client, server) = await Initialize( - options => options.AddHandler((IJsonRpcHandler) onLanguageClientInitialized!), - options => options.AddHandler((IJsonRpcHandler) onLanguageServerInitialized!) + options => options.AddHandler((IJsonRpcHandler)onLanguageClientInitialized!), + options => options.AddHandler((IJsonRpcHandler)onLanguageServerInitialized!) ); await onLanguageClientInitialized.Received(1).OnInitialized(client, client.ClientSettings, client.ServerSettings, Arg.Any()); @@ -138,16 +142,18 @@ public async Task Initialized_Interface_Is_Supported_On_Handlers() public async Task Initialized_Interface_Is_Supported_On_Handlers_After_Startup() { var onLanguageClientInitialized = - (IOnLanguageClientInitialized) Substitute.For(new[] { typeof(IOnLanguageClientInitialized), typeof(PublishDiagnosticsHandlerBase) }, Array.Empty()); + (IOnLanguageClientInitialized)Substitute.For( + new[] { typeof(IOnLanguageClientInitialized), typeof(PublishDiagnosticsHandlerBase) }, Array.Empty() + ); var onLanguageServerInitialized = - (IOnLanguageServerInitialized) Substitute.For(new[] { typeof(IOnLanguageServerInitialized), typeof(CompletionHandlerBase) }, new object[] { }); + (IOnLanguageServerInitialized)Substitute.For(new[] { typeof(IOnLanguageServerInitialized), typeof(CompletionHandlerBase) }, new object[] { }); var (client, server) = await Initialize(o => { }, o => { }); await onLanguageClientInitialized.Received(0).OnInitialized(client, client.ClientSettings, client.ServerSettings, Arg.Any()); await onLanguageServerInitialized.Received(0).OnInitialized(server, server.ClientSettings, server.ServerSettings, Arg.Any()); - client.Register(r => r.AddHandler((IJsonRpcHandler) onLanguageClientInitialized!)); - server.Register(r => r.AddHandler((IJsonRpcHandler) onLanguageServerInitialized!)); + client.Register(r => r.AddHandler((IJsonRpcHandler)onLanguageClientInitialized!)); + server.Register(r => r.AddHandler((IJsonRpcHandler)onLanguageServerInitialized!)); await onLanguageClientInitialized.Received(1).OnInitialized(client, client.ClientSettings, client.ServerSettings, Arg.Any()); await onLanguageServerInitialized.Received(1).OnInitialized(server, server.ClientSettings, server.ServerSettings, Arg.Any()); @@ -185,12 +191,14 @@ public async Task Started_Delegate_Is_Supported() public async Task Started_Interface_Is_Supported_On_Handlers() { var onLanguageClientStarted = - (IOnLanguageClientStarted) Substitute.For(new[] { typeof(IOnLanguageClientStarted), typeof(PublishDiagnosticsHandlerBase) }, Array.Empty()); + (IOnLanguageClientStarted)Substitute.For( + new[] { typeof(IOnLanguageClientStarted), typeof(PublishDiagnosticsHandlerBase) }, Array.Empty() + ); var onLanguageServerStarted = - (IOnLanguageServerStarted) Substitute.For(new[] { typeof(IOnLanguageServerStarted), typeof(CompletionHandlerBase) }, new object[] { }); + (IOnLanguageServerStarted)Substitute.For(new[] { typeof(IOnLanguageServerStarted), typeof(CompletionHandlerBase) }, new object[] { }); var (client, server) = await Initialize( - options => options.AddHandler((IJsonRpcHandler) onLanguageClientStarted!), - options => options.AddHandler((IJsonRpcHandler) onLanguageServerStarted!) + options => options.AddHandler((IJsonRpcHandler)onLanguageClientStarted!), + options => options.AddHandler((IJsonRpcHandler)onLanguageServerStarted!) ); await onLanguageClientStarted.Received(1).OnStarted(client, Arg.Any()); @@ -201,16 +209,18 @@ public async Task Started_Interface_Is_Supported_On_Handlers() public async Task Started_Interface_Is_Supported_On_Handlers_After_Startup() { var onLanguageClientStarted = - (IOnLanguageClientStarted) Substitute.For(new[] { typeof(IOnLanguageClientStarted), typeof(PublishDiagnosticsHandlerBase) }, Array.Empty()); + (IOnLanguageClientStarted)Substitute.For( + new[] { typeof(IOnLanguageClientStarted), typeof(PublishDiagnosticsHandlerBase) }, Array.Empty() + ); var onLanguageServerStarted = - (IOnLanguageServerStarted) Substitute.For(new[] { typeof(IOnLanguageServerStarted), typeof(CompletionHandlerBase) }, new object[] { }); + (IOnLanguageServerStarted)Substitute.For(new[] { typeof(IOnLanguageServerStarted), typeof(CompletionHandlerBase) }, new object[] { }); var (client, server) = await Initialize(o => { }, o => { }); await onLanguageClientStarted.Received(0).OnStarted(client, Arg.Any()); await onLanguageServerStarted.Received(0).OnStarted(server, Arg.Any()); - client.Register(r => r.AddHandler((IJsonRpcHandler) onLanguageClientStarted!)); - server.Register(r => r.AddHandler((IJsonRpcHandler) onLanguageServerStarted!)); + client.Register(r => r.AddHandler((IJsonRpcHandler)onLanguageClientStarted!)); + server.Register(r => r.AddHandler((IJsonRpcHandler)onLanguageServerStarted!)); await onLanguageClientStarted.Received(1).OnStarted(client, Arg.Any()); await onLanguageServerStarted.Received(1).OnStarted(server, Arg.Any()); diff --git a/test/Lsp.Integration.Tests/ExecuteCommandTests.cs b/test/Lsp.Integration.Tests/ExecuteCommandTests.cs index d059aa2b9..5cf75ae98 100644 --- a/test/Lsp.Integration.Tests/ExecuteCommandTests.cs +++ b/test/Lsp.Integration.Tests/ExecuteCommandTests.cs @@ -15,12 +15,11 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; using Serilog.Events; -using TestingUtils; using Xunit; using Xunit.Abstractions; using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class ExecuteCommandTests : LanguageProtocolTestBase { @@ -33,12 +32,15 @@ public async Task Should_Execute_A_Command() { var command = Substitute.For>(); var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a", 1, "2", false) } ) @@ -47,7 +49,8 @@ public async Task Should_Execute_A_Command() ); options.OnExecuteCommand( - command, (_, _) => new ExecuteCommandRegistrationOptions { + command, (_, _) => new ExecuteCommandRegistrationOptions + { Commands = new Container("execute-a") } ); @@ -71,18 +74,23 @@ public async Task Should_Execute_The_Correct_Command() var commanda = Substitute.For>(); var commandb = Substitute.For>(); var (client, _) = await Initialize( - options => { + options => + { options.WithCapability( - new ExecuteCommandCapability { + new ExecuteCommandCapability + { DynamicRegistration = false } ); - }, options => { + }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-b", 1, "2", false) } ) @@ -91,13 +99,15 @@ public async Task Should_Execute_The_Correct_Command() ); options.OnExecuteCommand( - commanda, (_, _) => new ExecuteCommandRegistrationOptions { + commanda, (_, _) => new ExecuteCommandRegistrationOptions + { Commands = new Container("execute-a") } ); options.OnExecuteCommand( - commandb, (_, _) => new ExecuteCommandRegistrationOptions { + commandb, (_, _) => new ExecuteCommandRegistrationOptions + { Commands = new Container("execute-b") } ); @@ -122,12 +132,15 @@ public async Task Should_Execute_The_Correct_Command() public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Is_Defined() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a", 1, "2", false) } ) @@ -143,7 +156,7 @@ public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Is_Defined() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().ThrowAsync(); } @@ -152,13 +165,17 @@ public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Name_Is_Given { var command = Substitute.For>(); var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionItem + { + Command = new Command + { Arguments = JArray.FromObject(new object[] { 1, "2", false }) } } @@ -168,7 +185,8 @@ public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Name_Is_Given ); options.OnExecuteCommand( - command, (_, _) => new ExecuteCommandRegistrationOptions { + command, (_, _) => new ExecuteCommandRegistrationOptions + { Commands = new Container("execute-a") } ); @@ -181,7 +199,7 @@ public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Name_Is_Given item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().ThrowAsync(); await command.Received(0).Invoke(Arg.Any()); @@ -193,12 +211,15 @@ public async Task Should_Fail_To_Execute_A_Command() var commandc = Substitute.For>(); var commandb = Substitute.For>(); var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a", 1, "2", false) } ) @@ -207,13 +228,15 @@ public async Task Should_Fail_To_Execute_A_Command() ); options.OnExecuteCommand( - commandb, (_, _) => new ExecuteCommandRegistrationOptions { + commandb, (_, _) => new ExecuteCommandRegistrationOptions + { Commands = new Container("execute-b") } ); options.OnExecuteCommand( - commandc, (_, _) => new ExecuteCommandRegistrationOptions { + commandc, (_, _) => new ExecuteCommandRegistrationOptions + { Commands = new Container("execute-c") } ); @@ -226,7 +249,7 @@ public async Task Should_Fail_To_Execute_A_Command() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().ThrowAsync(); await commandc.Received(0).Invoke(Arg.Any()); @@ -237,12 +260,15 @@ public async Task Should_Fail_To_Execute_A_Command() public async Task Should_Execute_1_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a", 1) } ) @@ -251,7 +277,8 @@ public async Task Should_Execute_1_Args() ); options.OnExecuteCommand( - "execute-a", i => { + "execute-a", i => + { i.Should().Be(1); return Task.CompletedTask; @@ -266,7 +293,7 @@ public async Task Should_Execute_1_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -274,12 +301,15 @@ public async Task Should_Execute_1_Args() public async Task Should_Execute_2_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a", 1, "2") } ) @@ -288,7 +318,8 @@ public async Task Should_Execute_2_Args() ); options.OnExecuteCommand( - "execute-a", (i, s) => { + "execute-a", (i, s) => + { i.Should().Be(1); s.Should().Be("2"); @@ -304,7 +335,7 @@ public async Task Should_Execute_2_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -312,12 +343,15 @@ public async Task Should_Execute_2_Args() public async Task Should_Execute_3_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a", 1, "2", true) } ) @@ -326,7 +360,8 @@ public async Task Should_Execute_3_Args() ); options.OnExecuteCommand( - "execute-a", (i, s, arg3) => { + "execute-a", (i, s, arg3) => + { i.Should().Be(1); s.Should().Be("2"); arg3.Should().BeTrue(); @@ -343,7 +378,7 @@ public async Task Should_Execute_3_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -351,13 +386,16 @@ public async Task Should_Execute_3_Args() public async Task Should_Execute_4_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { - Command = Command.Create("execute-a", 1, "2", true, new Range((0, 1), (1, 1))) + new CompletionItem + { + Command = Command.Create("execute-a", 1, "2", true, new Range(( 0, 1 ), ( 1, 1 ))) } ) ); @@ -365,11 +403,12 @@ public async Task Should_Execute_4_Args() ); options.OnExecuteCommand( - "execute-a", (i, s, arg3, arg4) => { + "execute-a", (i, s, arg3, arg4) => + { i.Should().Be(1); s.Should().Be("2"); arg3.Should().BeTrue(); - arg4.Should().Be(new Range((0, 1), (1, 1))); + arg4.Should().Be(new Range(( 0, 1 ), ( 1, 1 ))); return Task.CompletedTask; } @@ -383,7 +422,7 @@ public async Task Should_Execute_4_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -391,14 +430,18 @@ public async Task Should_Execute_4_Args() public async Task Should_Execute_5_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create( - "execute-a", 1, "2", true, new Range((0, 1), (1, 1)), new Dictionary { ["a"] = "123", ["b"] = "456" } + "execute-a", 1, "2", true, new Range(( 0, 1 ), ( 1, 1 )), + new Dictionary { ["a"] = "123", ["b"] = "456" } ) } ) @@ -407,11 +450,12 @@ public async Task Should_Execute_5_Args() ); options.OnExecuteCommand>( - "execute-a", (i, s, arg3, arg4, arg5) => { + "execute-a", (i, s, arg3, arg4, arg5) => + { i.Should().Be(1); s.Should().Be("2"); arg3.Should().BeTrue(); - arg4.Should().Be(new Range((0, 1), (1, 1))); + arg4.Should().Be(new Range(( 0, 1 ), ( 1, 1 ))); arg5.Should().ContainKeys("a", "b"); return Task.CompletedTask; @@ -426,7 +470,7 @@ public async Task Should_Execute_5_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -434,14 +478,18 @@ public async Task Should_Execute_5_Args() public async Task Should_Execute_6_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create( - "execute-a", 1, "2", true, new Range((0, 1), (1, 1)), new Dictionary { ["a"] = "123", ["b"] = "456" }, + "execute-a", 1, "2", true, new Range(( 0, 1 ), ( 1, 1 )), + new Dictionary { ["a"] = "123", ["b"] = "456" }, Guid.NewGuid() ) } @@ -451,11 +499,12 @@ public async Task Should_Execute_6_Args() ); options.OnExecuteCommand, Guid>( - "execute-a", (i, s, arg3, arg4, arg5, arg6) => { + "execute-a", (i, s, arg3, arg4, arg5, arg6) => + { i.Should().Be(1); s.Should().Be("2"); arg3.Should().BeTrue(); - arg4.Should().Be(new Range((0, 1), (1, 1))); + arg4.Should().Be(new Range(( 0, 1 ), ( 1, 1 ))); arg5.Should().ContainKeys("a", "b"); arg6.Should().NotBeEmpty(); @@ -471,7 +520,7 @@ public async Task Should_Execute_6_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -479,12 +528,15 @@ public async Task Should_Execute_6_Args() public async Task Should_Execute_1_With_Missing_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -493,7 +545,8 @@ public async Task Should_Execute_1_With_Missing_Args() ); options.OnExecuteCommand( - "execute-a", i => { + "execute-a", i => + { i.Should().Be(default); return Task.CompletedTask; @@ -508,7 +561,7 @@ public async Task Should_Execute_1_With_Missing_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -516,12 +569,15 @@ public async Task Should_Execute_1_With_Missing_Args() public async Task Should_Execute_2_With_Missing_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -530,7 +586,8 @@ public async Task Should_Execute_2_With_Missing_Args() ); options.OnExecuteCommand( - "execute-a", (i, s) => { + "execute-a", (i, s) => + { i.Should().Be(default); s.Should().Be(default); @@ -546,7 +603,7 @@ public async Task Should_Execute_2_With_Missing_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -554,12 +611,15 @@ public async Task Should_Execute_2_With_Missing_Args() public async Task Should_Execute_3_With_Missing_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -568,7 +628,8 @@ public async Task Should_Execute_3_With_Missing_Args() ); options.OnExecuteCommand( - "execute-a", (i, s, arg3) => { + "execute-a", (i, s, arg3) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); @@ -585,7 +646,7 @@ public async Task Should_Execute_3_With_Missing_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -593,12 +654,15 @@ public async Task Should_Execute_3_With_Missing_Args() public async Task Should_Execute_4_With_Missing_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -607,7 +671,8 @@ public async Task Should_Execute_4_With_Missing_Args() ); options.OnExecuteCommand( - "execute-a", (i, s, arg3, arg4) => { + "execute-a", (i, s, arg3, arg4) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); @@ -625,7 +690,7 @@ public async Task Should_Execute_4_With_Missing_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -633,12 +698,15 @@ public async Task Should_Execute_4_With_Missing_Args() public async Task Should_Execute_5_With_Missing_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -647,7 +715,8 @@ public async Task Should_Execute_5_With_Missing_Args() ); options.OnExecuteCommand>( - "execute-a", (i, s, arg3, arg4, arg5) => { + "execute-a", (i, s, arg3, arg4, arg5) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); @@ -666,7 +735,7 @@ public async Task Should_Execute_5_With_Missing_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -674,12 +743,15 @@ public async Task Should_Execute_5_With_Missing_Args() public async Task Should_Execute_6_With_Missing_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -688,7 +760,8 @@ public async Task Should_Execute_6_With_Missing_Args() ); options.OnExecuteCommand, Guid>( - "execute-a", (i, s, arg3, arg4, arg5, arg6) => { + "execute-a", (i, s, arg3, arg4, arg5, arg6) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); @@ -708,7 +781,7 @@ public async Task Should_Execute_6_With_Missing_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -716,12 +789,15 @@ public async Task Should_Execute_6_With_Missing_Args() public async Task Should_Execute_1_Null_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -730,7 +806,8 @@ public async Task Should_Execute_1_Null_Args() ); options.OnExecuteCommand( - "execute-a", i => { + "execute-a", i => + { i.Should().Be(default); return Task.CompletedTask; @@ -745,7 +822,7 @@ public async Task Should_Execute_1_Null_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -753,12 +830,15 @@ public async Task Should_Execute_1_Null_Args() public async Task Should_Execute_2_Null_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -767,7 +847,8 @@ public async Task Should_Execute_2_Null_Args() ); options.OnExecuteCommand( - "execute-a", (i, s) => { + "execute-a", (i, s) => + { i.Should().Be(default); s.Should().Be(default); @@ -783,7 +864,7 @@ public async Task Should_Execute_2_Null_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -791,12 +872,15 @@ public async Task Should_Execute_2_Null_Args() public async Task Should_Execute_3_Null_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -805,7 +889,8 @@ public async Task Should_Execute_3_Null_Args() ); options.OnExecuteCommand( - "execute-a", (i, s, arg3) => { + "execute-a", (i, s, arg3) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); @@ -822,7 +907,7 @@ public async Task Should_Execute_3_Null_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -830,12 +915,15 @@ public async Task Should_Execute_3_Null_Args() public async Task Should_Execute_4_Null_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -844,7 +932,8 @@ public async Task Should_Execute_4_Null_Args() ); options.OnExecuteCommand( - "execute-a", (i, s, arg3, arg4) => { + "execute-a", (i, s, arg3, arg4) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); @@ -862,7 +951,7 @@ public async Task Should_Execute_4_Null_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -870,12 +959,15 @@ public async Task Should_Execute_4_Null_Args() public async Task Should_Execute_5_Null_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -884,7 +976,8 @@ public async Task Should_Execute_5_Null_Args() ); options.OnExecuteCommand>( - "execute-a", (i, s, arg3, arg4, arg5) => { + "execute-a", (i, s, arg3, arg4, arg5) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); @@ -903,7 +996,7 @@ public async Task Should_Execute_5_Null_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } @@ -911,12 +1004,15 @@ public async Task Should_Execute_5_Null_Args() public async Task Should_Execute_6_Null_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -925,7 +1021,8 @@ public async Task Should_Execute_6_Null_Args() ); options.OnExecuteCommand, Guid>( - "execute-a", (i, s, arg3, arg4, arg5, arg6) => { + "execute-a", (i, s, arg3, arg4, arg5, arg6) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); @@ -945,7 +1042,7 @@ public async Task Should_Execute_6_Null_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command!); + var action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } } diff --git a/test/Lsp.Integration.Tests/ExecuteTypedCommandTests.cs b/test/Lsp.Integration.Tests/ExecuteTypedCommandTests.cs index 4caf445ae..b57001dc8 100644 --- a/test/Lsp.Integration.Tests/ExecuteTypedCommandTests.cs +++ b/test/Lsp.Integration.Tests/ExecuteTypedCommandTests.cs @@ -15,12 +15,11 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; using Serilog.Events; -using TestingUtils; using Xunit; using Xunit.Abstractions; using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class ExecuteTypedCommandTests : LanguageProtocolTestBase { @@ -32,14 +31,17 @@ public ExecuteTypedCommandTests(ITestOutputHelper outputHelper) : base(new JsonR public async Task Should_Execute_A_Command() { var command = Substitute.For, Task>>(); - command.Invoke(Arg.Any>()).Returns(new CommandResponse() { Value = "1234" }); + command.Invoke(Arg.Any>()).Returns(new CommandResponse { Value = "1234" }); var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a", 1, "2", false) } ) @@ -48,7 +50,8 @@ public async Task Should_Execute_A_Command() ); options.OnExecuteCommand( - command, (_, _) => new ExecuteCommandRegistrationOptions { + command, (_, _) => new ExecuteCommandRegistrationOptions + { Commands = new Container("execute-a") } ); @@ -70,22 +73,28 @@ public async Task Should_Execute_A_Command() public async Task Should_Execute_The_Correct_Command() { var commanda = Substitute.For, Task>>(); - commanda.Invoke(Arg.Any>()).Returns(new CommandResponse() { Value = "1234" }); - var commandb = Substitute.For,ExecuteCommandCapability, CancellationToken, Task>>(); - commandb.Invoke(Arg.Any>(), Arg.Any(), Arg.Any()).Returns(new CommandResponse() { Value = "4321" }); + commanda.Invoke(Arg.Any>()).Returns(new CommandResponse { Value = "1234" }); + var commandb = Substitute.For, ExecuteCommandCapability, CancellationToken, Task>>(); + commandb.Invoke(Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(new CommandResponse { Value = "4321" }); var (client, _) = await Initialize( - options => { + options => + { options.WithCapability( - new ExecuteCommandCapability { + new ExecuteCommandCapability + { DynamicRegistration = false } ); - }, options => { + }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-b", 1, "2", false) } ) @@ -94,13 +103,15 @@ public async Task Should_Execute_The_Correct_Command() ); options.OnExecuteCommand( - commanda, (_, _) => new ExecuteCommandRegistrationOptions { + commanda, (_, _) => new ExecuteCommandRegistrationOptions + { Commands = new Container("execute-a") } ); options.OnExecuteCommand( - commandb, (_, _) => new ExecuteCommandRegistrationOptions { + commandb, (_, _) => new ExecuteCommandRegistrationOptions + { Commands = new Container("execute-b") } ); @@ -117,7 +128,9 @@ public async Task Should_Execute_The_Correct_Command() response.Value.Should().Be("4321"); await commanda.Received(0).Invoke(Arg.Any>()); - await commandb.Received(1).Invoke(Arg.Any>(), Arg.Any(), Arg.Any()); + await commandb.Received(1).Invoke( + Arg.Any>(), Arg.Any(), Arg.Any() + ); var arg = commandb.ReceivedCalls().Single().GetArguments()[1]; arg.Should().BeOfType(); } @@ -125,16 +138,20 @@ public async Task Should_Execute_The_Correct_Command() [Fact] public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Name_Is_Given() { - var command = Substitute.For,Task>>(); - command.Invoke(Arg.Any>()).Returns(new CommandResponse() { Value = "1234" }); + var command = Substitute.For, Task>>(); + command.Invoke(Arg.Any>()).Returns(new CommandResponse { Value = "1234" }); var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionItem + { + Command = new Command + { Arguments = JArray.FromObject(new object[] { 1, "2", false }) } } @@ -144,7 +161,8 @@ public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Name_Is_Given ); options.OnExecuteCommand( - command, (_, _) => new ExecuteCommandRegistrationOptions { + command, (_, _) => new ExecuteCommandRegistrationOptions + { Commands = new Container("execute-a") } ); @@ -157,7 +175,7 @@ public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Name_Is_Given item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().ThrowAsync(); await command.Received(0).Invoke(Arg.Any>()); @@ -166,17 +184,20 @@ public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Name_Is_Given [Fact] public async Task Should_Fail_To_Execute_A_Command() { - var commandc = Substitute.For,Task>>(); - commandc.Invoke(Arg.Any>()).Returns(new CommandResponse() { Value = "1234" }); - var commandb = Substitute.For,Task>>(); - commandb.Invoke(Arg.Any>()).Returns(new CommandResponse() { Value = "1234" }); + var commandc = Substitute.For, Task>>(); + commandc.Invoke(Arg.Any>()).Returns(new CommandResponse { Value = "1234" }); + var commandb = Substitute.For, Task>>(); + commandb.Invoke(Arg.Any>()).Returns(new CommandResponse { Value = "1234" }); var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a", 1, "2", false) } ) @@ -185,13 +206,15 @@ public async Task Should_Fail_To_Execute_A_Command() ); options.OnExecuteCommand( - commandb, (_, _) => new ExecuteCommandRegistrationOptions { + commandb, (_, _) => new ExecuteCommandRegistrationOptions + { Commands = new Container("execute-b") } ); options.OnExecuteCommand( - commandc, (_, _) => new ExecuteCommandRegistrationOptions { + commandc, (_, _) => new ExecuteCommandRegistrationOptions + { Commands = new Container("execute-c") } ); @@ -204,7 +227,7 @@ public async Task Should_Fail_To_Execute_A_Command() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().ThrowAsync(); await commandc.Received(0).Invoke(Arg.Any>()); @@ -215,12 +238,15 @@ public async Task Should_Fail_To_Execute_A_Command() public async Task Should_Execute_1_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a", 1) } ) @@ -229,10 +255,11 @@ public async Task Should_Execute_1_Args() ); options.OnExecuteCommand( - "execute-a", i => { + "execute-a", i => + { i.Should().Be(1); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -244,7 +271,7 @@ public async Task Should_Execute_1_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -252,12 +279,15 @@ public async Task Should_Execute_1_Args() public async Task Should_Execute_2_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a", 1, "2") } ) @@ -266,11 +296,12 @@ public async Task Should_Execute_2_Args() ); options.OnExecuteCommand( - "execute-a", (i, s) => { + "execute-a", (i, s) => + { i.Should().Be(1); s.Should().Be("2"); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -290,12 +321,15 @@ public async Task Should_Execute_2_Args() public async Task Should_Execute_3_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a", 1, "2", true) } ) @@ -304,12 +338,13 @@ public async Task Should_Execute_3_Args() ); options.OnExecuteCommand( - "execute-a", (i, s, arg3) => { + "execute-a", (i, s, arg3) => + { i.Should().Be(1); s.Should().Be("2"); arg3.Should().BeTrue(); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -321,7 +356,7 @@ public async Task Should_Execute_3_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -329,13 +364,16 @@ public async Task Should_Execute_3_Args() public async Task Should_Execute_4_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { - Command = Command.Create("execute-a", 1, "2", true, new Range((0, 1), (1, 1))) + new CompletionItem + { + Command = Command.Create("execute-a", 1, "2", true, new Range(( 0, 1 ), ( 1, 1 ))) } ) ); @@ -343,13 +381,14 @@ public async Task Should_Execute_4_Args() ); options.OnExecuteCommand( - "execute-a", (i, s, arg3, arg4) => { + "execute-a", (i, s, arg3, arg4) => + { i.Should().Be(1); s.Should().Be("2"); arg3.Should().BeTrue(); - arg4.Should().Be(new Range((0, 1), (1, 1))); + arg4.Should().Be(new Range(( 0, 1 ), ( 1, 1 ))); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -361,7 +400,7 @@ public async Task Should_Execute_4_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -369,14 +408,18 @@ public async Task Should_Execute_4_Args() public async Task Should_Execute_5_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create( - "execute-a", 1, "2", true, new Range((0, 1), (1, 1)), new Dictionary { ["a"] = "123", ["b"] = "456" } + "execute-a", 1, "2", true, new Range(( 0, 1 ), ( 1, 1 )), + new Dictionary { ["a"] = "123", ["b"] = "456" } ) } ) @@ -385,14 +428,15 @@ public async Task Should_Execute_5_Args() ); options.OnExecuteCommand, CommandResponse>( - "execute-a", (i, s, arg3, arg4, arg5) => { + "execute-a", (i, s, arg3, arg4, arg5) => + { i.Should().Be(1); s.Should().Be("2"); arg3.Should().BeTrue(); - arg4.Should().Be(new Range((0, 1), (1, 1))); + arg4.Should().Be(new Range(( 0, 1 ), ( 1, 1 ))); arg5.Should().ContainKeys("a", "b"); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -404,7 +448,7 @@ public async Task Should_Execute_5_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -412,14 +456,18 @@ public async Task Should_Execute_5_Args() public async Task Should_Execute_6_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create( - "execute-a", 1, "2", true, new Range((0, 1), (1, 1)), new Dictionary { ["a"] = "123", ["b"] = "456" }, + "execute-a", 1, "2", true, new Range(( 0, 1 ), ( 1, 1 )), + new Dictionary { ["a"] = "123", ["b"] = "456" }, Guid.NewGuid() ) } @@ -429,15 +477,16 @@ public async Task Should_Execute_6_Args() ); options.OnExecuteCommand, Guid, CommandResponse>( - "execute-a", (i, s, arg3, arg4, arg5, arg6) => { + "execute-a", (i, s, arg3, arg4, arg5, arg6) => + { i.Should().Be(1); s.Should().Be("2"); arg3.Should().BeTrue(); - arg4.Should().Be(new Range((0, 1), (1, 1))); + arg4.Should().Be(new Range(( 0, 1 ), ( 1, 1 ))); arg5.Should().ContainKeys("a", "b"); arg6.Should().NotBeEmpty(); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -449,7 +498,7 @@ public async Task Should_Execute_6_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -457,12 +506,15 @@ public async Task Should_Execute_6_Args() public async Task Should_Execute_1_With_Missing_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -471,10 +523,11 @@ public async Task Should_Execute_1_With_Missing_Args() ); options.OnExecuteCommand( - "execute-a", i => { + "execute-a", i => + { i.Should().Be(default); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -486,7 +539,7 @@ public async Task Should_Execute_1_With_Missing_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -494,12 +547,15 @@ public async Task Should_Execute_1_With_Missing_Args() public async Task Should_Execute_2_With_Missing_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -508,11 +564,12 @@ public async Task Should_Execute_2_With_Missing_Args() ); options.OnExecuteCommand( - "execute-a", (i, s) => { + "execute-a", (i, s) => + { i.Should().Be(default); s.Should().Be(default); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -524,7 +581,7 @@ public async Task Should_Execute_2_With_Missing_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -532,12 +589,15 @@ public async Task Should_Execute_2_With_Missing_Args() public async Task Should_Execute_3_With_Missing_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -546,12 +606,13 @@ public async Task Should_Execute_3_With_Missing_Args() ); options.OnExecuteCommand( - "execute-a", (i, s, arg3) => { + "execute-a", (i, s, arg3) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -563,7 +624,7 @@ public async Task Should_Execute_3_With_Missing_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -571,12 +632,15 @@ public async Task Should_Execute_3_With_Missing_Args() public async Task Should_Execute_4_With_Missing_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -585,13 +649,14 @@ public async Task Should_Execute_4_With_Missing_Args() ); options.OnExecuteCommand( - "execute-a", (i, s, arg3, arg4) => { + "execute-a", (i, s, arg3, arg4) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); arg4.Should().Be(default); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -603,7 +668,7 @@ public async Task Should_Execute_4_With_Missing_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -611,12 +676,15 @@ public async Task Should_Execute_4_With_Missing_Args() public async Task Should_Execute_5_With_Missing_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -625,14 +693,15 @@ public async Task Should_Execute_5_With_Missing_Args() ); options.OnExecuteCommand, CommandResponse>( - "execute-a", (i, s, arg3, arg4, arg5) => { + "execute-a", (i, s, arg3, arg4, arg5) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); arg4.Should().Be(default); arg5.Should().BeNull(); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -644,7 +713,7 @@ public async Task Should_Execute_5_With_Missing_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -652,12 +721,15 @@ public async Task Should_Execute_5_With_Missing_Args() public async Task Should_Execute_6_With_Missing_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -666,7 +738,8 @@ public async Task Should_Execute_6_With_Missing_Args() ); options.OnExecuteCommand, Guid, CommandResponse>( - "execute-a", (i, s, arg3, arg4, arg5, arg6) => { + "execute-a", (i, s, arg3, arg4, arg5, arg6) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); @@ -674,7 +747,7 @@ public async Task Should_Execute_6_With_Missing_Args() arg5.Should().BeNull(); arg6.Should().BeEmpty(); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -686,7 +759,7 @@ public async Task Should_Execute_6_With_Missing_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -694,12 +767,15 @@ public async Task Should_Execute_6_With_Missing_Args() public async Task Should_Execute_1_Null_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -708,10 +784,11 @@ public async Task Should_Execute_1_Null_Args() ); options.OnExecuteCommand( - "execute-a", i => { + "execute-a", i => + { i.Should().Be(default); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -723,7 +800,7 @@ public async Task Should_Execute_1_Null_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -731,12 +808,15 @@ public async Task Should_Execute_1_Null_Args() public async Task Should_Execute_2_Null_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -745,11 +825,12 @@ public async Task Should_Execute_2_Null_Args() ); options.OnExecuteCommand( - "execute-a", (i, s) => { + "execute-a", (i, s) => + { i.Should().Be(default); s.Should().Be(default); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -761,7 +842,7 @@ public async Task Should_Execute_2_Null_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -769,12 +850,15 @@ public async Task Should_Execute_2_Null_Args() public async Task Should_Execute_3_Null_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -783,12 +867,13 @@ public async Task Should_Execute_3_Null_Args() ); options.OnExecuteCommand( - "execute-a", (i, s, arg3) => { + "execute-a", (i, s, arg3) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -800,7 +885,7 @@ public async Task Should_Execute_3_Null_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -808,12 +893,15 @@ public async Task Should_Execute_3_Null_Args() public async Task Should_Execute_4_Null_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -822,13 +910,14 @@ public async Task Should_Execute_4_Null_Args() ); options.OnExecuteCommand( - "execute-a", (i, s, arg3, arg4) => { + "execute-a", (i, s, arg3, arg4) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); arg4.Should().Be(default); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -840,7 +929,7 @@ public async Task Should_Execute_4_Null_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -848,12 +937,15 @@ public async Task Should_Execute_4_Null_Args() public async Task Should_Execute_5_Null_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -862,14 +954,15 @@ public async Task Should_Execute_5_Null_Args() ); options.OnExecuteCommand, CommandResponse>( - "execute-a", (i, s, arg3, arg4, arg5) => { + "execute-a", (i, s, arg3, arg4, arg5) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); arg4.Should().Be(default); arg5.Should().BeNull(); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -881,7 +974,7 @@ public async Task Should_Execute_5_Null_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } @@ -889,12 +982,15 @@ public async Task Should_Execute_5_Null_Args() public async Task Should_Execute_6_Null_Args() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - x => { + x => + { return Task.FromResult( new CompletionList( - new CompletionItem { + new CompletionItem + { Command = Command.Create("execute-a") } ) @@ -903,7 +999,8 @@ public async Task Should_Execute_6_Null_Args() ); options.OnExecuteCommand, Guid, CommandResponse>( - "execute-a", (i, s, arg3, arg4, arg5, arg6) => { + "execute-a", (i, s, arg3, arg4, arg5, arg6) => + { i.Should().Be(default); s.Should().Be(default); arg3.Should().Be(default); @@ -911,7 +1008,7 @@ public async Task Should_Execute_6_Null_Args() arg5.Should().BeNull(); arg6.Should().BeEmpty(); - return Task.FromResult(new CommandResponse() { Value = "1234" }); + return Task.FromResult(new CommandResponse { Value = "1234" }); } ); } @@ -923,7 +1020,7 @@ public async Task Should_Execute_6_Null_Args() item.Command.Should().NotBeNull(); - Func> action = () => client.ExecuteCommandWithResponse(item.Command!); + var action = () => client.ExecuteCommandWithResponse(item.Command!); await action.Should().NotThrowAsync(); } diff --git a/test/Lsp.Integration.Tests/ExtensionTests.cs b/test/Lsp.Integration.Tests/ExtensionTests.cs index 1405c7c81..5c67a0b61 100644 --- a/test/Lsp.Integration.Tests/ExtensionTests.cs +++ b/test/Lsp.Integration.Tests/ExtensionTests.cs @@ -1,27 +1,25 @@ using System; using System.Linq; -using System.Reactive.Linq; -using System.Reactive.Threading.Tasks; using System.Threading; using System.Threading.Tasks; using FluentAssertions; +using Lsp.Integration.Tests.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using Newtonsoft.Json.Linq; using NSubstitute; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Client; -using Serilog.Events; -using Xunit; -using Xunit.Abstractions; -using Lsp.Tests.Integration.Fixtures; -using Microsoft.Extensions.DependencyInjection; -using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; +using Serilog.Events; using TestingUtils; +using Xunit; +using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class ExtensionTests : LanguageProtocolTestBase { @@ -41,23 +39,26 @@ public async Task Should_Support_Custom_Capabilities() .Invoke(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var (client, server) = await Initialize( - options => { + options => + { options.UseAssemblyAttributeScanning = false; options .WithAssemblies(typeof(UnitTestCapability).Assembly) .WithCapability( - new UnitTestCapability() { + new UnitTestCapability + { DynamicRegistration = true, Property = "Abcd" } ); - }, options => { + }, options => + { options.UseAssemblyAttributeScanning = false; options - .WithAssemblies(typeof(UnitTestCapability).Assembly) - .OnDiscoverUnitTests(onDiscoverHandler, (_, _) => new UnitTestRegistrationOptions()) + .WithAssemblies(typeof(UnitTestCapability).Assembly).OnDiscoverUnitTests(onDiscoverHandler, (_, _) => new UnitTestRegistrationOptions()) .OnRunUnitTest( - onRunUnitHandler, (_, _) => new UnitTestRegistrationOptions() { + onRunUnitHandler, (_, _) => new UnitTestRegistrationOptions + { SupportsDebugging = true, WorkDoneProgress = true } @@ -86,14 +87,17 @@ public async Task Should_Support_Custom_Capabilities() } await client.RequestDiscoverUnitTests( - new DiscoverUnitTestsParams() { + new DiscoverUnitTestsParams + { PartialResultToken = new ProgressToken(1), WorkDoneToken = new ProgressToken(1), }, CancellationToken ); await client.RunUnitTest(new UnitTest(), CancellationToken); - onDiscoverHandler.Received(1).Invoke(Arg.Any(), Arg.Is(x => x.Property == "Abcd"), Arg.Any()); + onDiscoverHandler.Received(1).Invoke( + Arg.Any(), Arg.Is(x => x.Property == "Abcd"), Arg.Any() + ); onRunUnitHandler.Received(1).Invoke(Arg.Any(), Arg.Is(x => x.Property == "Abcd"), Arg.Any()); } @@ -109,11 +113,13 @@ public async Task Should_Support_Custom_Capabilities_Using_Json() .Invoke(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var (client, server) = await Initialize( - options => { + options => + { options.UseAssemblyAttributeScanning = false; - options.ClientCapabilities.Workspace!.ExtensionData["unitTests"] = JToken.FromObject(new { property = "Abcd", dynamicRegistration = true }); }, - options => { - + options.ClientCapabilities.Workspace!.ExtensionData["unitTests"] = JToken.FromObject(new { property = "Abcd", dynamicRegistration = true }); + }, + options => + { options.UseAssemblyAttributeScanning = false; options.OnDiscoverUnitTests(onDiscoverHandler, (_, _) => new UnitTestRegistrationOptions()); options.OnRunUnitTest(onRunUnitHandler, (_, _) => new UnitTestRegistrationOptions()); @@ -138,7 +144,9 @@ public async Task Should_Support_Custom_Capabilities_Using_Json() await client.RequestDiscoverUnitTests(new DiscoverUnitTestsParams(), CancellationToken); await client.RunUnitTest(new UnitTest(), CancellationToken); - onDiscoverHandler.Received(1).Invoke(Arg.Any(), Arg.Is(x => x.Property == "Abcd"), Arg.Any()); + onDiscoverHandler.Received(1).Invoke( + Arg.Any(), Arg.Is(x => x.Property == "Abcd"), Arg.Any() + ); onRunUnitHandler.Received(1).Invoke(Arg.Any(), Arg.Is(x => x.Property == "Abcd"), Arg.Any()); } @@ -148,18 +156,21 @@ public async Task Should_Support_Custom_Static_Options() var onDiscoverHandler = Substitute.For>>>(); var onRunUnitHandler = Substitute.For>(); var (_, server) = await Initialize( - options => { + options => + { options.UseAssemblyAttributeScanning = false; options.WithCapability( - new UnitTestCapability() { + new UnitTestCapability + { DynamicRegistration = false, Property = "Abcd" } ); - }, options => { + }, options => + { options.UseAssemblyAttributeScanning = false; - options.OnDiscoverUnitTests(onDiscoverHandler, (_, _) => new UnitTestRegistrationOptions() { SupportsDebugging = true }); - options.OnRunUnitTest(onRunUnitHandler, (_, _) => new UnitTestRegistrationOptions() { SupportsDebugging = true }); + options.OnDiscoverUnitTests(onDiscoverHandler, (_, _) => new UnitTestRegistrationOptions { SupportsDebugging = true }); + options.OnRunUnitTest(onRunUnitHandler, (_, _) => new UnitTestRegistrationOptions { SupportsDebugging = true }); } ); @@ -184,14 +195,18 @@ public async Task Should_Support_Custom_Static_Options() public async Task Should_Convert_Registration_Options_Into_Static_Options_As_Required() { var (client, _) = await Initialize( - options => { + options => + { options.UseAssemblyAttributeScanning = false; options.DisableDynamicRegistration(); options.WithCapability( - new CodeActionCapability() { + new CodeActionCapability + { DynamicRegistration = false, - CodeActionLiteralSupport = new CodeActionLiteralSupportOptions() { - CodeActionKind = new CodeActionKindCapabilityOptions() { + CodeActionLiteralSupport = new CodeActionLiteralSupportOptions + { + CodeActionKind = new CodeActionKindCapabilityOptions + { ValueSet = new Container( CodeActionKind.Empty, CodeActionKind.Refactor, @@ -207,11 +222,13 @@ public async Task Should_Convert_Registration_Options_Into_Static_Options_As_Req } ); }, - options => { + options => + { options.UseAssemblyAttributeScanning = false; options.OnCodeAction( (@params, capability, token) => Task.FromResult(new CommandOrCodeActionContainer()), - (_, _) => new CodeActionRegistrationOptions() { + (_, _) => new CodeActionRegistrationOptions + { CodeActionKinds = new Container( CodeActionKind.RefactorExtract, CodeActionKind.RefactorInline, diff --git a/test/Lsp.Integration.Tests/FileOperationTests.cs b/test/Lsp.Integration.Tests/FileOperationTests.cs index 6fc4fb275..94f8851de 100644 --- a/test/Lsp.Integration.Tests/FileOperationTests.cs +++ b/test/Lsp.Integration.Tests/FileOperationTests.cs @@ -15,16 +15,24 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class FileOperationTests : LanguageProtocolTestBase { private readonly Action _didCreateFileHandler = Substitute.For>(); - private readonly Func> _willCreateFileHandler = Substitute.For>>(); + + private readonly Func> _willCreateFileHandler = + Substitute.For>>(); + private readonly Action _didRenameFileHandler = Substitute.For>(); - private readonly Func> _willRenameFileHandler = Substitute.For>>(); + + private readonly Func> _willRenameFileHandler = + Substitute.For>>(); + private readonly Action _didDeleteFileHandler = Substitute.For>(); - private readonly Func> _willDeleteFileHandler = Substitute.For>>(); + + private readonly Func> _willDeleteFileHandler = + Substitute.For>>(); public FileOperationTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper, LogEventLevel.Verbose)) { @@ -36,13 +44,15 @@ public async Task Should_Handle_FileCreate() var (client, server) = await Initialize(Configure, Configure); await client.RequestWillCreateFile( - new WillCreateFileParams() { - Files = Container.From(new FileCreate() { Uri = new Uri("file://asdf") }) + new WillCreateFileParams + { + Files = Container.From(new FileCreate { Uri = new Uri("file://asdf") }) } ); client.DidCreateFile( - new DidCreateFileParams() { - Files = Container.From(new FileCreate() { Uri = new Uri("file://asdf") }) + new DidCreateFileParams + { + Files = Container.From(new FileCreate { Uri = new Uri("file://asdf") }) } ); @@ -82,13 +92,15 @@ public async Task Should_Handle_FileRename() var (client, server) = await Initialize(Configure, Configure); await client.RequestWillRenameFile( - new WillRenameFileParams() { - Files = Container.From(new FileRename() { Uri = new Uri("file://asdf") }) + new WillRenameFileParams + { + Files = Container.From(new FileRename { Uri = new Uri("file://asdf") }) } ); client.DidRenameFile( - new DidRenameFileParams() { - Files = Container.From(new FileRename() { Uri = new Uri("file://asdf") }) + new DidRenameFileParams + { + Files = Container.From(new FileRename { Uri = new Uri("file://asdf") }) } ); @@ -128,13 +140,15 @@ public async Task Should_Handle_FileDelete() var (client, server) = await Initialize(Configure, Configure); await client.RequestWillDeleteFile( - new WillDeleteFileParams() { - Files = Container.From(new FileDelete() { Uri = new Uri("file://asdf") }) + new WillDeleteFileParams + { + Files = Container.From(new FileDelete { Uri = new Uri("file://asdf") }) } ); client.DidDeleteFile( - new DidDeleteFileParams() { - Files = Container.From(new FileDelete() { Uri = new Uri("file://asdf") }) + new DidDeleteFileParams + { + Files = Container.From(new FileDelete { Uri = new Uri("file://asdf") }) } ); @@ -171,7 +185,8 @@ static void VerifyClientSettings(InitializeParams result) private void Configure(LanguageClientOptions options) { options.WithCapability( - new FileOperationsWorkspaceClientCapabilities() { + new FileOperationsWorkspaceClientCapabilities + { DidCreate = true, DidRename = true, DidDelete = true, @@ -185,11 +200,14 @@ private void Configure(LanguageClientOptions options) private void Configure(LanguageServerOptions options) { var filters = Container.From( - new FileOperationFilter() { - Scheme = "file", Pattern = new FileOperationPattern() { + new FileOperationFilter + { + Scheme = "file", Pattern = new FileOperationPattern + { Glob = "**/*.cs", Matches = FileOperationPatternKind.File, - Options = new FileOperationPatternOptions() { + Options = new FileOperationPatternOptions + { IgnoreCase = true } } diff --git a/test/Lsp.Integration.Tests/Fixtures/DefaultClient.cs b/test/Lsp.Integration.Tests/Fixtures/DefaultClient.cs index 0fdc6afb3..bea286c1b 100644 --- a/test/Lsp.Integration.Tests/Fixtures/DefaultClient.cs +++ b/test/Lsp.Integration.Tests/Fixtures/DefaultClient.cs @@ -1,10 +1,8 @@ using System; -using System.ComponentModel; -using Newtonsoft.Json; using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -namespace Lsp.Tests.Integration.Fixtures +namespace Lsp.Integration.Tests.Fixtures { public sealed class DefaultClient : IConfigureLanguageClientOptions { diff --git a/test/Lsp.Integration.Tests/Fixtures/DefaultOptions.cs b/test/Lsp.Integration.Tests/Fixtures/DefaultOptions.cs index 2cf45a9d4..6819556b8 100644 --- a/test/Lsp.Integration.Tests/Fixtures/DefaultOptions.cs +++ b/test/Lsp.Integration.Tests/Fixtures/DefaultOptions.cs @@ -1,9 +1,12 @@ using OmniSharp.Extensions.JsonRpc.Testing; -namespace Lsp.Tests.Integration.Fixtures +namespace Lsp.Integration.Tests.Fixtures { public sealed class DefaultOptions : IConfigureLanguageProtocolFixture { - public JsonRpcTestOptions Configure(JsonRpcTestOptions options) => options; + public JsonRpcTestOptions Configure(JsonRpcTestOptions options) + { + return options; + } } -} \ No newline at end of file +} diff --git a/test/Lsp.Integration.Tests/Fixtures/DefaultServer.cs b/test/Lsp.Integration.Tests/Fixtures/DefaultServer.cs index c8f37e8d4..9879d8f50 100644 --- a/test/Lsp.Integration.Tests/Fixtures/DefaultServer.cs +++ b/test/Lsp.Integration.Tests/Fixtures/DefaultServer.cs @@ -1,6 +1,6 @@ using OmniSharp.Extensions.LanguageServer.Server; -namespace Lsp.Tests.Integration.Fixtures +namespace Lsp.Integration.Tests.Fixtures { public sealed class DefaultServer : IConfigureLanguageServerOptions { diff --git a/test/Lsp.Integration.Tests/Fixtures/ExampleExtensions.cs b/test/Lsp.Integration.Tests/Fixtures/ExampleExtensions.cs index 11ec8a37a..3215b72b3 100644 --- a/test/Lsp.Integration.Tests/Fixtures/ExampleExtensions.cs +++ b/test/Lsp.Integration.Tests/Fixtures/ExampleExtensions.cs @@ -1,4 +1,3 @@ -using MediatR; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; using OmniSharp.Extensions.LanguageServer.Protocol; @@ -9,24 +8,26 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -namespace Lsp.Tests.Integration.Fixtures +namespace Lsp.Integration.Tests.Fixtures { - [Parallel, Method("tests/discover", Direction.ClientToServer)] - [ - GenerateHandler, - GenerateHandlerMethods(typeof(ILanguageServerRegistry)), - GenerateRequestMethods(typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(UnitTestRegistrationOptions)), Capability(typeof(UnitTestCapability))] - public partial class DiscoverUnitTestsParams : IPartialItemsRequest, UnitTest>, IWorkDoneProgressParams { } + [Parallel] + [Method("tests/discover", Direction.ClientToServer)] + [GenerateHandler] + [GenerateHandlerMethods(typeof(ILanguageServerRegistry))] + [GenerateRequestMethods(typeof(ILanguageClient))] + [RegistrationOptions(typeof(UnitTestRegistrationOptions))] + [Capability(typeof(UnitTestCapability))] + public partial class DiscoverUnitTestsParams : IPartialItemsRequest, UnitTest>, IWorkDoneProgressParams + { + } - [Parallel, Method("tests/run", Direction.ClientToServer)] - [ - GenerateHandler(Name = "RunUnitTest"), - GenerateHandlerMethods(typeof(ILanguageServerRegistry)), - GenerateRequestMethods(typeof(ILanguageClient)) - ] - [RegistrationOptions(typeof(UnitTestRegistrationOptions)), Capability(typeof(UnitTestCapability))] + [Parallel] + [Method("tests/run", Direction.ClientToServer)] + [GenerateHandler(Name = "RunUnitTest")] + [GenerateHandlerMethods(typeof(ILanguageServerRegistry))] + [GenerateRequestMethods(typeof(ILanguageClient))] + [RegistrationOptions(typeof(UnitTestRegistrationOptions))] + [Capability(typeof(UnitTestCapability))] public partial class UnitTest : IJsonRpcRequest, IDoesNotParticipateInRegistration { public string Name { get; set; } = null!; diff --git a/test/Lsp.Integration.Tests/Fixtures/IConfigureLanguageClientOptions.cs b/test/Lsp.Integration.Tests/Fixtures/IConfigureLanguageClientOptions.cs index 59b2e8b35..e745faadd 100644 --- a/test/Lsp.Integration.Tests/Fixtures/IConfigureLanguageClientOptions.cs +++ b/test/Lsp.Integration.Tests/Fixtures/IConfigureLanguageClientOptions.cs @@ -1,6 +1,6 @@ using OmniSharp.Extensions.LanguageServer.Client; -namespace Lsp.Tests.Integration.Fixtures +namespace Lsp.Integration.Tests.Fixtures { public interface IConfigureLanguageClientOptions { diff --git a/test/Lsp.Integration.Tests/Fixtures/IConfigureLanguageProtocolFixture.cs b/test/Lsp.Integration.Tests/Fixtures/IConfigureLanguageProtocolFixture.cs index d3ffe1b54..8d4be6e0e 100644 --- a/test/Lsp.Integration.Tests/Fixtures/IConfigureLanguageProtocolFixture.cs +++ b/test/Lsp.Integration.Tests/Fixtures/IConfigureLanguageProtocolFixture.cs @@ -1,9 +1,9 @@ using OmniSharp.Extensions.JsonRpc.Testing; -namespace Lsp.Tests.Integration.Fixtures +namespace Lsp.Integration.Tests.Fixtures { public interface IConfigureLanguageProtocolFixture { JsonRpcTestOptions Configure(JsonRpcTestOptions options); } -} \ No newline at end of file +} diff --git a/test/Lsp.Integration.Tests/Fixtures/IConfigureLanguageServerOptions.cs b/test/Lsp.Integration.Tests/Fixtures/IConfigureLanguageServerOptions.cs index cdacaecca..4314b7436 100644 --- a/test/Lsp.Integration.Tests/Fixtures/IConfigureLanguageServerOptions.cs +++ b/test/Lsp.Integration.Tests/Fixtures/IConfigureLanguageServerOptions.cs @@ -1,9 +1,9 @@ using OmniSharp.Extensions.LanguageServer.Server; -namespace Lsp.Tests.Integration.Fixtures +namespace Lsp.Integration.Tests.Fixtures { public interface IConfigureLanguageServerOptions { void Configure(LanguageServerOptions options); } -} \ No newline at end of file +} diff --git a/test/Lsp.Integration.Tests/Fixtures/LanguageProtocolFixture.cs b/test/Lsp.Integration.Tests/Fixtures/LanguageProtocolFixture.cs index fd9543ab0..b5c96eff7 100644 --- a/test/Lsp.Integration.Tests/Fixtures/LanguageProtocolFixture.cs +++ b/test/Lsp.Integration.Tests/Fixtures/LanguageProtocolFixture.cs @@ -7,7 +7,7 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration.Fixtures +namespace Lsp.Integration.Tests.Fixtures { public class LanguageProtocolFixture : LanguageProtocolTestBase, IAsyncLifetime where TConfigureFixture : IConfigureLanguageProtocolFixture, new() @@ -47,6 +47,9 @@ public async Task InitializeAsync() Server = server; } - public Task DisposeAsync() => Task.CompletedTask; + public Task DisposeAsync() + { + return Task.CompletedTask; + } } } diff --git a/test/Lsp.Integration.Tests/Fixtures/LanguageProtocolFixtureTest.cs b/test/Lsp.Integration.Tests/Fixtures/LanguageProtocolFixtureTest.cs index a7b12cad3..bbd7dc5a6 100644 --- a/test/Lsp.Integration.Tests/Fixtures/LanguageProtocolFixtureTest.cs +++ b/test/Lsp.Integration.Tests/Fixtures/LanguageProtocolFixtureTest.cs @@ -8,7 +8,7 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration.Fixtures +namespace Lsp.Integration.Tests.Fixtures { public abstract class LanguageProtocolFixtureTest : IClassFixture> @@ -18,7 +18,9 @@ public abstract class LanguageProtocolFixtureTest Fixture { get; } - protected LanguageProtocolFixtureTest(ITestOutputHelper testOutputHelper, LanguageProtocolFixture fixture) + protected LanguageProtocolFixtureTest( + ITestOutputHelper testOutputHelper, LanguageProtocolFixture fixture + ) { Fixture = fixture; Client = fixture.Client; @@ -38,7 +40,15 @@ protected LanguageProtocolFixtureTest(ITestOutputHelper testOutputHelper, Langua protected ISettler ClientEvents { get; } protected ISettler ServerEvents { get; } protected ISettler Events { get; } - protected Task SettleNext() => Events.SettleNext(); - protected IObservable Settle() => Events.Settle(); + + protected Task SettleNext() + { + return Events.SettleNext(); + } + + protected IObservable Settle() + { + return Events.Settle(); + } } -} \ No newline at end of file +} diff --git a/test/Lsp.Integration.Tests/FluentAssertionsExtensions.cs b/test/Lsp.Integration.Tests/FluentAssertionsExtensions.cs index 6c12fb871..bba67f668 100644 --- a/test/Lsp.Integration.Tests/FluentAssertionsExtensions.cs +++ b/test/Lsp.Integration.Tests/FluentAssertionsExtensions.cs @@ -1,50 +1,48 @@ -using System; using FluentAssertions.Equivalency; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Microsoft.Extensions.Options; using NSubstitute; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; -namespace Lsp.Tests +namespace Lsp.Integration.Tests { public static class FluentAssertionsExtensions { - public static EquivalencyAssertionOptions ConfigureForSupports(this EquivalencyAssertionOptions options, ILogger? logger = null) => - options - .WithTracing(new TraceWriter(logger ?? NullLogger.Instance)) - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>(); + public static EquivalencyAssertionOptions ConfigureForSupports(this EquivalencyAssertionOptions options, ILogger? logger = null) + { + return options + .WithTracing(new TraceWriter(logger ?? NullLogger.Instance)) + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>(); + } } } diff --git a/test/Lsp.Integration.Tests/HandlersManagerIntegrationTests.cs b/test/Lsp.Integration.Tests/HandlersManagerIntegrationTests.cs index f5050a773..081acb611 100644 --- a/test/Lsp.Integration.Tests/HandlersManagerIntegrationTests.cs +++ b/test/Lsp.Integration.Tests/HandlersManagerIntegrationTests.cs @@ -8,11 +8,10 @@ using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using TestingUtils; using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class HandlersManagerIntegrationTests : LanguageProtocolTestBase { @@ -23,7 +22,7 @@ public HandlersManagerIntegrationTests(ITestOutputHelper testOutputHelper) : bas [Fact] public async Task Should_Return_Default_Handlers() { - var (_, server) = await Initialize(options => {}, options => {}); + var (_, server) = await Initialize(options => { }, options => { }); var handlersManager = server.GetRequiredService(); handlersManager.Descriptors.Should().HaveCount(9); @@ -33,9 +32,13 @@ public async Task Should_Return_Default_Handlers() [Fact] public async Task Should_Return_Additional_Handlers() { - var (_, server) = await Initialize(options => {}, options => {}); + var (_, server) = await Initialize(options => { }, options => { }); - server.Register(o => o.AddHandler((IJsonRpcHandler) Substitute.For(new[] { typeof (ICompletionHandler), typeof(ICompletionResolveHandler) }, Array.Empty()))); + server.Register( + o => o.AddHandler( + (IJsonRpcHandler)Substitute.For(new[] { typeof(ICompletionHandler), typeof(ICompletionResolveHandler) }, Array.Empty()) + ) + ); var handlersManager = server.GetRequiredService(); handlersManager.Descriptors.Should().HaveCount(11); handlersManager.GetHandlers().Should().HaveCount(7); @@ -44,24 +47,29 @@ public async Task Should_Return_Additional_Handlers() [Fact] public async Task Link_Should_Fail_If_No_Handler_Is_Defined() { - var (_, server) = await Initialize(options => {}, options => {}); + var (_, server) = await Initialize(options => { }, options => { }); var handlersManager = server.GetRequiredService(); - Action a = () => handlersManager.AddLink(TextDocumentNames.Completion, "my/completion"); + Action a = () => handlersManager.AddLink(TextDocumentNames.Completion, "my/completion"); a.Should().Throw().Which.Message.Should().Contain("Descriptors must be registered before links can be created"); } [Fact] public async Task Link_Should_Fail_If_Link_Is_On_The_Wrong_Side() { - var (_, server) = await Initialize(options => {}, options => {}); + var (_, server) = await Initialize(options => { }, options => { }); - server.Register(o => o.AddHandler((IJsonRpcHandler) Substitute.For(new[] { typeof (ICompletionHandler), typeof(ICompletionResolveHandler) }, Array.Empty()))); + server.Register( + o => o.AddHandler( + (IJsonRpcHandler)Substitute.For(new[] { typeof(ICompletionHandler), typeof(ICompletionResolveHandler) }, Array.Empty()) + ) + ); var handlersManager = server.GetRequiredService(); - Action a = () => handlersManager.AddLink("my/completion", TextDocumentNames.Completion); - a.Should().Throw().Which.Message.Should().Contain($"Did you mean to link '{TextDocumentNames.Completion}' to 'my/completion' instead"); + Action a = () => handlersManager.AddLink("my/completion", TextDocumentNames.Completion); + a.Should().Throw().Which.Message.Should() + .Contain($"Did you mean to link '{TextDocumentNames.Completion}' to 'my/completion' instead"); } } } diff --git a/test/Lsp.Integration.Tests/InitializationTests.cs b/test/Lsp.Integration.Tests/InitializationTests.cs index 6c783cf6c..3afead878 100644 --- a/test/Lsp.Integration.Tests/InitializationTests.cs +++ b/test/Lsp.Integration.Tests/InitializationTests.cs @@ -1,15 +1,12 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using NSubstitute; -using NSubstitute.ReceivedExtensions; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Client; @@ -21,11 +18,10 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Window; using OmniSharp.Extensions.LanguageServer.Server; using Serilog.Events; -using TestingUtils; using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class InitializationTests : LanguageProtocolTestBase { @@ -57,29 +53,33 @@ public async Task Facades_should_be_resolvable() [Fact] public async Task Should_Not_Be_Able_To_Send_Messages_Unit_Initialization() { - if (!(TestOptions.ClientLoggerFactory is TestLoggerFactory loggerFactory)) throw new Exception("wtf"); + if (!( TestOptions.ClientLoggerFactory is TestLoggerFactory loggerFactory )) throw new Exception("wtf"); var logs = new List(); var onInitializeNotify = Substitute.For(); var onInitializedNotify = Substitute.For(); using var _ = loggerFactory.Where(z => z.Level == LogEventLevel.Warning).Subscribe(z => logs.Add(z)); var (client, server) = await Initialize( - options => { + options => + { ConfigureClient(options); options .OnNotification("OnInitializeNotify", onInitializeNotify) .OnNotification("OnInitializedNotify", onInitializedNotify); - }, options => { + }, options => + { ConfigureServer(options); options .OnInitialize( - (languageServer, request, token) => { + (languageServer, request, token) => + { languageServer.SendNotification("OnInitializeNotify"); return Task.CompletedTask; } ) .OnInitialized( - (languageServer, request, response, token) => { + (languageServer, request, response, token) => + { languageServer.SendNotification("OnInitializedNotify"); return Task.CompletedTask; } @@ -119,35 +119,51 @@ await Observable.FromAsync(client.Initialize) response.Should().NotBeNull(); } - class CodeLensHandlerA : CodeLensHandlerBase + private class CodeLensHandlerA : CodeLensHandlerBase { public CodeLensHandlerA(ILanguageServerFacade languageServerFacade) { languageServerFacade.Should().NotBeNull(); } - public override Task Handle(CodeLensParams request, CancellationToken cancellationToken) => Task.FromResult(new CodeLensContainer()); + public override Task Handle(CodeLensParams request, CancellationToken cancellationToken) + { + return Task.FromResult(new CodeLensContainer()); + } + + public override Task Handle(CodeLens request, CancellationToken cancellationToken) + { + return Task.FromResult(request); + } - public override Task Handle(CodeLens request, CancellationToken cancellationToken) => Task.FromResult(request); - protected internal override CodeLensRegistrationOptions CreateRegistrationOptions(CodeLensCapability capability, ClientCapabilities clientCapabilities) => new (); + protected internal override CodeLensRegistrationOptions CreateRegistrationOptions( + CodeLensCapability capability, ClientCapabilities clientCapabilities + ) + { + return new(); + } } private readonly List _logs = new List(); - private void ConfigureClient(LanguageClientOptions options) => + private void ConfigureClient(LanguageClientOptions options) + { options.OnLogMessage(log => { _logs.Add(log.Message); }); + } private void ConfigureServer(LanguageServerOptions options) { options.OnInitialize( - (server, request, token) => { + (server, request, token) => + { server.Window.LogInfo("OnInitialize"); return Task.CompletedTask; } ); options.AddHandler(); options.OnInitialized( - (server, request, response, token) => { + (server, request, response, token) => + { server.Window.LogInfo("OnInitialized"); return Task.CompletedTask; } diff --git a/test/Lsp.Integration.Tests/IntegrationTestingExtensions.cs b/test/Lsp.Integration.Tests/IntegrationTestingExtensions.cs index 58c8d600f..13febf0d5 100644 --- a/test/Lsp.Integration.Tests/IntegrationTestingExtensions.cs +++ b/test/Lsp.Integration.Tests/IntegrationTestingExtensions.cs @@ -1,4 +1,4 @@ -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public static class IntegrationTestingExtensions { diff --git a/test/Lsp.Integration.Tests/LanguageServerConfigurationTests.cs b/test/Lsp.Integration.Tests/LanguageServerConfigurationTests.cs index b40359ede..134c4fc87 100644 --- a/test/Lsp.Integration.Tests/LanguageServerConfigurationTests.cs +++ b/test/Lsp.Integration.Tests/LanguageServerConfigurationTests.cs @@ -8,7 +8,6 @@ using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; using NSubstitute; -using NSubstitute.Extensions; using NSubstitute.ReceivedExtensions; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; @@ -24,11 +23,13 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class LanguageServerConfigurationTests : LanguageProtocolTestBase { - public LanguageServerConfigurationTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper, LogEventLevel.Verbose)) + public LanguageServerConfigurationTests(ITestOutputHelper outputHelper) : base( + new JsonRpcTestOptions().ConfigureForXUnit(outputHelper, LogEventLevel.Verbose) + ) { } @@ -50,13 +51,15 @@ public async Task Should_Not_Support_Configuration_It_Not_Configured() public async Task Should_Allow_Null_Response() { var (client, server) = await Initialize( - options => { + options => + { options.WithCapability(new DidChangeConfigurationCapability()); options.OnConfiguration(@params => Task.FromResult(new Container(@params.Items.Select(z => (JToken?)null)))); ConfigureClient(options); - }, ConfigureServer); + }, ConfigureServer + ); - Func a = () => server.Configuration.GetConfiguration(new ConfigurationItem() { Section = "mysection" }); + Func a = () => server.Configuration.GetConfiguration(new ConfigurationItem { Section = "mysection" }); await a.Should().NotThrowAsync(); } @@ -78,7 +81,7 @@ public async Task Should_Update_Configuration_On_Server() [Fact] public async Task Should_Update_Configuration_On_Server_After_Starting() { - var (_, server, configuration) = await InitializeWithConfiguration(ConfigureClient, options => {}); + var (_, server, configuration) = await InitializeWithConfiguration(ConfigureClient, options => { }); server.Configuration.AsEnumerable().Should().BeEmpty(); server.Configuration.AddSection("mysection", "othersection"); @@ -212,10 +215,13 @@ public async Task Should_Support_Configuration_Binding() [Fact] public async Task Should_Support_Options() { - var (_, server, configuration) = await InitializeWithConfiguration(ConfigureClient, options => { - ConfigureServer(options); - options.Services.Configure("mysection"); - }); + var (_, server, configuration) = await InitializeWithConfiguration( + ConfigureClient, options => + { + ConfigureServer(options); + options.Services.Configure("mysection"); + } + ); configuration.Update("mysection", new Dictionary { ["host"] = "localhost", ["port"] = "443" }); configuration.Update("notmysection", new Dictionary { ["host"] = "127.0.0.1", ["port"] = "123" }); @@ -237,10 +243,13 @@ public async Task Should_Support_Options() [Fact] public async Task Should_Support_Options_Monitor() { - var (_, server, configuration) = await InitializeWithConfiguration(ConfigureClient, options => { - ConfigureServer(options); - options.Services.Configure("mysection"); - }); + var (_, server, configuration) = await InitializeWithConfiguration( + ConfigureClient, options => + { + ConfigureServer(options); + options.Services.Configure("mysection"); + } + ); var options = server.GetService>(); var sub = Substitute.For>(); @@ -265,7 +274,7 @@ public async Task Should_Support_Options_Monitor() sub.Received(Quantity.Within(2, int.MaxValue)).Invoke(Arg.Any()); } - class BinderSourceUrl + private class BinderSourceUrl { public string Host { get; set; } public int Port { get; set; } @@ -275,6 +284,9 @@ private void ConfigureClient(LanguageClientOptions options) { } - private void ConfigureServer(LanguageServerOptions options) => options.WithConfigurationSection("mysection").WithConfigurationSection("othersection"); + private void ConfigureServer(LanguageServerOptions options) + { + options.WithConfigurationSection("mysection").WithConfigurationSection("othersection"); + } } } diff --git a/test/Lsp.Integration.Tests/LanguageServerLoggingTests.cs b/test/Lsp.Integration.Tests/LanguageServerLoggingTests.cs index 273dcffef..bcef7bce2 100644 --- a/test/Lsp.Integration.Tests/LanguageServerLoggingTests.cs +++ b/test/Lsp.Integration.Tests/LanguageServerLoggingTests.cs @@ -1,12 +1,10 @@ using System; using System.Collections.Concurrent; -using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using NSubstitute; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Protocol.Models; @@ -17,7 +15,7 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class LanguageServerLoggingTests : LanguageProtocolTestBase { @@ -31,7 +29,8 @@ public async Task Logs_Are_Sent_To_Client_From_Server() var logs = new ConcurrentBag(); var (client, server) = await Initialize( options => { options.Trace = InitializeTrace.Verbose; }, - options => { + options => + { options.ConfigureLogging( z => z .AddLanguageProtocolLogging() @@ -70,7 +69,8 @@ public async Task Logs_Are_Sent_To_Client_From_Server_Respecting_SetMinimumLevel var logs = new ConcurrentBag(); var (client, server) = await Initialize( options => { }, - options => { + options => + { options.ConfigureLogging( z => z .AddLanguageProtocolLogging() @@ -109,7 +109,8 @@ public async Task Logs_Are_Sent_To_Client_From_Server_Respecting_TraceLevel() var logs = new ConcurrentBag(); var (client, server) = await Initialize( options => { options.Trace = InitializeTrace.Messages; }, - options => { + options => + { options.ConfigureLogging( z => z .AddLanguageProtocolLogging() @@ -148,7 +149,8 @@ public async Task Client_Can_Dynamically_Change_Server_Trace_Level_Off_To_Verbos var logs = new ConcurrentBag(); var (client, server) = await Initialize( options => { }, - options => { + options => + { options.ConfigureLogging( z => z .AddLanguageProtocolLogging() @@ -214,10 +216,9 @@ public async Task Client_Can_Dynamically_Change_Server_Trace_Level_Verbose_To_Of { var logs = new ConcurrentBag(); var (client, server) = await Initialize( - options => { - options.Trace = InitializeTrace.Verbose; - }, - options => { + options => { options.Trace = InitializeTrace.Verbose; }, + options => + { options.ConfigureLogging( z => z .AddLanguageProtocolLogging() diff --git a/test/Lsp.Integration.Tests/LogMessageTests.cs b/test/Lsp.Integration.Tests/LogMessageTests.cs index 6a4869a85..a19bb457c 100644 --- a/test/Lsp.Integration.Tests/LogMessageTests.cs +++ b/test/Lsp.Integration.Tests/LogMessageTests.cs @@ -13,7 +13,7 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class LogMessageTests : LanguageProtocolTestBase { @@ -33,12 +33,14 @@ public async Task Should_Log_Messages_Through_Window_Extension_Methods() server.Window.LogWarning("Uh-oh..."); server.Window.Log("Just gotta let you know!"); server.Window.Log( - new LogMessageParams { + new LogMessageParams + { Type = MessageType.Log, Message = "1234" } ); server.Window.LogMessage( - new LogMessageParams { + new LogMessageParams + { Type = MessageType.Log, Message = "1234" } ); @@ -62,12 +64,14 @@ public async Task Should_Log_Messages_Through_Server_Extension_Methods() server.LogWarning("Uh-oh..."); server.Log("Just gotta let you know!"); server.Log( - new LogMessageParams { + new LogMessageParams + { Type = MessageType.Log, Message = "1234" } ); server.LogMessage( - new LogMessageParams { + new LogMessageParams + { Type = MessageType.Log, Message = "1234" } ); @@ -81,7 +85,10 @@ public async Task Should_Log_Messages_Through_Server_Extension_Methods() _receivedMessages.Should().Contain(z => z.Type == MessageType.Log).And.Subject.Count(z => z.Type == MessageType.Log).Should().Be(3); } - private void ConfigureClient(LanguageClientOptions options) => options.OnLogMessage(request => { _receivedMessages.Add(request); }); + private void ConfigureClient(LanguageClientOptions options) + { + options.OnLogMessage(request => { _receivedMessages.Add(request); }); + } private void ConfigureServer(LanguageServerOptions options) { diff --git a/test/Lsp.Integration.Tests/MonikerTests.cs b/test/Lsp.Integration.Tests/MonikerTests.cs index 6b5c37aaf..cfaee34c7 100644 --- a/test/Lsp.Integration.Tests/MonikerTests.cs +++ b/test/Lsp.Integration.Tests/MonikerTests.cs @@ -9,18 +9,17 @@ using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Server; using Serilog.Events; -using TestingUtils; using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class MonikerTests : LanguageProtocolTestBase { private readonly Func?>> _request; + public MonikerTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper, LogEventLevel.Verbose)) { _request = Substitute.For?>>>(); @@ -30,16 +29,17 @@ public MonikerTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOption public async Task Should_Get_Monikers() { _request.Invoke(Arg.Any(), Arg.Any()) - .Returns(new Container( - new[] { - new Moniker() { - Identifier = "abcd", - Kind = MonikerKind.Export, - Scheme = "http", - Unique = UniquenessLevel.Document - }, - } - )); + .Returns( + new Container( + new Moniker + { + Identifier = "abcd", + Kind = MonikerKind.Export, + Scheme = "http", + Unique = UniquenessLevel.Document + } + ) + ); var (client, _) = await Initialize(ClientOptionsAction, ServerOptionsAction); @@ -53,7 +53,8 @@ public async Task Should_Get_Monikers() private void ServerOptionsAction(LanguageServerOptions obj) { obj.OnMoniker( - _request, (_, _) => new MonikerRegistrationOptions() { + _request, (_, _) => new MonikerRegistrationOptions + { DocumentSelector = DocumentSelector.ForLanguage("csharp"), } ); diff --git a/test/Lsp.Integration.Tests/OverrideHandlerTests.cs b/test/Lsp.Integration.Tests/OverrideHandlerTests.cs index e0e961e2a..435f2cf3b 100644 --- a/test/Lsp.Integration.Tests/OverrideHandlerTests.cs +++ b/test/Lsp.Integration.Tests/OverrideHandlerTests.cs @@ -12,11 +12,10 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; -using TestingUtils; using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class OverrideHandlerTests : LanguageProtocolTestBase { @@ -28,15 +27,12 @@ public OverrideHandlerTests(ITestOutputHelper testOutputHelper) : base(new JsonR public async Task Should_Support_Custom_Execute_Command_Handlers() { var (client, _) = await Initialize( - options => { - - }, options => { - options.AddHandler(); - } + options => { }, options => { options.AddHandler(); } ); var response = await client.SendRequest( - new CustomExecuteCommandParams() { + new CustomExecuteCommandParams + { Command = "mycommand", }, CancellationToken ); @@ -48,23 +44,24 @@ public async Task Should_Support_Custom_Execute_Command_Handlers() public async Task Should_Support_Mixed_Execute_Command_Handlers() { var (client, _) = await Initialize( - options => { - - }, options => { + options => { }, options => + { options.AddHandler(); options.OnExecuteCommand("myothercommand", (a, ct) => Unit.Task); } ); var normalResponse = await client.SendRequest( - new ExecuteCommandParams() { + new ExecuteCommandParams + { Command = "myothercommand", Arguments = new JArray(new JObject()) }, CancellationToken ); var customResponse = await client.SendRequest( - new CustomExecuteCommandParams() { + new CustomExecuteCommandParams + { Command = "mycommand", }, CancellationToken ); @@ -75,11 +72,14 @@ public async Task Should_Support_Mixed_Execute_Command_Handlers() } [Method(WorkspaceNames.ExecuteCommand)] - public class CustomExecuteCommandHandler : IJsonRpcRequestHandler, IRegistration + public class CustomExecuteCommandHandler : IJsonRpcRequestHandler, + IRegistration { // ReSharper disable once NotAccessedField.Local private ExecuteCommandCapability? _capability; - private readonly ExecuteCommandRegistrationOptions _executeCommandRegistrationOptions = new ExecuteCommandRegistrationOptions() { + + private readonly ExecuteCommandRegistrationOptions _executeCommandRegistrationOptions = new ExecuteCommandRegistrationOptions + { WorkDoneProgress = true, Commands = new Container("mycommand") }; diff --git a/test/Lsp.Integration.Tests/PartialItemTests.cs b/test/Lsp.Integration.Tests/PartialItemTests.cs index bbf7c21d8..dfd280b3e 100644 --- a/test/Lsp.Integration.Tests/PartialItemTests.cs +++ b/test/Lsp.Integration.Tests/PartialItemTests.cs @@ -5,22 +5,22 @@ using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using FluentAssertions; -using Lsp.Tests.Integration.Fixtures; +using Lsp.Integration.Tests.Fixtures; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Server; -using TestingUtils; using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public static class PartialItemTests { public class Delegates : LanguageProtocolFixtureTest { - public Delegates(ITestOutputHelper testOutputHelper, LanguageProtocolFixture fixture) : base(testOutputHelper, fixture) + public Delegates(ITestOutputHelper testOutputHelper, LanguageProtocolFixture fixture) : base( + testOutputHelper, fixture + ) { } @@ -28,7 +28,7 @@ public Delegates(ITestOutputHelper testOutputHelper, LanguageProtocolFixture(), (acc, v) => { + new List(), (acc, v) => + { acc.Add(v); return acc; } @@ -56,7 +57,9 @@ public async Task Should_Behave_Like_An_Observable() [Fact] public async Task Should_Behave_Like_An_Observable_Without_Progress_Support() { - var response = await Client.SendRequest(new SemanticTokensParams { TextDocument = new TextDocumentIdentifier(@"c:\test.cs") }, CancellationToken); + var response = await Client.SendRequest( + new SemanticTokensParams { TextDocument = new TextDocumentIdentifier(@"c:\test.cs") }, CancellationToken + ); response.Should().NotBeNull(); response!.Data.Should().HaveCount(3); @@ -64,14 +67,18 @@ public async Task Should_Behave_Like_An_Observable_Without_Progress_Support() public class DelegateServer : IConfigureLanguageServerOptions { - public void Configure(LanguageServerOptions options) => options.ObserveSemanticTokensFull( - (@params, observer, arg3) => { - observer.OnNext(new SemanticTokensPartialResult() { Data = new[] { 0 }.ToImmutableArray() }); - observer.OnNext(new SemanticTokensPartialResult() { Data = new[] { 0, 1 }.ToImmutableArray() }); - observer.OnNext(new SemanticTokensPartialResult() { Data = new[] { 0, 1, 2 }.ToImmutableArray() }); - observer.OnCompleted(); - }, (_, _) => new SemanticTokensRegistrationOptions() - ); + public void Configure(LanguageServerOptions options) + { + options.ObserveSemanticTokensFull( + (@params, observer, arg3) => + { + observer.OnNext(new SemanticTokensPartialResult { Data = new[] { 0 }.ToImmutableArray() }); + observer.OnNext(new SemanticTokensPartialResult { Data = new[] { 0, 1 }.ToImmutableArray() }); + observer.OnNext(new SemanticTokensPartialResult { Data = new[] { 0, 1, 2 }.ToImmutableArray() }); + observer.OnCompleted(); + }, (_, _) => new SemanticTokensRegistrationOptions() + ); + } } } } diff --git a/test/Lsp.Integration.Tests/PartialItemsTests.cs b/test/Lsp.Integration.Tests/PartialItemsTests.cs index d3243a697..823ab721d 100644 --- a/test/Lsp.Integration.Tests/PartialItemsTests.cs +++ b/test/Lsp.Integration.Tests/PartialItemsTests.cs @@ -7,7 +7,8 @@ using System.Threading; using System.Threading.Tasks; using FluentAssertions; -using Lsp.Tests.Integration.Fixtures; +using Lsp.Integration.Tests.Fixtures; +using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Document; @@ -19,13 +20,15 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public static class PartialItemsTests { public class Delegates : LanguageProtocolFixtureTest { - public Delegates(ITestOutputHelper testOutputHelper, LanguageProtocolFixture fixture) : base(testOutputHelper, fixture) + public Delegates(ITestOutputHelper testOutputHelper, LanguageProtocolFixture fixture) : base( + testOutputHelper, fixture + ) { } @@ -33,7 +36,8 @@ public Delegates(ITestOutputHelper testOutputHelper, LanguageProtocolFixture(), (acc, v) => { + new List(), (acc, v) => + { acc.AddRange(v); return acc; } @@ -67,7 +73,8 @@ public async Task Should_Behave_Like_An_Observable() public async Task Should_Behave_Like_An_Observable_Without_Progress_Support() { var response = await Client.SendRequest( - new CodeLensParams { + new CodeLensParams + { TextDocument = new TextDocumentIdentifier(@"c:\test.cs") }, CancellationToken ); @@ -78,31 +85,42 @@ public async Task Should_Behave_Like_An_Observable_Without_Progress_Support() public class DelegateServer : IConfigureLanguageServerOptions { - public void Configure(LanguageServerOptions options) => + public void Configure(LanguageServerOptions options) + { options.ObserveCodeLens( - (@params, observer, capability, cancellationToken) => { + (@params, observer, capability, cancellationToken) => + { observer.OnNext( - new[] { - new CodeLens { - Command = new Command { + new[] + { + new CodeLens + { + Command = new Command + { Name = "CodeLens 1" } }, } ); observer.OnNext( - new[] { - new CodeLens { - Command = new Command { + new[] + { + new CodeLens + { + Command = new Command + { Name = "CodeLens 2" } }, } ); observer.OnNext( - new[] { - new CodeLens { - Command = new Command { + new[] + { + new CodeLens + { + Command = new Command + { Name = "CodeLens 3" } }, @@ -111,12 +129,15 @@ public void Configure(LanguageServerOptions options) => observer.OnCompleted(); }, (_, _) => new CodeLensRegistrationOptions() ); + } } } public class Handlers : LanguageProtocolFixtureTest { - public Handlers(ITestOutputHelper testOutputHelper, LanguageProtocolFixture fixture) : base(testOutputHelper, fixture) + public Handlers(ITestOutputHelper testOutputHelper, LanguageProtocolFixture fixture) : base( + testOutputHelper, fixture + ) { } @@ -128,9 +149,11 @@ public async Task Should_Behave_Like_An_Observable_With_WorkDone() Client.TextDocument .ObserveWorkDone( new CodeLensParams { TextDocument = new TextDocumentIdentifier(@"c:\test.cs") }, - (client, request) => CodeLensExtensions.RequestCodeLens(client, request, CancellationToken), + (client, request) => client.RequestCodeLens(request, CancellationToken), Observer.Create(z => work.Add(z)) - ).Subscribe(x => items.AddRange(x)); + ).Subscribe( + x => items.AddRange(x) + ); await work.DelayUntilCount(6, CancellationToken); @@ -147,7 +170,10 @@ public async Task Should_Behave_Like_An_Observable_With_WorkDone() public class HandlersServer : IConfigureLanguageServerOptions { - public void Configure(LanguageServerOptions options) => options.AddHandler(); + public void Configure(LanguageServerOptions options) + { + options.AddHandler(); + } } } @@ -166,75 +192,93 @@ public override async Task Handle(CodeLensParams request, Can { var partial = _progressManager.For(request, cancellationToken); var workDone = _workDoneManager.For( - request, new WorkDoneProgressBegin { + request, new WorkDoneProgressBegin + { Cancellable = true, Message = "Begin", Percentage = 0, Title = "Work is pending" - }, onComplete: () => new WorkDoneProgressEnd { + }, onComplete: () => new WorkDoneProgressEnd + { Message = "End" } ); partial.OnNext( - new[] { - new CodeLens { - Command = new Command { + new[] + { + new CodeLens + { + Command = new Command + { Name = "CodeLens 1" } }, } ); workDone.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 10, Message = "Report 1" } ); partial.OnNext( - new[] { - new CodeLens { - Command = new Command { + new[] + { + new CodeLens + { + Command = new Command + { Name = "CodeLens 2" } }, } ); workDone.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 20, Message = "Report 2" } ); partial.OnNext( - new[] { - new CodeLens { - Command = new Command { + new[] + { + new CodeLens + { + Command = new Command + { Name = "CodeLens 3" } }, } ); workDone.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 30, Message = "Report 3" } ); partial.OnNext( - new[] { - new CodeLens { - Command = new Command { + new[] + { + new CodeLens + { + Command = new Command + { Name = "CodeLens 4" } }, } ); workDone.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 40, Message = "Report 4" } @@ -247,8 +291,17 @@ public override async Task Handle(CodeLensParams request, Can return new CodeLensContainer(); } - public override Task Handle(CodeLens request, CancellationToken cancellationToken) => Task.FromResult(request); - protected internal override CodeLensRegistrationOptions CreateRegistrationOptions(CodeLensCapability capability, ClientCapabilities clientCapabilities) => new CodeLensRegistrationOptions(); + public override Task Handle(CodeLens request, CancellationToken cancellationToken) + { + return Task.FromResult(request); + } + + protected internal override CodeLensRegistrationOptions CreateRegistrationOptions( + CodeLensCapability capability, ClientCapabilities clientCapabilities + ) + { + return new CodeLensRegistrationOptions(); + } } } } diff --git a/test/Lsp.Integration.Tests/ProgressTests.cs b/test/Lsp.Integration.Tests/ProgressTests.cs index e61bb7e56..6c7dad46a 100644 --- a/test/Lsp.Integration.Tests/ProgressTests.cs +++ b/test/Lsp.Integration.Tests/ProgressTests.cs @@ -7,7 +7,7 @@ using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using FluentAssertions; -using Lsp.Tests.Integration.Fixtures; +using Lsp.Integration.Tests.Fixtures; using Microsoft.Extensions.DependencyInjection; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; @@ -15,11 +15,13 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class ProgressTests : LanguageProtocolFixtureTest { - public ProgressTests(ITestOutputHelper testOutputHelper, LanguageProtocolFixture fixture) : base(testOutputHelper, fixture) + public ProgressTests(ITestOutputHelper testOutputHelper, LanguageProtocolFixture fixture) : base( + testOutputHelper, fixture + ) { } @@ -34,32 +36,39 @@ public async Task Should_Send_Progress_From_Server_To_Client() var token = new ProgressToken(Guid.NewGuid().ToString()); using var observer = Client.ProgressManager.For(token, CancellationToken); - var workDoneObservable = Server.ProgressManager.Monitor(token, x => x.ToObject(Server.Services.GetRequiredService().JsonSerializer)); + var workDoneObservable = Server.ProgressManager.Monitor( + token, x => x.ToObject(Server.Services.GetRequiredService().JsonSerializer) + ); var observable = workDoneObservable.Replay(); using var _ = observable.Connect(); observer.OnNext( - new Data { + new Data + { Value = "1" } ); observer.OnNext( - new Data { + new Data + { Value = "3" } ); observer.OnNext( - new Data { + new Data + { Value = "2" } ); observer.OnNext( - new Data { + new Data + { Value = "4" } ); observer.OnNext( - new Data { + new Data + { Value = "5" } ); @@ -67,7 +76,8 @@ public async Task Should_Send_Progress_From_Server_To_Client() observer.OnCompleted(); await Observable.Create( - innerObserver => new CompositeDisposable() { + innerObserver => new CompositeDisposable + { observable.Take(5).Select(z => z.Value).Subscribe(v => innerObserver.OnNext(Unit.Default), innerObserver.OnCompleted), workDoneObservable } @@ -75,7 +85,7 @@ await Observable.Create( var data = await observable.Select(z => z.Value).ToArray().ToTask(CancellationToken); - data.Should().ContainInOrder(new[] { "1", "3", "2", "4", "5" }); + data.Should().ContainInOrder("1", "3", "2", "4", "5"); } [Fact] @@ -84,32 +94,39 @@ public async Task Should_Send_Progress_From_Client_To_Server() var token = new ProgressToken(Guid.NewGuid().ToString()); using var observer = Server.ProgressManager.For(token, CancellationToken); - var workDoneObservable = Client.ProgressManager.Monitor(token, x => x.ToObject(Client.Services.GetRequiredService().JsonSerializer)); + var workDoneObservable = Client.ProgressManager.Monitor( + token, x => x.ToObject(Client.Services.GetRequiredService().JsonSerializer) + ); var observable = workDoneObservable.Replay(); using var _ = observable.Connect(); observer.OnNext( - new Data { + new Data + { Value = "1" } ); observer.OnNext( - new Data { + new Data + { Value = "3" } ); observer.OnNext( - new Data { + new Data + { Value = "2" } ); observer.OnNext( - new Data { + new Data + { Value = "4" } ); observer.OnNext( - new Data { + new Data + { Value = "5" } ); @@ -117,7 +134,8 @@ public async Task Should_Send_Progress_From_Client_To_Server() observer.OnCompleted(); await Observable.Create( - innerObserver => new CompositeDisposable() { + innerObserver => new CompositeDisposable + { observable .Take(5) .Select(z => z.Value) @@ -128,7 +146,7 @@ await Observable.Create( var data = await observable.Select(z => z.Value).ToArray().ToTask(CancellationToken); - data.Should().ContainInOrder(new[] { "1", "3", "2", "4", "5" }); + data.Should().ContainInOrder("1", "3", "2", "4", "5"); } [Fact] @@ -148,39 +166,45 @@ public async Task Should_Support_Creating_Work_Done_From_Sever_To_Client() using var _ = observable.Connect(); using var workDoneObserver = await Server.WorkDoneManager.Create( - token, new WorkDoneProgressBegin { + token, new WorkDoneProgressBegin + { Cancellable = true, Message = "Begin", Percentage = 0, Title = "Work is pending" - }, onComplete: () => new WorkDoneProgressEnd { + }, onComplete: () => new WorkDoneProgressEnd + { Message = "End" } ); workDoneObserver.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 10, Message = "Report 1" } ); workDoneObserver.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 20, Message = "Report 2" } ); workDoneObserver.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 30, Message = "Report 3" } ); workDoneObserver.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 40, Message = "Report 4" } @@ -189,7 +213,8 @@ public async Task Should_Support_Creating_Work_Done_From_Sever_To_Client() workDoneObserver.OnCompleted(); var results = await observable.Select( - z => z switch { + z => z switch + { WorkDoneProgressBegin begin => begin.Message, WorkDoneProgressReport begin => begin.Message, WorkDoneProgressEnd begin => begin.Message, @@ -210,39 +235,45 @@ public async Task Should_Support_Observing_Work_Done_From_Client_To_Server_Reque using var _ = observable.Connect(); using var workDoneObserver = await Server.WorkDoneManager.Create( - token, new WorkDoneProgressBegin { + token, new WorkDoneProgressBegin + { Cancellable = true, Message = "Begin", Percentage = 0, Title = "Work is pending" - }, onComplete: () => new WorkDoneProgressEnd { + }, onComplete: () => new WorkDoneProgressEnd + { Message = "End" } ); workDoneObserver.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 10, Message = "Report 1" } ); workDoneObserver.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 20, Message = "Report 2" } ); workDoneObserver.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 30, Message = "Report 3" } ); workDoneObserver.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 40, Message = "Report 4" } @@ -251,7 +282,8 @@ public async Task Should_Support_Observing_Work_Done_From_Client_To_Server_Reque workDoneObserver.OnCompleted(); var results = await observable.Select( - z => z switch { + z => z switch + { WorkDoneProgressBegin begin => begin.Message, WorkDoneProgressReport begin => begin.Message, WorkDoneProgressEnd begin => begin.Message, @@ -272,25 +304,29 @@ public async Task Should_Support_Cancelling_Work_Done_From_Client_To_Server_Requ using var _ = workDoneObservable.Subscribe(x => data.Add(x)); using var workDoneObserver = await Server.WorkDoneManager.Create( - token, new WorkDoneProgressBegin { + token, new WorkDoneProgressBegin + { Cancellable = true, Message = "Begin", Percentage = 0, Title = "Work is pending" - }, onComplete: () => new WorkDoneProgressEnd { + }, onComplete: () => new WorkDoneProgressEnd + { Message = "End" } ); workDoneObserver.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 10, Message = "Report 1" } ); workDoneObserver.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 20, Message = "Report 2" } @@ -301,14 +337,16 @@ public async Task Should_Support_Cancelling_Work_Done_From_Client_To_Server_Requ workDoneObservable.Dispose(); workDoneObserver.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 30, Message = "Report 3" } ); workDoneObserver.OnNext( - new WorkDoneProgressReport { + new WorkDoneProgressReport + { Percentage = 40, Message = "Report 4" } @@ -318,7 +356,8 @@ public async Task Should_Support_Cancelling_Work_Done_From_Client_To_Server_Requ var results = data .Select( - z => z switch { + z => z switch + { WorkDoneProgressBegin begin => begin.Message, WorkDoneProgressReport begin => begin.Message, WorkDoneProgressEnd begin => begin.Message, diff --git a/test/Lsp.Integration.Tests/Properties.cs b/test/Lsp.Integration.Tests/Properties.cs index 80a070195..627fca850 100644 --- a/test/Lsp.Integration.Tests/Properties.cs +++ b/test/Lsp.Integration.Tests/Properties.cs @@ -1,3 +1,3 @@ -using System; +using Xunit; -[assembly: Xunit.CollectionBehavior(MaxParallelThreads = 10)] +[assembly: CollectionBehavior(MaxParallelThreads = 10)] diff --git a/test/Lsp.Integration.Tests/ProposalTests.cs b/test/Lsp.Integration.Tests/ProposalTests.cs index 002834c5e..d03efd0ae 100644 --- a/test/Lsp.Integration.Tests/ProposalTests.cs +++ b/test/Lsp.Integration.Tests/ProposalTests.cs @@ -1,25 +1,15 @@ -using System; -using System.Reactive; -using System.Reactive.Disposables; -using System.Reactive.Linq; -using System.Reactive.Threading.Tasks; -using System.Threading.Tasks; +using System.Threading.Tasks; using FluentAssertions; -using Lsp.Tests.Integration.Fixtures; -using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; -using TestingUtils; using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class ProposalTests : LanguageProtocolTestBase { @@ -31,11 +21,7 @@ public ProposalTests(ITestOutputHelper testOutputHelper) : base(new JsonRpcTestO public async Task Server_Should_Deserialize_Capabilities_As_Proposal_Types() { var (_, server) = await Initialize( - options => { - options.EnableProposals().EnableAllCapabilities(); - }, options => { - options.EnableProposals(); - } + options => { options.EnableProposals().EnableAllCapabilities(); }, options => { options.EnableProposals(); } ); server.ServerSettings.Capabilities.Should().BeOfType(); @@ -51,11 +37,7 @@ public async Task Server_Should_Deserialize_Capabilities_As_Proposal_Types() public async Task Client_Should_Deserialize_Capabilities_As_Proposal_Types() { var (client, _) = await Initialize( - options => { - options.EnableProposals().EnableAllCapabilities(); - }, options => { - options.EnableProposals(); - } + options => { options.EnableProposals().EnableAllCapabilities(); }, options => { options.EnableProposals(); } ); client.ServerSettings.Capabilities.Should().BeOfType(); diff --git a/test/Lsp.Integration.Tests/RecursiveResolutionTests.cs b/test/Lsp.Integration.Tests/RecursiveResolutionTests.cs index 205cca543..7cc1a14f1 100644 --- a/test/Lsp.Integration.Tests/RecursiveResolutionTests.cs +++ b/test/Lsp.Integration.Tests/RecursiveResolutionTests.cs @@ -18,7 +18,7 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class RecursiveResolutionTests : LanguageProtocolTestBase { @@ -31,7 +31,8 @@ public RecursiveResolutionTests(ITestOutputHelper testOutputHelper) : base(new J [InlineData(Side.Server)] public async Task Server_Can_Be_Injected_Into_Handler_After_Creation_Using_Registration(Side side) { - Func a = async () => { + Func a = async () => + { var (client, server) = await Initialize( options => { }, options => { } @@ -64,7 +65,8 @@ public async Task Server_Can_Be_Injected_Into_Handler_After_Creation_Using_Regis public async Task Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_Registration(Side side) { Func a = () => Initialize( - options => { + options => + { if (side == Side.Client) { options @@ -72,7 +74,8 @@ public async Task Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_R .AddHandler>(); } }, - options => { + options => + { if (side == Side.Server) { options @@ -91,7 +94,8 @@ public async Task Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_R public async Task Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_Description(Side side) { Func a = () => Initialize( - options => { + options => + { if (side == Side.Client) { options.Services @@ -99,7 +103,8 @@ public async Task Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_D .AddSingleton(JsonRpcHandlerDescription.Infer(typeof(ClassHandler))); } }, - options => { + options => + { if (side == Side.Server) { options.Services @@ -118,7 +123,8 @@ public async Task Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_D public async Task Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_Injection(Side side) { Func a = () => Initialize( - options => { + options => + { if (side == Side.Client) { options.Services @@ -126,7 +132,8 @@ public async Task Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_I .AddSingleton>(); } }, - options => { + options => + { if (side == Side.Server) { options.Services @@ -145,14 +152,16 @@ public async Task Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_I public async Task Server_Facade_Can_Be_Injected_Into_Handler_During_Creation_Using_Registration(Side side) { Func a = () => Initialize( - options => { + options => + { if (side == Side.Client) { options .AddHandler>(); } }, - options => { + options => + { if (side == Side.Server) { options @@ -169,14 +178,16 @@ public async Task Server_Facade_Can_Be_Injected_Into_Handler_During_Creation_Usi public async Task Server_Facade_Can_Be_Injected_Into_Handler_During_Creation_Using_Description(Side side) { Func a = () => Initialize( - options => { + options => + { if (side == Side.Client) { options.Services .AddSingleton(JsonRpcHandlerDescription.Infer(typeof(InterfaceHandler))); } }, - options => { + options => + { if (side == Side.Server) { options.Services @@ -193,14 +204,16 @@ public async Task Server_Facade_Can_Be_Injected_Into_Handler_During_Creation_Usi public async Task Server_Facade_Can_Injected_Into_Handler_During_Creation_Using_Injection(Side side) { Func a = () => Initialize( - options => { + options => + { if (side == Side.Client) { options.Services .AddSingleton>(); } }, - options => { + options => + { if (side == Side.Server) { options.Services @@ -217,13 +230,15 @@ public async Task Server_Facade_Can_Injected_Into_Handler_During_Creation_Using_ public async Task Should_Allow_Nested_Registration_During_Creation_Using_Registration(Side side) { var (client, server) = await Initialize( - options => { + options => + { if (side == Side.Client) { options.AddHandler(); } }, - options => { + options => + { if (side == Side.Server) { options.AddHandler(); @@ -254,13 +269,15 @@ public async Task Should_Allow_Nested_Registration_During_Creation_Using_Registr public async Task Should_Allow_Nested_Registration_During_Creation_Using_Description(Side side) { var (client, server) = await Initialize( - options => { + options => + { if (side == Side.Client) { options.Services.AddSingleton(JsonRpcHandlerDescription.Infer(typeof(NestedClientHandler))); } }, - options => { + options => + { if (side == Side.Server) { options.Services.AddSingleton(JsonRpcHandlerDescription.Infer(typeof(NestedServerHandler))); @@ -291,13 +308,15 @@ public async Task Should_Allow_Nested_Registration_During_Creation_Using_Descrip public async Task Should_Allow_Nested_Registration_During_Creation_Using_Injection(Side side) { var (client, server) = await Initialize( - options => { + options => + { if (side == Side.Client) { options.Services.AddSingleton(); } }, - options => { + options => + { if (side == Side.Server) { options.Services.AddSingleton(); @@ -334,7 +353,7 @@ public class ClassRequest : IRequest } [Method(nameof(ClassRequest))] - class ClassHandler : IJsonRpcRequestHandler where T : class + private class ClassHandler : IJsonRpcRequestHandler where T : class { // ReSharper disable once NotAccessedField.Local private readonly T _jsonRpcServer; @@ -344,7 +363,10 @@ public ClassHandler(T jsonRpcServer) _jsonRpcServer = jsonRpcServer; } - public Task Handle(ClassRequest classRequest, CancellationToken cancellationToken) => throw new NotImplementedException(); + public Task Handle(ClassRequest classRequest, CancellationToken cancellationToken) + { + throw new NotImplementedException(); + } } [Method(nameof(InterfaceRequest))] @@ -353,7 +375,7 @@ public class InterfaceRequest : IRequest } [Method(nameof(InterfaceRequest))] - class InterfaceHandler : IJsonRpcRequestHandler + private class InterfaceHandler : IJsonRpcRequestHandler { // ReSharper disable once NotAccessedField.Local private readonly T _jsonRpcServer; @@ -363,7 +385,10 @@ public InterfaceHandler(T jsonRpcServer) _jsonRpcServer = jsonRpcServer; } - public Task Handle(InterfaceRequest request, CancellationToken cancellationToken) => throw new NotImplementedException(); + public Task Handle(InterfaceRequest request, CancellationToken cancellationToken) + { + throw new NotImplementedException(); + } } [Method(nameof(NestedRequest))] @@ -372,7 +397,7 @@ public class NestedRequest : IRequest } [Method(nameof(NestedRequest))] - class NestedClientHandler : IJsonRpcRequestHandler + private class NestedClientHandler : IJsonRpcRequestHandler { // ReSharper disable once NotAccessedField.Local private readonly ILanguageClientFacade _languageClientFacade; @@ -383,11 +408,14 @@ public NestedClientHandler(ILanguageClientFacade languageClientFacade) languageClientFacade.Register(r => r.AddHandler>()); } - public Task Handle(NestedRequest request, CancellationToken cancellationToken) => throw new NotImplementedException(); + public Task Handle(NestedRequest request, CancellationToken cancellationToken) + { + throw new NotImplementedException(); + } } [Method(nameof(NestedRequest))] - class NestedServerHandler : IJsonRpcRequestHandler + private class NestedServerHandler : IJsonRpcRequestHandler { // ReSharper disable once NotAccessedField.Local private readonly ILanguageServerFacade _languageClientFacade; @@ -398,7 +426,10 @@ public NestedServerHandler(ILanguageServerFacade languageClientFacade) languageClientFacade.Register(z => z.AddHandler>()); } - public Task Handle(NestedRequest request, CancellationToken cancellationToken) => throw new NotImplementedException(); + public Task Handle(NestedRequest request, CancellationToken cancellationToken) + { + throw new NotImplementedException(); + } } } } diff --git a/test/Lsp.Integration.Tests/RenameTests.cs b/test/Lsp.Integration.Tests/RenameTests.cs index 1ea72c999..cffef9bc7 100644 --- a/test/Lsp.Integration.Tests/RenameTests.cs +++ b/test/Lsp.Integration.Tests/RenameTests.cs @@ -4,7 +4,6 @@ using System.Threading.Tasks; using FluentAssertions; using NSubstitute; -using NSubstitute.Callbacks; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Client; @@ -19,7 +18,7 @@ using Xunit.Abstractions; using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class RenameTests : LanguageProtocolTestBase { @@ -37,7 +36,8 @@ public async Task Should_Handle_Rename_With_No_Value() { _prepareRename.Invoke(Arg.Any(), Arg.Any(), Arg.Any()) .Returns( - call => { + call => + { var pos = call.Arg().Position; return new RangeOrPlaceholderRange( new Range( @@ -50,17 +50,24 @@ public async Task Should_Handle_Rename_With_No_Value() _rename.Invoke(Arg.Any(), Arg.Any(), Arg.Any()) .Returns( - new WorkspaceEdit() { - DocumentChanges = new Container(new WorkspaceEditDocumentChange(new CreateFile() { - Uri = DocumentUri.FromFileSystemPath("/abcd/create.cs") - })) + new WorkspaceEdit + { + DocumentChanges = new Container( + new WorkspaceEditDocumentChange( + new CreateFile + { + Uri = DocumentUri.FromFileSystemPath("/abcd/create.cs") + } + ) + ) } ); var (client, _) = await Initialize(ClientOptionsAction, ServerOptionsAction); var result = await client.PrepareRename( - new PrepareRenameParams() { + new PrepareRenameParams + { Position = ( 1, 1 ), TextDocument = DocumentUri.FromFileSystemPath("/abcd/file.cs") }, @@ -70,7 +77,8 @@ public async Task Should_Handle_Rename_With_No_Value() result.Should().NotBeNull(); var renameResponse = await client.RequestRename( - new RenameParams() { + new RenameParams + { Position = result!.Range!.Start, NewName = "newname", TextDocument = DocumentUri.FromFileSystemPath("/abcd/file.cs") @@ -96,7 +104,8 @@ public async Task Should_Handle_Prepare_Rename_With_No_Value() var (client, _) = await Initialize(ClientOptionsAction, ServerOptionsAction); var result = await client.PrepareRename( - new PrepareRenameParams() { + new PrepareRenameParams + { Position = ( 1, 1 ), TextDocument = DocumentUri.FromFileSystemPath("/abcd/file.cs") }, @@ -111,7 +120,8 @@ public async Task Should_Handle_Prepare_Rename_With_Range() { _prepareRename.Invoke(Arg.Any(), Arg.Any(), Arg.Any()) .Returns( - call => { + call => + { var pos = call.Arg().Position; return new RangeOrPlaceholderRange( new Range( @@ -125,7 +135,8 @@ public async Task Should_Handle_Prepare_Rename_With_Range() var (client, _) = await Initialize(ClientOptionsAction, ServerOptionsAction); var result = await client.PrepareRename( - new PrepareRenameParams() { + new PrepareRenameParams + { Position = ( 1, 1 ), TextDocument = DocumentUri.FromFileSystemPath("/abcd/file.cs") }, @@ -140,10 +151,12 @@ public async Task Should_Handle_Prepare_Rename_With_PlaceholderRange() { _prepareRename.Invoke(Arg.Any(), Arg.Any(), Arg.Any()) .Returns( - call => { + call => + { var pos = call.Arg().Position; return new RangeOrPlaceholderRange( - new PlaceholderRange() { + new PlaceholderRange + { Range = new Range( pos, @@ -158,7 +171,8 @@ public async Task Should_Handle_Prepare_Rename_With_PlaceholderRange() var (client, _) = await Initialize(ClientOptionsAction, ServerOptionsAction); var result = await client.PrepareRename( - new PrepareRenameParams() { + new PrepareRenameParams + { Position = ( 1, 1 ), TextDocument = DocumentUri.FromFileSystemPath("/abcd/file.cs") }, @@ -174,7 +188,8 @@ public async Task Should_Handle_Prepare_Rename_With_DefaultBehavior() _prepareRename.Invoke(Arg.Any(), Arg.Any(), Arg.Any()) .Returns( call => new RangeOrPlaceholderRange( - new RenameDefaultBehavior() { + new RenameDefaultBehavior + { DefaultBehavior = true } ) @@ -183,7 +198,8 @@ public async Task Should_Handle_Prepare_Rename_With_DefaultBehavior() var (client, _) = await Initialize(ClientOptionsAction, ServerOptionsAction); var result = await client.PrepareRename( - new PrepareRenameParams() { + new PrepareRenameParams + { Position = ( 1, 1 ), TextDocument = DocumentUri.FromFileSystemPath("/abcd/file.cs") }, @@ -210,12 +226,14 @@ await client.DelayUntil( private void ServerOptionsAction(LanguageServerOptions obj) { obj.OnPrepareRename( - _prepareRename, (_, _) => new RenameRegistrationOptions() { + _prepareRename, (_, _) => new RenameRegistrationOptions + { DocumentSelector = DocumentSelector.ForLanguage("csharp") } ); obj.OnRename( - _rename, (_, _) =>new RenameRegistrationOptions() { + _rename, (_, _) => new RenameRegistrationOptions + { DocumentSelector = DocumentSelector.ForLanguage("csharp"), PrepareProvider = true, } @@ -225,7 +243,8 @@ private void ServerOptionsAction(LanguageServerOptions obj) private void ClientOptionsAction(LanguageClientOptions obj) { obj.WithCapability( - new RenameCapability() { + new RenameCapability + { PrepareSupport = true, PrepareSupportDefaultBehavior = PrepareSupportDefaultBehavior.Identifier } diff --git a/test/Lsp.Integration.Tests/RequestCancellationTests.cs b/test/Lsp.Integration.Tests/RequestCancellationTests.cs index d028392cc..3185bfc59 100644 --- a/test/Lsp.Integration.Tests/RequestCancellationTests.cs +++ b/test/Lsp.Integration.Tests/RequestCancellationTests.cs @@ -18,7 +18,7 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class RequestCancellationTests : LanguageProtocolTestBase { @@ -31,11 +31,13 @@ public async Task Should_Cancel_Pending_Requests() { var (client, _) = await Initialize(ConfigureClient, ConfigureServer); - Func> action = () => { + var action = () => + { var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(10)); CancellationToken.Register(cts.Cancel); return client.TextDocument.RequestCompletion( - new CompletionParams { + new CompletionParams + { TextDocument = "/a/file.cs" }, cts.Token ).AsTask(); @@ -49,14 +51,17 @@ public async Task Should_Abandon_Pending_Requests_For_Text_Changes() var (client, _) = await Initialize(ConfigureClient, ConfigureServer); var request1 = client.TextDocument.RequestCompletion( - new CompletionParams { + new CompletionParams + { TextDocument = "/a/file.cs" }, CancellationToken ).AsTask(); client.TextDocument.DidChangeTextDocument( - new DidChangeTextDocumentParams { - TextDocument = new OptionalVersionedTextDocumentIdentifier { + new DidChangeTextDocumentParams + { + TextDocument = new OptionalVersionedTextDocumentIdentifier + { Uri = "/a/file.cs", Version = 123, }, @@ -71,16 +76,19 @@ public async Task Should_Abandon_Pending_Requests_For_Text_Changes() [Fact] public async Task Should_Cancel_Requests_After_Timeout() { - Func action = async () => { + Func action = async () => + { var (client, _) = await Initialize( - ConfigureClient, x => { + ConfigureClient, x => + { ConfigureServer(x); x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(3000)); } ); await client.TextDocument.RequestCompletion( - new CompletionParams { + new CompletionParams + { TextDocument = "/a/file.cs" }, CancellationToken ).AsTask(); @@ -91,16 +99,19 @@ await client.TextDocument.RequestCompletion( [Fact] public async Task Should_Cancel_Requests_After_Timeout_without_Content_Modified() { - Func action = async () => { + Func action = async () => + { var (client, _) = await Initialize( - ConfigureClient, x => { + ConfigureClient, x => + { ConfigureServer(x); x.WithContentModifiedSupport(false).WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(3000)); } ); await client.TextDocument.RequestCompletion( - new CompletionParams { + new CompletionParams + { TextDocument = "/a/file.cs" }, CancellationToken ).AsTask(); @@ -112,16 +123,19 @@ await client.TextDocument.RequestCompletion( public async Task Can_Publish_Diagnostics_Delayed() { var (_, server) = await Initialize( - ConfigureClient, x => { + ConfigureClient, x => + { ConfigureServer(x); x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(10000)); } ); server.TextDocument.PublishDiagnostics( - new PublishDiagnosticsParams { + new PublishDiagnosticsParams + { Diagnostics = new Container( - new Diagnostic { + new Diagnostic + { Message = "asdf", } ), @@ -137,11 +151,14 @@ public async Task Can_Publish_Diagnostics_Delayed() _diagnostics.Should().HaveCount(1); } - private readonly ConcurrentDictionary> _diagnostics = new ConcurrentDictionary>(); + private readonly ConcurrentDictionary> _diagnostics = + new ConcurrentDictionary>(); - private void ConfigureClient(LanguageClientOptions options) => + private void ConfigureClient(LanguageClientOptions options) + { options.OnPublishDiagnostics( - async (request, ct) => { + async (request, ct) => + { try { TestOptions.ClientLoggerFactory.CreateLogger("test").LogCritical("start"); @@ -154,17 +171,19 @@ private void ConfigureClient(LanguageClientOptions options) => } } ); + } private void ConfigureServer(LanguageServerOptions options) { options.WithContentModifiedSupport(true); options.OnCompletion( - async (x, ct) => { + async (x, ct) => + { await Task.Delay(50000, ct); return new CompletionList(); }, (_, _) => new CompletionRegistrationOptions() ); - options.OnDidChangeTextDocument(async x => { await Task.Delay(20); }, (_, _) =>new TextDocumentChangeRegistrationOptions()); + options.OnDidChangeTextDocument(async x => { await Task.Delay(20); }, (_, _) => new TextDocumentChangeRegistrationOptions()); } } } diff --git a/test/Lsp.Integration.Tests/ShowMessageTests.cs b/test/Lsp.Integration.Tests/ShowMessageTests.cs index 92cd016af..3424cf64f 100644 --- a/test/Lsp.Integration.Tests/ShowMessageTests.cs +++ b/test/Lsp.Integration.Tests/ShowMessageTests.cs @@ -14,11 +14,13 @@ using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class ShowMessageTests : LanguageProtocolTestBase { - public ShowMessageTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper).WithWaitTime(TimeSpan.FromMilliseconds(500))) + public ShowMessageTests(ITestOutputHelper outputHelper) : base( + new JsonRpcTestOptions().ConfigureForXUnit(outputHelper).WithWaitTime(TimeSpan.FromMilliseconds(500)) + ) { } @@ -34,12 +36,14 @@ public async Task Should_Show_Messages_Through_Window_Extension_Methods() server.Window.ShowWarning("Uh-oh..."); server.Window.Show("Just gotta let you know!"); server.Window.Show( - new ShowMessageParams { + new ShowMessageParams + { Type = MessageType.Log, Message = "1234" } ); server.Window.ShowMessage( - new ShowMessageParams { + new ShowMessageParams + { Type = MessageType.Log, Message = "1234" } ); @@ -63,12 +67,14 @@ public async Task Should_Show_Messages_Through_Server_Extension_Methods() server.ShowWarning("Uh-oh..."); server.Show("Just gotta let you know!"); server.Show( - new ShowMessageParams { + new ShowMessageParams + { Type = MessageType.Log, Message = "1234" } ); server.ShowMessage( - new ShowMessageParams { + new ShowMessageParams + { Type = MessageType.Log, Message = "1234" } ); @@ -82,7 +88,10 @@ public async Task Should_Show_Messages_Through_Server_Extension_Methods() _receivedMessages.Should().Contain(z => z.Type == MessageType.Log).And.Subject.Count(z => z.Type == MessageType.Log).Should().Be(3); } - private void ConfigureClient(LanguageClientOptions options) => options.OnShowMessage(request => { _receivedMessages.Add(request); }); + private void ConfigureClient(LanguageClientOptions options) + { + options.OnShowMessage(request => { _receivedMessages.Add(request); }); + } private void ConfigureServer(LanguageServerOptions options) { diff --git a/test/Lsp.Integration.Tests/TypedCallHierarchyTests.cs b/test/Lsp.Integration.Tests/TypedCallHierarchyTests.cs index 252524f53..3da1c2560 100644 --- a/test/Lsp.Integration.Tests/TypedCallHierarchyTests.cs +++ b/test/Lsp.Integration.Tests/TypedCallHierarchyTests.cs @@ -1,28 +1,22 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Linq; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using FluentAssertions; -using Lsp.Tests.Integration.Fixtures; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; +using Lsp.Integration.Tests.Fixtures; using NSubstitute; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using Serilog.Events; -using TestingUtils; using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class TypedCallHierarchyTests : LanguageProtocolTestBase { @@ -38,7 +32,8 @@ public async Task Should_Aggregate_With_All_Related_Handlers() var outgoingHandlerA = Substitute.For, Task?>>>(); var outgoingHandlerB = Substitute.For, Task?>>>(); var (client, _) = await Initialize( - options => { options.EnableAllCapabilities(); }, options => { + options => { options.EnableAllCapabilities(); }, options => + { var identifier = Substitute.For(); identifier.GetTextDocumentAttributes(Arg.Any()).Returns( call => new TextDocumentAttributes(call.ArgAt(0), "file", "csharp") @@ -48,11 +43,14 @@ public async Task Should_Aggregate_With_All_Related_Handlers() options.OnCallHierarchy( @params => Task.FromResult( new Container?>( - new CallHierarchyItem { + new CallHierarchyItem + { Name = "Test", Kind = SymbolKind.Boolean, - Data = new Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -63,7 +61,8 @@ public async Task Should_Aggregate_With_All_Related_Handlers() )!, incomingHandlerA, outgoingHandlerA, - (_, _) => new() { + (_, _) => new() + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); @@ -71,10 +70,12 @@ public async Task Should_Aggregate_With_All_Related_Handlers() options.OnCallHierarchy( @params => Task.FromResult( new Container?>( - new CallHierarchyItem { + new CallHierarchyItem + { Name = "Test Nested", Kind = SymbolKind.Constant, - Data = new Nested { + Data = new Nested + { Date = DateTimeOffset.MinValue } } @@ -82,7 +83,8 @@ public async Task Should_Aggregate_With_All_Related_Handlers() )!, incomingHandlerB, outgoingHandlerB, - (_, _) => new() { + (_, _) => new() + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); @@ -90,7 +92,8 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ); var items = await client.RequestCallHierarchyPrepare( - new CallHierarchyPrepareParams() { + new CallHierarchyPrepareParams + { TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), } ); @@ -98,10 +101,14 @@ public async Task Should_Aggregate_With_All_Related_Handlers() var lens = items.ToArray(); lens.Select(z => z.Name).Should().Contain(new[] { "Test", "Test Nested" }); - var incomingItems = await Task.WhenAll(lens.Select(z => client.RequestCallHierarchyIncoming(new CallHierarchyIncomingCallsParams() { Item = z }).AsTask())); + var incomingItems = await Task.WhenAll( + lens.Select(z => client.RequestCallHierarchyIncoming(new CallHierarchyIncomingCallsParams { Item = z }).AsTask()) + ); incomingHandlerA.Received(1).Invoke(Arg.Any>()); incomingHandlerB.Received(1).Invoke(Arg.Any>()); - var outgoingItems = await Task.WhenAll(lens.Select(z => client.RequestCallHierarchyOutgoing(new CallHierarchyOutgoingCallsParams() { Item = z }).AsTask())); + var outgoingItems = await Task.WhenAll( + lens.Select(z => client.RequestCallHierarchyOutgoing(new CallHierarchyOutgoingCallsParams { Item = z }).AsTask()) + ); outgoingHandlerA.Received(1).Invoke(Arg.Any>()); outgoingHandlerB.Received(1).Invoke(Arg.Any>()); } @@ -112,15 +119,19 @@ public async Task Should_Resolve_With_Data_Capability() var incomingHandler = Substitute.For, Task?>>>(); var outgoingHandler = Substitute.For, Task?>>>(); var (client, _) = await Initialize( - options => { options.EnableAllCapabilities(); }, options => { + options => { options.EnableAllCapabilities(); }, options => + { options.OnCallHierarchy( @params => Task.FromResult( new Container?>( - new CallHierarchyItem { + new CallHierarchyItem + { Name = "Test", Kind = SymbolKind.Boolean, - Data = new Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -131,7 +142,8 @@ public async Task Should_Resolve_With_Data_Capability() )!, incomingHandler, outgoingHandler, - (_, _) => new() { + (_, _) => new() + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); @@ -139,16 +151,17 @@ public async Task Should_Resolve_With_Data_Capability() ); var items = await client.RequestCallHierarchyPrepare( - new CallHierarchyPrepareParams() { + new CallHierarchyPrepareParams + { TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), } ); var item = items.Single(); - var incomingItems = await client.RequestCallHierarchyIncoming(new CallHierarchyIncomingCallsParams() { Item = item }); + var incomingItems = await client.RequestCallHierarchyIncoming(new CallHierarchyIncomingCallsParams { Item = item }); incomingHandler.Received(1).Invoke(Arg.Any>()); - var outgoingItems = await client.RequestCallHierarchyOutgoing(new CallHierarchyOutgoingCallsParams() { Item = item }); + var outgoingItems = await client.RequestCallHierarchyOutgoing(new CallHierarchyOutgoingCallsParams { Item = item }); outgoingHandler.Received(1).Invoke(Arg.Any>()); } @@ -158,16 +171,21 @@ public async Task Should_Resolve_With_Partial_Data_Capability() var incomingHandler = Substitute.For, IObserver>>>(); var outgoingHandler = Substitute.For, IObserver>>>(); var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCallHierarchy( - (completionParams, observer) => { + (completionParams, observer) => + { var a = new Container?>( new Container?>( - new CallHierarchyItem { + new CallHierarchyItem + { Name = "Test", Kind = SymbolKind.Boolean, - Data = new Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -180,12 +198,14 @@ public async Task Should_Resolve_With_Partial_Data_Capability() observer.OnNext(a); observer.OnCompleted(); }, - (a, b) => { + (a, b) => + { incomingHandler(a, b); b.OnNext(Enumerable.Empty()); b.OnCompleted(); }, - (a, b) => { + (a, b) => + { outgoingHandler(a, b); b.OnNext(Enumerable.Empty()); b.OnCompleted(); @@ -196,19 +216,19 @@ public async Task Should_Resolve_With_Partial_Data_Capability() ); var items = await client - .RequestCallHierarchyPrepare(new CallHierarchyPrepareParams() { TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), }) + .RequestCallHierarchyPrepare(new CallHierarchyPrepareParams { TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), }) .Take(1) .ToTask(CancellationToken); var item = items.Single(); var incomingItems = await client - .RequestCallHierarchyIncoming(new CallHierarchyIncomingCallsParams() { Item = item }) + .RequestCallHierarchyIncoming(new CallHierarchyIncomingCallsParams { Item = item }) .Take(1) .ToTask(CancellationToken); incomingHandler.Received(1).Invoke(Arg.Any>(), Arg.Any>>()); var outgoingItems = await client - .RequestCallHierarchyOutgoing(new CallHierarchyOutgoingCallsParams() { Item = item }) + .RequestCallHierarchyOutgoing(new CallHierarchyOutgoingCallsParams { Item = item }) .Take(1) .ToTask(CancellationToken); outgoingHandler.Received(1).Invoke(Arg.Any>(), Arg.Any>>()); diff --git a/test/Lsp.Integration.Tests/TypedCodeActionTests.cs b/test/Lsp.Integration.Tests/TypedCodeActionTests.cs index 02373175d..d155a5a4b 100644 --- a/test/Lsp.Integration.Tests/TypedCodeActionTests.cs +++ b/test/Lsp.Integration.Tests/TypedCodeActionTests.cs @@ -1,12 +1,10 @@ using System; -using System.ComponentModel; using System.Linq; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using FluentAssertions; -using Lsp.Tests.Integration.Fixtures; -using Newtonsoft.Json; +using Lsp.Integration.Tests.Fixtures; using Newtonsoft.Json.Linq; using NSubstitute; using OmniSharp.Extensions.JsonRpc.Testing; @@ -15,12 +13,10 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using Serilog.Events; -using TestingUtils; using Xunit; using Xunit.Abstractions; -using Nested = Lsp.Tests.Integration.Fixtures.Nested; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class TypedCodeActionTests : LanguageProtocolTestBase { @@ -32,7 +28,8 @@ public TypedCodeActionTests(ITestOutputHelper outputHelper) : base(new JsonRpcTe public async Task Should_Aggregate_With_All_Related_Handlers() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { var identifier = Substitute.For(); identifier.GetTextDocumentAttributes(Arg.Any()).Returns( call => new TextDocumentAttributes(call.ArgAt(0), "file", "csharp") @@ -40,18 +37,23 @@ public async Task Should_Aggregate_With_All_Related_Handlers() options.AddTextDocumentIdentifier(identifier); options.OnCodeAction( - codeActionParams => { + codeActionParams => + { return Task.FromResult( - new CodeActionContainer( - new CodeAction { + new CodeActionContainer( + new CodeAction + { Title = "data-a", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "data-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -61,48 +63,53 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - action => { - return Task.FromResult(action with { Command = action.Command with { Name = "resolved-a" } }); - }, - (_, _) => new CodeActionRegistrationOptions { + action => { return Task.FromResult(action with { Command = action.Command with { Name = "resolved-a" } }); }, + (_, _) => new CodeActionRegistrationOptions + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); options.OnCodeAction( - codeActionParams => { + codeActionParams => + { return Task.FromResult( new CodeActionContainer( - new CodeAction { + new CodeAction + { Title = "nested-b", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "nested-b", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Nested { + Data = new Nested + { Date = DateTimeOffset.Now } } ) ); }, - action => { - return Task.FromResult(action with { Command = action.Command with { Name = "resolved-b" } }); - }, - (_, _) => new CodeActionRegistrationOptions { + action => { return Task.FromResult(action with { Command = action.Command with { Name = "resolved-b" } }); }, + (_, _) => new CodeActionRegistrationOptions + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); options.OnCodeAction( - codeActionParams => { + codeActionParams => + { return Task.FromResult( new CommandOrCodeActionContainer( - new CodeAction { + new CodeAction + { Title = "no-data-c", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "no-data-c", Arguments = JArray.FromObject(new object[] { 1, "2", false }) } @@ -110,22 +117,24 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - action => { - return Task.FromResult(action with { Command = action.Command with { Name = "resolved-c" } }); - }, - (_, _) => new CodeActionRegistrationOptions { + action => { return Task.FromResult(action with { Command = action.Command with { Name = "resolved-c" } }); }, + (_, _) => new CodeActionRegistrationOptions + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); options.OnCodeAction( - codeActionParams => { + codeActionParams => + { return Task.FromResult( new CommandOrCodeActionContainer( - new CodeAction { + new CodeAction + { Title = "not-included", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "not-included", Arguments = JArray.FromObject(new object[] { 1, "2", false }) } @@ -133,10 +142,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - action => { - return Task.FromResult(action with { Command = action.Command with { Name = "resolved-d" } }); - }, - (_, _) => new CodeActionRegistrationOptions { + action => { return Task.FromResult(action with { Command = action.Command with { Name = "resolved-d" } }); }, + (_, _) => new CodeActionRegistrationOptions + { DocumentSelector = DocumentSelector.ForLanguage("vb") } ); @@ -144,7 +152,8 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ); var codeAction = await client.RequestCodeAction( - new CodeActionParams { + new CodeActionParams + { TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), } ); @@ -161,20 +170,26 @@ public async Task Should_Aggregate_With_All_Related_Handlers() public async Task Should_Resolve_With_Data_Capability() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCodeAction( - (codeActionParams, capability, token) => { + (codeActionParams, capability, token) => + { return Task.FromResult( - new CodeActionContainer( - new CodeAction { + new CodeActionContainer( + new CodeAction + { Title = "name", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -184,7 +199,8 @@ public async Task Should_Resolve_With_Data_Capability() ) ); }, - (codeAction, capability, token) => { + (codeAction, capability, token) => + { codeAction.Data.Id.Should().NotBeEmpty(); codeAction.Data.Child.Should().NotBeNull(); codeAction.Data.Name.Should().Be("name"); @@ -207,19 +223,25 @@ public async Task Should_Resolve_With_Data_Capability() public async Task Should_Resolve_With_Partial_Data_Capability() { var (client, _) = await Initialize( - options => { }, options => { - options.ObserveCodeAction( - (codeActionParams, observer, capability, token) => { - var a = new CodeActionContainer( - new CodeAction { + options => { }, options => + { + options.ObserveCodeAction( + (codeActionParams, observer, capability, token) => + { + var a = new CodeActionContainer( + new CodeAction + { Title = "name", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -231,7 +253,8 @@ public async Task Should_Resolve_With_Partial_Data_Capability() observer.OnNext(a); observer.OnCompleted(); }, - (codeAction, capability, token) => { + (codeAction, capability, token) => + { codeAction.Data.Id.Should().NotBeEmpty(); codeAction.Data.Child.Should().NotBeNull(); codeAction.Data.Name.Should().Be("name"); @@ -252,20 +275,26 @@ public async Task Should_Resolve_With_Partial_Data_Capability() public async Task Should_Resolve_With_Data_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCodeAction( - (codeActionParams, token) => { + (codeActionParams, token) => + { return Task.FromResult( - new CodeActionContainer( - new CodeAction { + new CodeActionContainer( + new CodeAction + { Title = "execute-a", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -275,7 +304,8 @@ public async Task Should_Resolve_With_Data_CancellationToken() ) ); }, - (codeAction, token) => { + (codeAction, token) => + { codeAction.Data.Id.Should().NotBeEmpty(); codeAction.Data.Child.Should().NotBeNull(); codeAction.Data.Name.Should().Be("name"); @@ -298,19 +328,25 @@ public async Task Should_Resolve_With_Data_CancellationToken() public async Task Should_Resolve_With_Partial_Data_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { - options.ObserveCodeAction( - (codeActionParams, observer, token) => { - var a = new CodeActionContainer( - new CodeAction { + options => { }, options => + { + options.ObserveCodeAction( + (codeActionParams, observer, token) => + { + var a = new CodeActionContainer( + new CodeAction + { Title = "execute-a", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -322,7 +358,8 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() observer.OnNext(a); observer.OnCompleted(); }, - (codeAction, token) => { + (codeAction, token) => + { codeAction.Data.Id.Should().NotBeEmpty(); codeAction.Data.Child.Should().NotBeNull(); codeAction.Data.Name.Should().Be("name"); @@ -343,20 +380,26 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() public async Task Should_Resolve_With_Data() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCodeAction( - codeActionParams => { + codeActionParams => + { return Task.FromResult( - new CodeActionContainer( - new CodeAction { + new CodeActionContainer( + new CodeAction + { Title = "execute-a", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -366,7 +409,8 @@ public async Task Should_Resolve_With_Data() ) ); }, - codeAction => { + codeAction => + { codeAction.Data.Id.Should().NotBeEmpty(); codeAction.Data.Child.Should().NotBeNull(); codeAction.Data.Name.Should().Be("name"); @@ -389,19 +433,25 @@ public async Task Should_Resolve_With_Data() public async Task Should_Resolve_With_Partial_Data() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveCodeAction( - (codeActionParams, observer) => { + (codeActionParams, observer) => + { var a = new CodeActionContainer( - new CodeAction { + new CodeAction + { Title = "execute-a", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -413,7 +463,8 @@ public async Task Should_Resolve_With_Partial_Data() observer.OnNext(a); observer.OnCompleted(); }, - codeAction => { + codeAction => + { codeAction.Data.Id.Should().NotBeEmpty(); codeAction.Data.Child.Should().NotBeNull(); codeAction.Data.Name.Should().Be("name"); @@ -435,15 +486,19 @@ public async Task Should_Resolve_With_Partial_Data() public async Task Should_Resolve_Capability() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCodeAction( - (codeActionParams, capability, token) => { + (codeActionParams, capability, token) => + { return Task.FromResult( new CommandOrCodeActionContainer( - new CodeAction { + new CodeAction + { Title = "execute-a", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) } @@ -451,7 +506,8 @@ public async Task Should_Resolve_Capability() ) ); }, - (codeAction, capability, token) => { + (codeAction, capability, token) => + { return Task.FromResult(codeAction with { Command = codeAction.Command with { Name = "resolved" } }); }, (_, _) => new CodeActionRegistrationOptions() @@ -471,14 +527,18 @@ public async Task Should_Resolve_Capability() public async Task Should_Resolve_Partial_Capability() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveCodeAction( - (codeActionParams, observer, capability, token) => { + (codeActionParams, observer, capability, token) => + { var a = new CommandOrCodeActionContainer( - new CodeAction { + new CodeAction + { Title = "execute-a", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -488,7 +548,8 @@ public async Task Should_Resolve_Partial_Capability() observer.OnNext(a); observer.OnCompleted(); }, - (codeAction, capability, token) => { + (codeAction, capability, token) => + { return Task.FromResult(codeAction with { Command = codeAction.Command with { Name = "resolved" } }); }, (_, _) => new CodeActionRegistrationOptions() @@ -506,15 +567,19 @@ public async Task Should_Resolve_Partial_Capability() public async Task Should_Resolve_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCodeAction( - (codeActionParams, token) => { + (codeActionParams, token) => + { return Task.FromResult( new CommandOrCodeActionContainer( - new CodeAction { + new CodeAction + { Title = "execute-a", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -522,9 +587,7 @@ public async Task Should_Resolve_CancellationToken() ) ); }, - (codeAction, token) => { - return Task.FromResult(codeAction with { Command = codeAction.Command with { Name = "resolved" } }); - }, + (codeAction, token) => { return Task.FromResult(codeAction with { Command = codeAction.Command with { Name = "resolved" } }); }, (_, _) => new CodeActionRegistrationOptions() ); } @@ -542,14 +605,18 @@ public async Task Should_Resolve_CancellationToken() public async Task Should_Resolve_Partial_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveCodeAction( - (codeActionParams, observer, token) => { + (codeActionParams, observer, token) => + { var a = new CommandOrCodeActionContainer( - new CodeAction { + new CodeAction + { Title = "execute-a", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -559,9 +626,7 @@ public async Task Should_Resolve_Partial_CancellationToken() observer.OnNext(a); observer.OnCompleted(); }, - (codeAction, token) => { - return Task.FromResult(codeAction with { Command = codeAction.Command with { Name = "resolved" } }); - }, + (codeAction, token) => { return Task.FromResult(codeAction with { Command = codeAction.Command with { Name = "resolved" } }); }, (_, _) => new CodeActionRegistrationOptions() ); } @@ -577,15 +642,19 @@ public async Task Should_Resolve_Partial_CancellationToken() public async Task Should_Resolve() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCodeAction( - codeActionParams => { + codeActionParams => + { return Task.FromResult( new CommandOrCodeActionContainer( - new CodeAction { + new CodeAction + { Title = "execute-a", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -593,9 +662,7 @@ public async Task Should_Resolve() ) ); }, - codeAction => { - return Task.FromResult(codeAction with { Command = codeAction.Command with { Name = "resolved" } }); - }, + codeAction => { return Task.FromResult(codeAction with { Command = codeAction.Command with { Name = "resolved" } }); }, (_, _) => new CodeActionRegistrationOptions() ); } @@ -613,14 +680,18 @@ public async Task Should_Resolve() public async Task Should_Resolve_Partial() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveCodeAction( - (codeActionParams, observer) => { + (codeActionParams, observer) => + { var a = new CommandOrCodeActionContainer( - new CodeAction { + new CodeAction + { Title = "execute-a", Kind = CodeActionKind.QuickFix, - Command = new Command { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -630,9 +701,7 @@ public async Task Should_Resolve_Partial() observer.OnNext(a); observer.OnCompleted(); }, - codeAction => { - return Task.FromResult(codeAction with { Command = codeAction.Command! with { Name = "resolved"}}); - }, + codeAction => { return Task.FromResult(codeAction with { Command = codeAction.Command! with { Name = "resolved" } }); }, (_, _) => new CodeActionRegistrationOptions() ); } diff --git a/test/Lsp.Integration.Tests/TypedCodeLensTests.cs b/test/Lsp.Integration.Tests/TypedCodeLensTests.cs index 7e70e8bf0..0737fd0fa 100644 --- a/test/Lsp.Integration.Tests/TypedCodeLensTests.cs +++ b/test/Lsp.Integration.Tests/TypedCodeLensTests.cs @@ -1,12 +1,10 @@ using System; -using System.ComponentModel; using System.Linq; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using FluentAssertions; -using Lsp.Tests.Integration.Fixtures; -using Newtonsoft.Json; +using Lsp.Integration.Tests.Fixtures; using Newtonsoft.Json.Linq; using NSubstitute; using OmniSharp.Extensions.JsonRpc.Testing; @@ -15,13 +13,10 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using Serilog.Events; -using TestingUtils; using Xunit; using Xunit.Abstractions; -using IHandlerIdentity = OmniSharp.Extensions.LanguageServer.Protocol.Models.IHandlerIdentity; -using Nested = Lsp.Tests.Integration.Fixtures.Nested; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class TypedCodeLensTests : LanguageProtocolTestBase { @@ -33,7 +28,8 @@ public TypedCodeLensTests(ITestOutputHelper outputHelper) : base(new JsonRpcTest public async Task Should_Aggregate_With_All_Related_Handlers() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { var identifier = Substitute.For(); identifier.GetTextDocumentAttributes(Arg.Any()).Returns( call => new TextDocumentAttributes(call.ArgAt(0), "file", "csharp") @@ -41,16 +37,21 @@ public async Task Should_Aggregate_With_All_Related_Handlers() options.AddTextDocumentIdentifier(identifier); options.OnCodeLens( - codeLensParams => { + codeLensParams => + { return Task.FromResult( - new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLensContainer( + new CodeLens + { + Command = new Command + { Name = "data-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -61,21 +62,26 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ); }, l => { return Task.FromResult(l with { Command = l.Command with { Name = "resolved-a" } }); }, - (_, _) => new CodeLensRegistrationOptions { + (_, _) => new CodeLensRegistrationOptions + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); options.OnCodeLens( - codeLensParams => { + codeLensParams => + { return Task.FromResult( new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLens + { + Command = new Command + { Name = "nested-b", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Nested { + Data = new Nested + { Date = DateTimeOffset.Now } } @@ -83,17 +89,21 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ); }, l => { return Task.FromResult(l with { Command = l.Command with { Name = "resolved-b" } }); }, - (_, _) => new CodeLensRegistrationOptions { + (_, _) => new CodeLensRegistrationOptions + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); options.OnCodeLens( - codeLensParams => { + codeLensParams => + { return Task.FromResult( new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLens + { + Command = new Command + { Name = "no-data-c", Arguments = JArray.FromObject(new object[] { 1, "2", false }) } @@ -102,17 +112,21 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ); }, l => { return Task.FromResult(l with { Command = l.Command with { Name = "resolved-c" } }); }, - (_, _) => new CodeLensRegistrationOptions { + (_, _) => new CodeLensRegistrationOptions + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); options.OnCodeLens( - codeLensParams => { + codeLensParams => + { return Task.FromResult( new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLens + { + Command = new Command + { Name = "not-included", Arguments = JArray.FromObject(new object[] { 1, "2", false }) } @@ -121,7 +135,8 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ); }, l => { return Task.FromResult(l with { Command = l.Command with { Name = "resolved-d" } }); }, - (_, _) => new CodeLensRegistrationOptions { + (_, _) => new CodeLensRegistrationOptions + { DocumentSelector = DocumentSelector.ForLanguage("vb") } ); @@ -129,7 +144,8 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ); var codeLens = await client.RequestCodeLens( - new CodeLensParams { + new CodeLensParams + { TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), } ); @@ -146,18 +162,24 @@ public async Task Should_Aggregate_With_All_Related_Handlers() public async Task Should_Resolve_With_Data_Capability() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCodeLens( - (codeLensParams, capability, token) => { + (codeLensParams, capability, token) => + { return Task.FromResult( - new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLensContainer( + new CodeLens + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -167,7 +189,8 @@ public async Task Should_Resolve_With_Data_Capability() ) ); }, - (lens, capability, token) => { + (lens, capability, token) => + { lens.Data.Id.Should().NotBeEmpty(); lens.Data.Child.Should().NotBeNull(); lens.Data.Name.Should().Be("name"); @@ -191,17 +214,23 @@ public async Task Should_Resolve_With_Data_Capability() public async Task Should_Resolve_With_Partial_Data_Capability() { var (client, _) = await Initialize( - options => { }, options => { - options.ObserveCodeLens( - (codeLensParams, observer, capability, token) => { - var a = new CodeLensContainer( - new CodeLens { - Command = new Command { + options => { }, options => + { + options.ObserveCodeLens( + (codeLensParams, observer, capability, token) => + { + var a = new CodeLensContainer( + new CodeLens + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -213,7 +242,8 @@ public async Task Should_Resolve_With_Partial_Data_Capability() observer.OnNext(a); observer.OnCompleted(); }, - (codeLens, capability, token) => { + (codeLens, capability, token) => + { codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); codeLens.Data.Name.Should().Be("name"); @@ -235,18 +265,24 @@ public async Task Should_Resolve_With_Partial_Data_Capability() public async Task Should_Resolve_With_Data_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCodeLens( - (codeLensParams, token) => { + (codeLensParams, token) => + { return Task.FromResult( - new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLensContainer( + new CodeLens + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -256,7 +292,8 @@ public async Task Should_Resolve_With_Data_CancellationToken() ) ); }, - (codeLens, token) => { + (codeLens, token) => + { codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); codeLens.Data.Name.Should().Be("name"); @@ -280,17 +317,23 @@ public async Task Should_Resolve_With_Data_CancellationToken() public async Task Should_Resolve_With_Partial_Data_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { - options.ObserveCodeLens( - (codeLensParams, observer, token) => { - var a = new CodeLensContainer( - new CodeLens { - Command = new Command { + options => { }, options => + { + options.ObserveCodeLens( + (codeLensParams, observer, token) => + { + var a = new CodeLensContainer( + new CodeLens + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -302,7 +345,8 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() observer.OnNext(a); observer.OnCompleted(); }, - (codeLens, token) => { + (codeLens, token) => + { codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); codeLens.Data.Name.Should().Be("name"); @@ -324,18 +368,24 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() public async Task Should_Resolve_With_Data() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCodeLens( - codeLensParams => { + codeLensParams => + { return Task.FromResult( - new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLensContainer( + new CodeLens + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -345,7 +395,8 @@ public async Task Should_Resolve_With_Data() ) ); }, - codeLens => { + codeLens => + { codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); codeLens.Data.Name.Should().Be("name"); @@ -369,17 +420,23 @@ public async Task Should_Resolve_With_Data() public async Task Should_Resolve_With_Partial_Data() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveCodeLens( - (codeLensParams, observer) => { + (codeLensParams, observer) => + { var a = new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLens + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -391,7 +448,8 @@ public async Task Should_Resolve_With_Partial_Data() observer.OnNext(a); observer.OnCompleted(); }, - codeLens => { + codeLens => + { codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); codeLens.Data.Name.Should().Be("name"); @@ -414,13 +472,17 @@ public async Task Should_Resolve_With_Partial_Data() public async Task Should_Resolve_Capability() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCodeLens( - (codeLensParams, capability, token) => { + (codeLensParams, capability, token) => + { return Task.FromResult( new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLens + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) } @@ -428,7 +490,8 @@ public async Task Should_Resolve_Capability() ) ); }, - (codeLens, capability, token) => { + (codeLens, capability, token) => + { return Task.FromResult(codeLens with { Command = codeLens.Command with { Name = "resolved" } }); return Task.FromResult(codeLens); }, @@ -449,12 +512,16 @@ public async Task Should_Resolve_Capability() public async Task Should_Resolve_Partial_Capability() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveCodeLens( - (codeLensParams, observer, capability, token) => { + (codeLensParams, observer, capability, token) => + { var a = new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLens + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -464,7 +531,8 @@ public async Task Should_Resolve_Partial_Capability() observer.OnNext(a); observer.OnCompleted(); }, - (codeLens, capability, token) => { + (codeLens, capability, token) => + { return Task.FromResult(codeLens with { Command = codeLens.Command with { Name = "resolved" } }); return Task.FromResult(codeLens); }, @@ -483,13 +551,17 @@ public async Task Should_Resolve_Partial_Capability() public async Task Should_Resolve_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCodeLens( - (codeLensParams, token) => { + (codeLensParams, token) => + { return Task.FromResult( new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLens + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -497,7 +569,8 @@ public async Task Should_Resolve_CancellationToken() ) ); }, - (codeLens, token) => { + (codeLens, token) => + { return Task.FromResult(codeLens with { Command = codeLens.Command with { Name = "resolved" } }); return Task.FromResult(codeLens); }, @@ -518,12 +591,16 @@ public async Task Should_Resolve_CancellationToken() public async Task Should_Resolve_Partial_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveCodeLens( - (codeLensParams, observer, token) => { + (codeLensParams, observer, token) => + { var a = new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLens + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -533,7 +610,8 @@ public async Task Should_Resolve_Partial_CancellationToken() observer.OnNext(a); observer.OnCompleted(); }, - (codeLens, token) => { + (codeLens, token) => + { return Task.FromResult(codeLens with { Command = codeLens.Command with { Name = "resolved" } }); return Task.FromResult(codeLens); }, @@ -552,13 +630,17 @@ public async Task Should_Resolve_Partial_CancellationToken() public async Task Should_Resolve() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCodeLens( - codeLensParams => { + codeLensParams => + { return Task.FromResult( new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLens + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -566,7 +648,8 @@ public async Task Should_Resolve() ) ); }, - codeLens => { + codeLens => + { return Task.FromResult(codeLens with { Command = codeLens.Command with { Name = "resolved" } }); return Task.FromResult(codeLens); }, @@ -587,12 +670,16 @@ public async Task Should_Resolve() public async Task Should_Resolve_Partial() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveCodeLens( - (codeLensParams, observer) => { + (codeLensParams, observer) => + { var a = new CodeLensContainer( - new CodeLens { - Command = new Command { + new CodeLens + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -602,7 +689,8 @@ public async Task Should_Resolve_Partial() observer.OnNext(a); observer.OnCompleted(); }, - codeLens => { + codeLens => + { return Task.FromResult(codeLens with { Command = codeLens.Command with { Name = "resolved" } }); return Task.FromResult(codeLens); }, diff --git a/test/Lsp.Integration.Tests/TypedCompletionTests.cs b/test/Lsp.Integration.Tests/TypedCompletionTests.cs index ac238921a..61cc6faaa 100644 --- a/test/Lsp.Integration.Tests/TypedCompletionTests.cs +++ b/test/Lsp.Integration.Tests/TypedCompletionTests.cs @@ -1,12 +1,10 @@ using System; -using System.ComponentModel; using System.Linq; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using FluentAssertions; -using Lsp.Tests.Integration.Fixtures; -using Newtonsoft.Json; +using Lsp.Integration.Tests.Fixtures; using Newtonsoft.Json.Linq; using NSubstitute; using OmniSharp.Extensions.JsonRpc.Testing; @@ -15,13 +13,10 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using Serilog.Events; -using TestingUtils; using Xunit; using Xunit.Abstractions; -using IHandlerIdentity = OmniSharp.Extensions.LanguageServer.Protocol.Models.IHandlerIdentity; -using Nested = Lsp.Tests.Integration.Fixtures.Nested; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class TypedCompletionTests : LanguageProtocolTestBase { @@ -33,7 +28,8 @@ public TypedCompletionTests(ITestOutputHelper outputHelper) : base(new JsonRpcTe public async Task Should_Aggregate_With_All_Related_Handlers() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { var identifier = Substitute.For(); identifier.GetTextDocumentAttributes(Arg.Any()).Returns( call => new TextDocumentAttributes(call.ArgAt(0), "file", "csharp") @@ -41,16 +37,21 @@ public async Task Should_Aggregate_With_All_Related_Handlers() options.AddTextDocumentIdentifier(identifier); options.OnCompletion( - codeLensParams => { + codeLensParams => + { return Task.FromResult( - new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionList( + new CompletionItem + { + Command = new Command + { Name = "data-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -61,21 +62,26 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ); }, completionItem => { return Task.FromResult(completionItem with { Command = completionItem.Command with { Name = "resolved-a" } }); }, - (_, _) => new CompletionRegistrationOptions { + (_, _) => new CompletionRegistrationOptions + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); options.OnCompletion( - codeLensParams => { + codeLensParams => + { return Task.FromResult( new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionItem + { + Command = new Command + { Name = "nested-b", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Nested { + Data = new Nested + { Date = DateTimeOffset.Now } } @@ -83,17 +89,21 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ); }, completionItem => { return Task.FromResult(completionItem with { Command = completionItem.Command with { Name = "resolved-b" } }); }, - (_, _) => new CompletionRegistrationOptions { + (_, _) => new CompletionRegistrationOptions + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); options.OnCompletion( - codeLensParams => { + codeLensParams => + { return Task.FromResult( new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionItem + { + Command = new Command + { Name = "no-data-c", Arguments = JArray.FromObject(new object[] { 1, "2", false }) } @@ -102,17 +112,21 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ); }, completionItem => { return Task.FromResult(completionItem with { Command = completionItem.Command with { Name = "resolved-c" } }); }, - (_, _) => new CompletionRegistrationOptions { + (_, _) => new CompletionRegistrationOptions + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); options.OnCompletion( - codeLensParams => { + codeLensParams => + { return Task.FromResult( new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionItem + { + Command = new Command + { Name = "not-included", Arguments = JArray.FromObject(new object[] { 1, "2", false }) } @@ -120,8 +134,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - completionItem => { return Task.FromResult(completionItem with { Command = completionItem.Command with { Name = "resolved-d" }}); }, - (_, _) => new CompletionRegistrationOptions { + completionItem => { return Task.FromResult(completionItem with { Command = completionItem.Command with { Name = "resolved-d" } }); }, + (_, _) => new CompletionRegistrationOptions + { DocumentSelector = DocumentSelector.ForLanguage("vb") } ); @@ -129,7 +144,8 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ); var items = await client.RequestCompletion( - new CompletionParams { + new CompletionParams + { TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), } ); @@ -146,18 +162,24 @@ public async Task Should_Aggregate_With_All_Related_Handlers() public async Task Should_Resolve_With_Data_Capability() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - (completionParams, capability, token) => { + (completionParams, capability, token) => + { return Task.FromResult( - new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionList( + new CompletionItem + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -167,15 +189,17 @@ public async Task Should_Resolve_With_Data_Capability() ) ); }, - (completionItem, capability, token) => { + (completionItem, capability, token) => + { completionItem.Data!.Id.Should().NotBeEmpty(); completionItem.Data!.Child.Should().NotBeNull(); completionItem.Data!.Name.Should().Be("name"); return Task.FromResult(completionItem with { Detail = "resolved" }); return Task.FromResult( - completionItem with { + completionItem with + { Detail = "resolved" - } + } ); }, (_, _) => new CompletionRegistrationOptions() @@ -195,17 +219,23 @@ completionItem with { public async Task Should_Resolve_With_Partial_Data_Capability() { var (client, _) = await Initialize( - options => { }, options => { - options.ObserveCompletion( - (completionParams, observer, capability, token) => { - var a = new CompletionList( - new CompletionItem { - Command = new Command { + options => { }, options => + { + options.ObserveCompletion( + (completionParams, observer, capability, token) => + { + var a = new CompletionList( + new CompletionItem + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -217,12 +247,13 @@ public async Task Should_Resolve_With_Partial_Data_Capability() observer.OnNext(a); observer.OnCompleted(); }, - (completionItem, capability, token) => { + (completionItem, capability, token) => + { completionItem.Data!.Id.Should().NotBeEmpty(); completionItem.Data!.Child.Should().NotBeNull(); completionItem.Data!.Name.Should().Be("name"); return Task.FromResult(completionItem with { Detail = "resolved" }); - }, + }, (_, _) => new CompletionRegistrationOptions() ); } @@ -239,18 +270,24 @@ public async Task Should_Resolve_With_Partial_Data_Capability() public async Task Should_Resolve_With_Data_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - (completionParams, token) => { + (completionParams, token) => + { return Task.FromResult( - new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionList( + new CompletionItem + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -260,7 +297,8 @@ public async Task Should_Resolve_With_Data_CancellationToken() ) ); }, - (completionItem, token) => { + (completionItem, token) => + { completionItem.Data!.Id.Should().NotBeEmpty(); completionItem.Data!.Child.Should().NotBeNull(); completionItem.Data!.Name.Should().Be("name"); @@ -283,17 +321,23 @@ public async Task Should_Resolve_With_Data_CancellationToken() public async Task Should_Resolve_With_Partial_Data_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { - options.ObserveCompletion( - (completionParams, observer, token) => { - var a = new CompletionList( - new CompletionItem { - Command = new Command { + options => { }, options => + { + options.ObserveCompletion( + (completionParams, observer, token) => + { + var a = new CompletionList( + new CompletionItem + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -305,7 +349,8 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() observer.OnNext(a); observer.OnCompleted(); }, - (completionItem, token) => { + (completionItem, token) => + { completionItem.Data!.Id.Should().NotBeEmpty(); completionItem.Data!.Child.Should().NotBeNull(); completionItem.Data!.Name.Should().Be("name"); @@ -326,18 +371,24 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() public async Task Should_Resolve_With_Data() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - completionParams => { + completionParams => + { return Task.FromResult( - new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionList( + new CompletionItem + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -347,7 +398,8 @@ public async Task Should_Resolve_With_Data() ) ); }, - completionItem => { + completionItem => + { completionItem.Data!.Id.Should().NotBeEmpty(); completionItem.Data!.Child.Should().NotBeNull(); completionItem.Data!.Name.Should().Be("name"); @@ -370,17 +422,23 @@ public async Task Should_Resolve_With_Data() public async Task Should_Resolve_With_Partial_Data() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveCompletion( - (completionParams, observer) => { + (completionParams, observer) => + { var a = new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionItem + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Data = new Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -392,7 +450,8 @@ public async Task Should_Resolve_With_Partial_Data() observer.OnNext(a); observer.OnCompleted(); }, - completionItem => { + completionItem => + { completionItem.Data!.Id.Should().NotBeEmpty(); completionItem.Data!.Child.Should().NotBeNull(); completionItem.Data!.Name.Should().Be("name"); @@ -414,13 +473,17 @@ public async Task Should_Resolve_With_Partial_Data() public async Task Should_Resolve_Capability() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - (completionParams, capability, token) => { + (completionParams, capability, token) => + { return Task.FromResult( new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionItem + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) } @@ -446,12 +509,16 @@ public async Task Should_Resolve_Capability() public async Task Should_Resolve_Partial_Capability() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveCompletion( - (completionParams, observer, capability, token) => { + (completionParams, observer, capability, token) => + { var a = new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionItem + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -477,13 +544,17 @@ public async Task Should_Resolve_Partial_Capability() public async Task Should_Resolve_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - (completionParams, token) => { + (completionParams, token) => + { return Task.FromResult( new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionItem + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -509,12 +580,16 @@ public async Task Should_Resolve_CancellationToken() public async Task Should_Resolve_Partial_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveCompletion( - (completionParams, observer, token) => { + (completionParams, observer, token) => + { var a = new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionItem + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -540,13 +615,17 @@ public async Task Should_Resolve_Partial_CancellationToken() public async Task Should_Resolve() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnCompletion( - completionParams => { + completionParams => + { return Task.FromResult( new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionItem + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, @@ -572,12 +651,16 @@ public async Task Should_Resolve() public async Task Should_Resolve_Partial() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveCompletion( - (completionParams, observer) => { + (completionParams, observer) => + { var a = new CompletionList( - new CompletionItem { - Command = new Command { + new CompletionItem + { + Command = new Command + { Name = "execute-a", Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, diff --git a/test/Lsp.Integration.Tests/TypedDocumentLinkTests.cs b/test/Lsp.Integration.Tests/TypedDocumentLinkTests.cs index 0cd4ebd54..2ea362015 100644 --- a/test/Lsp.Integration.Tests/TypedDocumentLinkTests.cs +++ b/test/Lsp.Integration.Tests/TypedDocumentLinkTests.cs @@ -1,12 +1,10 @@ using System; -using System.ComponentModel; using System.Linq; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using FluentAssertions; -using Lsp.Tests.Integration.Fixtures; -using Newtonsoft.Json; +using Lsp.Integration.Tests.Fixtures; using NSubstitute; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; @@ -14,12 +12,10 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using Serilog.Events; -using TestingUtils; using Xunit; using Xunit.Abstractions; -using Nested = Lsp.Tests.Integration.Fixtures.Nested; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public partial class TypedDocumentLinkTests : LanguageProtocolTestBase { @@ -31,7 +27,8 @@ public TypedDocumentLinkTests(ITestOutputHelper outputHelper) : base(new JsonRpc public async Task Should_Aggregate_With_All_Related_Handlers() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { var identifier = Substitute.For(); identifier.GetTextDocumentAttributes(Arg.Any()).Returns( call => new TextDocumentAttributes(call.ArgAt(0), "file", "csharp") @@ -39,13 +36,17 @@ public async Task Should_Aggregate_With_All_Related_Handlers() options.AddTextDocumentIdentifier(identifier); options.OnDocumentLink( - codeLensParams => { + codeLensParams => + { return Task.FromResult( - new DocumentLinkContainer( - new DocumentLink { + new DocumentLinkContainer( + new DocumentLink + { Tooltip = "data-a", - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -55,67 +56,70 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - documentLink => { - return Task.FromResult(documentLink with { Tooltip = "resolved-a" }); - }, - (_, _) => new DocumentLinkRegistrationOptions { + documentLink => { return Task.FromResult(documentLink with { Tooltip = "resolved-a" }); }, + (_, _) => new DocumentLinkRegistrationOptions + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); options.OnDocumentLink( - codeLensParams => { + codeLensParams => + { return Task.FromResult( new DocumentLinkContainer( - new DocumentLink { + new DocumentLink + { Tooltip = "nested-b", - Data = new Nested { + Data = new Nested + { Date = DateTimeOffset.Now } } ) ); }, - documentLink => { - return Task.FromResult(documentLink with { Tooltip = "resolved-b" }); - }, - (_, _) => new DocumentLinkRegistrationOptions { + documentLink => { return Task.FromResult(documentLink with { Tooltip = "resolved-b" }); }, + (_, _) => new DocumentLinkRegistrationOptions + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); options.OnDocumentLink( - codeLensParams => { + codeLensParams => + { return Task.FromResult( new DocumentLinkContainer( - new DocumentLink { + new DocumentLink + { Tooltip = "no-data-c", } ) ); }, - documentLink => { - return Task.FromResult(documentLink with { Tooltip = "resolved-c" }); - }, - (_, _) => new DocumentLinkRegistrationOptions { + documentLink => { return Task.FromResult(documentLink with { Tooltip = "resolved-c" }); }, + (_, _) => new DocumentLinkRegistrationOptions + { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") } ); options.OnDocumentLink( - codeLensParams => { + codeLensParams => + { return Task.FromResult( new DocumentLinkContainer( - new DocumentLink { + new DocumentLink + { Tooltip = "not-included", } ) ); }, - documentLink => { - return Task.FromResult(documentLink with { Tooltip = "resolved-d" }); - }, - (_, _) => new DocumentLinkRegistrationOptions { + documentLink => { return Task.FromResult(documentLink with { Tooltip = "resolved-d" }); }, + (_, _) => new DocumentLinkRegistrationOptions + { DocumentSelector = DocumentSelector.ForLanguage("vb") } ); @@ -123,7 +127,8 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ); var items = await client.RequestDocumentLink( - new DocumentLinkParams { + new DocumentLinkParams + { TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), } ); @@ -140,15 +145,20 @@ public async Task Should_Aggregate_With_All_Related_Handlers() public async Task Should_Resolve_With_Data_Capability() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnDocumentLink( - (documentLinkParams, capability, token) => { + (documentLinkParams, capability, token) => + { return Task.FromResult( - new DocumentLinkContainer( - new DocumentLink { + new DocumentLinkContainer( + new DocumentLink + { Tooltip = "execute-a", - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -158,7 +168,8 @@ public async Task Should_Resolve_With_Data_Capability() ) ); }, - (documentLink, capability, token) => { + (documentLink, capability, token) => + { documentLink.Data.Id.Should().NotBeEmpty(); documentLink.Data.Child.Should().NotBeNull(); documentLink.Data.Name.Should().Be("name"); @@ -181,14 +192,19 @@ public async Task Should_Resolve_With_Data_Capability() public async Task Should_Resolve_With_Partial_Data_Capability() { var (client, _) = await Initialize( - options => { }, options => { - options.ObserveDocumentLink( - (documentLinkParams, observer, capability, token) => { - var a = new DocumentLinkContainer( - new DocumentLink { + options => { }, options => + { + options.ObserveDocumentLink( + (documentLinkParams, observer, capability, token) => + { + var a = new DocumentLinkContainer( + new DocumentLink + { Tooltip = "execute-a", - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -200,7 +216,8 @@ public async Task Should_Resolve_With_Partial_Data_Capability() observer.OnNext(a); observer.OnCompleted(); }, - (documentLink, capability, token) => { + (documentLink, capability, token) => + { documentLink.Data.Id.Should().NotBeEmpty(); documentLink.Data.Child.Should().NotBeNull(); documentLink.Data.Name.Should().Be("name"); @@ -221,15 +238,20 @@ public async Task Should_Resolve_With_Partial_Data_Capability() public async Task Should_Resolve_With_Data_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnDocumentLink( - (documentLinkParams, token) => { + (documentLinkParams, token) => + { return Task.FromResult( - new DocumentLinkContainer( - new DocumentLink { + new DocumentLinkContainer( + new DocumentLink + { Tooltip = "execute-a", - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -239,7 +261,8 @@ public async Task Should_Resolve_With_Data_CancellationToken() ) ); }, - (documentLink, token) => { + (documentLink, token) => + { documentLink.Data.Id.Should().NotBeEmpty(); documentLink.Data.Child.Should().NotBeNull(); documentLink.Data.Name.Should().Be("name"); @@ -262,14 +285,19 @@ public async Task Should_Resolve_With_Data_CancellationToken() public async Task Should_Resolve_With_Partial_Data_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { - options.ObserveDocumentLink( - (documentLinkParams, observer, token) => { - var a = new DocumentLinkContainer( - new DocumentLink { + options => { }, options => + { + options.ObserveDocumentLink( + (documentLinkParams, observer, token) => + { + var a = new DocumentLinkContainer( + new DocumentLink + { Tooltip = "execute-a", - Data = new Fixtures.Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -281,7 +309,8 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() observer.OnNext(a); observer.OnCompleted(); }, - (documentLink, token) => { + (documentLink, token) => + { documentLink.Data.Id.Should().NotBeEmpty(); documentLink.Data.Child.Should().NotBeNull(); documentLink.Data.Name.Should().Be("name"); @@ -302,15 +331,20 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() public async Task Should_Resolve_With_Data() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnDocumentLink( - documentLinkParams => { + documentLinkParams => + { return Task.FromResult( - new DocumentLinkContainer( - new DocumentLink { + new DocumentLinkContainer( + new DocumentLink + { Tooltip = "execute-a", - Data = new Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -320,7 +354,8 @@ public async Task Should_Resolve_With_Data() ) ); }, - documentLink => { + documentLink => + { documentLink.Data.Id.Should().NotBeEmpty(); documentLink.Data.Child.Should().NotBeNull(); documentLink.Data.Name.Should().Be("name"); @@ -343,14 +378,19 @@ public async Task Should_Resolve_With_Data() public async Task Should_Resolve_With_Partial_Data() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveDocumentLink( - (documentLinkParams, observer) => { + (documentLinkParams, observer) => + { var a = new DocumentLinkContainer( - new DocumentLink { + new DocumentLink + { Tooltip = "execute-a", - Data = new Data { - Child = new Nested { + Data = new Data + { + Child = new Nested + { Date = DateTimeOffset.MinValue }, Id = Guid.NewGuid(), @@ -362,7 +402,8 @@ public async Task Should_Resolve_With_Partial_Data() observer.OnNext(a); observer.OnCompleted(); }, - documentLink => { + documentLink => + { documentLink.Data.Id.Should().NotBeEmpty(); documentLink.Data.Child.Should().NotBeNull(); documentLink.Data.Name.Should().Be("name"); @@ -384,20 +425,21 @@ public async Task Should_Resolve_With_Partial_Data() public async Task Should_Resolve_Capability() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnDocumentLink( - (documentLinkParams, capability, token) => { + (documentLinkParams, capability, token) => + { return Task.FromResult( new DocumentLinkContainer( - new DocumentLink { + new DocumentLink + { Tooltip = "execute-a", } ) ); }, - (documentLink, capability, token) => { - return Task.FromResult(documentLink with { Tooltip = "resolved" }); - }, + (documentLink, capability, token) => { return Task.FromResult(documentLink with { Tooltip = "resolved" }); }, (_, _) => new DocumentLinkRegistrationOptions() ); } @@ -415,11 +457,14 @@ public async Task Should_Resolve_Capability() public async Task Should_Resolve_Partial_Capability() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveDocumentLink( - (documentLinkParams, observer, capability, token) => { + (documentLinkParams, observer, capability, token) => + { var a = new DocumentLinkContainer( - new DocumentLink { + new DocumentLink + { Tooltip = "execute-a", } ); @@ -427,9 +472,7 @@ public async Task Should_Resolve_Partial_Capability() observer.OnNext(a); observer.OnCompleted(); }, - (documentLink, capability, token) => { - return Task.FromResult(documentLink with { Tooltip = "resolved" }); - }, + (documentLink, capability, token) => { return Task.FromResult(documentLink with { Tooltip = "resolved" }); }, (_, _) => new DocumentLinkRegistrationOptions() ); } @@ -445,20 +488,21 @@ public async Task Should_Resolve_Partial_Capability() public async Task Should_Resolve_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnDocumentLink( - (documentLinkParams, token) => { + (documentLinkParams, token) => + { return Task.FromResult( new DocumentLinkContainer( - new DocumentLink { + new DocumentLink + { Tooltip = "execute-a", } ) ); }, - (documentLink, token) => { - return Task.FromResult(documentLink with { Tooltip = "resolved" }); - }, + (documentLink, token) => { return Task.FromResult(documentLink with { Tooltip = "resolved" }); }, (_, _) => new DocumentLinkRegistrationOptions() ); } @@ -476,11 +520,14 @@ public async Task Should_Resolve_CancellationToken() public async Task Should_Resolve_Partial_CancellationToken() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveDocumentLink( - (documentLinkParams, observer, token) => { + (documentLinkParams, observer, token) => + { var a = new DocumentLinkContainer( - new DocumentLink { + new DocumentLink + { Tooltip = "execute-a", } ); @@ -488,9 +535,7 @@ public async Task Should_Resolve_Partial_CancellationToken() observer.OnNext(a); observer.OnCompleted(); }, - (documentLink, token) => { - return Task.FromResult(documentLink with { Tooltip = "resolved" }); - }, + (documentLink, token) => { return Task.FromResult(documentLink with { Tooltip = "resolved" }); }, (_, _) => new DocumentLinkRegistrationOptions() ); } @@ -506,20 +551,21 @@ public async Task Should_Resolve_Partial_CancellationToken() public async Task Should_Resolve() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.OnDocumentLink( - documentLinkParams => { + documentLinkParams => + { return Task.FromResult( new DocumentLinkContainer( - new DocumentLink { + new DocumentLink + { Tooltip = "execute-a", } ) ); }, - documentLink => { - return Task.FromResult(documentLink with { Tooltip = "resolved" }); - }, + documentLink => { return Task.FromResult(documentLink with { Tooltip = "resolved" }); }, (_, _) => new DocumentLinkRegistrationOptions() ); } @@ -537,11 +583,14 @@ public async Task Should_Resolve() public async Task Should_Resolve_Partial() { var (client, _) = await Initialize( - options => { }, options => { + options => { }, options => + { options.ObserveDocumentLink( - (documentLinkParams, observer) => { + (documentLinkParams, observer) => + { var a = new DocumentLinkContainer( - new DocumentLink { + new DocumentLink + { Tooltip = "execute-a", } ); @@ -549,9 +598,7 @@ public async Task Should_Resolve_Partial() observer.OnNext(a); observer.OnCompleted(); }, - documentLink => { - return Task.FromResult(documentLink with { Tooltip = "resolved" }); - }, + documentLink => { return Task.FromResult(documentLink with { Tooltip = "resolved" }); }, (_, _) => new DocumentLinkRegistrationOptions() ); } diff --git a/test/Lsp.Integration.Tests/WorkspaceFolderTests.cs b/test/Lsp.Integration.Tests/WorkspaceFolderTests.cs index 240394788..0a38d9877 100644 --- a/test/Lsp.Integration.Tests/WorkspaceFolderTests.cs +++ b/test/Lsp.Integration.Tests/WorkspaceFolderTests.cs @@ -17,11 +17,10 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; using OmniSharp.Extensions.LanguageServer.Server; using Serilog.Events; -using TestingUtils; using Xunit; using Xunit.Abstractions; -namespace Lsp.Tests.Integration +namespace Lsp.Integration.Tests { public class WorkspaceFolderTests : LanguageProtocolTestBase { @@ -37,7 +36,8 @@ public WorkspaceFolderTests(ITestOutputHelper outputHelper) : base( public async Task Should_Disable_If_Not_Supported() { var (_, server) = await Initialize( - options => { + options => + { options.DisableAllCapabilities(); options.OnInitialize(async (languageClient, request, token) => { request.Capabilities!.Workspace!.WorkspaceFolders = false; }); }, ConfigureServer @@ -75,10 +75,12 @@ public async Task Should_Add_A_Workspace_Folder() public async Task Should_Allow_Null_Response() { var (client, server) = await Initialize( - options => { + options => + { ConfigureClient(options); options.OnWorkspaceFolders(@params => Task.FromResult?>(null)); - }, ConfigureServer); + }, ConfigureServer + ); Func a = () => server.WorkspaceFolderManager.Refresh().LastOrDefaultAsync().ToTask(); await a.Should().NotThrowAsync(); @@ -87,7 +89,9 @@ public async Task Should_Allow_Null_Response() [Fact] public async Task Should_Have_Workspace_Folder_At_Startup() { - var (_, server) = await Initialize(options => { options.WithWorkspaceFolder("/abcd/", nameof(Should_Have_Workspace_Folder_At_Startup)); }, ConfigureServer); + var (_, server) = await Initialize( + options => { options.WithWorkspaceFolder("/abcd/", nameof(Should_Have_Workspace_Folder_At_Startup)); }, ConfigureServer + ); var folder = server.WorkspaceFolderManager.CurrentWorkspaceFolders.Should().HaveCount(1).And.Subject.First(); folder.Name.Should().Be(nameof(Should_Have_Workspace_Folder_At_Startup)); @@ -96,7 +100,9 @@ public async Task Should_Have_Workspace_Folder_At_Startup() [Fact] public async Task Should_Remove_Workspace_Folder_by_name() { - var (client, server) = await Initialize(options => { options.WithWorkspaceFolder("/abcd/", nameof(Should_Remove_Workspace_Folder_by_name)); }, ConfigureServer); + var (client, server) = await Initialize( + options => { options.WithWorkspaceFolder("/abcd/", nameof(Should_Remove_Workspace_Folder_by_name)); }, ConfigureServer + ); var folders = new List(); server.WorkspaceFolderManager.Changed.Subscribe(x => folders.Add(x)); @@ -116,7 +122,9 @@ public async Task Should_Remove_Workspace_Folder_by_name() [Fact] public async Task Should_Remove_Workspace_Folder_by_uri() { - var (client, server) = await Initialize(options => { options.WithWorkspaceFolder("/abcd/", nameof(Should_Remove_Workspace_Folder_by_uri)); }, ConfigureServer); + var (client, server) = await Initialize( + options => { options.WithWorkspaceFolder("/abcd/", nameof(Should_Remove_Workspace_Folder_by_uri)); }, ConfigureServer + ); var folders = new List(); server.WorkspaceFolderManager.Changed.Subscribe(x => folders.Add(x)); @@ -139,9 +147,12 @@ public async Task Should_Handle_Null_Workspace_Folders() var workspaceLanguageServer = Substitute.For(); var languageServer = Substitute.For(); languageServer.ClientSettings.Returns( - new InitializeParams() { - Capabilities = new ClientCapabilities() { - Workspace = new WorkspaceClientCapabilities() { + new InitializeParams + { + Capabilities = new ClientCapabilities + { + Workspace = new WorkspaceClientCapabilities + { WorkspaceFolders = true } }, @@ -149,8 +160,10 @@ public async Task Should_Handle_Null_Workspace_Folders() } ); var workspaceFolders = new LanguageServerWorkspaceFolderManager(workspaceLanguageServer); - ( (IRegistration) workspaceFolders ).GetRegistrationOptions(languageServer!.ClientSettings!.Capabilities!); - var started = (IOnLanguageServerStarted) workspaceFolders; + ( (IRegistration)workspaceFolders ).GetRegistrationOptions( + languageServer!.ClientSettings!.Capabilities! + ); + var started = (IOnLanguageServerStarted)workspaceFolders; await started.OnStarted(languageServer, CancellationToken); } @@ -160,19 +173,24 @@ public async Task Should_Handle_Null_Workspace_Folders_On_Refresh() var workspaceLanguageServer = Substitute.For(); var languageServer = Substitute.For(); languageServer.ClientSettings.Returns( - new InitializeParams() { - Capabilities = new ClientCapabilities() { - Workspace = new WorkspaceClientCapabilities() { + new InitializeParams + { + Capabilities = new ClientCapabilities + { + Workspace = new WorkspaceClientCapabilities + { WorkspaceFolders = true } }, WorkspaceFolders = null } ); - languageServer.SendRequest(Arg.Any(), Arg.Any()).Returns((Container? ) null); + languageServer.SendRequest(Arg.Any(), Arg.Any()).Returns((Container?)null); var workspaceFolders = new LanguageServerWorkspaceFolderManager(workspaceLanguageServer); - ( (IRegistration) workspaceFolders ).GetRegistrationOptions(languageServer!.ClientSettings!.Capabilities!); - var started = (IOnLanguageServerStarted) workspaceFolders; + ( (IRegistration)workspaceFolders ).GetRegistrationOptions( + languageServer!.ClientSettings!.Capabilities! + ); + var started = (IOnLanguageServerStarted)workspaceFolders; await started.OnStarted(languageServer, CancellationToken); var result = await workspaceFolders.Refresh().ToArray(); @@ -180,14 +198,18 @@ public async Task Should_Handle_Null_Workspace_Folders_On_Refresh() result.Should().BeEmpty(); } - private void ConfigureClient(LanguageClientOptions options) => + private void ConfigureClient(LanguageClientOptions options) + { options.WithClientCapabilities( - new ClientCapabilities { - Workspace = new WorkspaceClientCapabilities { + new ClientCapabilities + { + Workspace = new WorkspaceClientCapabilities + { WorkspaceFolders = true } } ); + } private void ConfigureServer(LanguageServerOptions options) { diff --git a/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncKindTests.cs b/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncKindTests.cs index b6b3a4eea..cb2b69557 100644 --- a/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncKindTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncKindTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; -using TestingUtils; using Xunit; namespace Lsp.Tests.Capabilities.Server diff --git a/test/Lsp.Tests/ClientCapabilityProviderTests.cs b/test/Lsp.Tests/ClientCapabilityProviderTests.cs index 4d0000117..4168c7d8d 100644 --- a/test/Lsp.Tests/ClientCapabilityProviderTests.cs +++ b/test/Lsp.Tests/ClientCapabilityProviderTests.cs @@ -10,10 +10,8 @@ using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; -using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; using OmniSharp.Extensions.LanguageServer.Server; using OmniSharp.Extensions.LanguageServer.Shared; using Xunit; @@ -23,7 +21,9 @@ namespace Lsp.Tests public class ClientCapabilityProviderTests { private static readonly Type[] Capabilities = typeof(ClientCapabilities).Assembly.GetTypes() - .Where(x => typeof(ICapability).IsAssignableFrom(x) && x.IsClass && !x.IsAbstract) + .Where( + x => typeof(ICapability).IsAssignableFrom(x) && x.IsClass && !x.IsAbstract + ) .Where(z => typeof(IDynamicCapability).IsAssignableFrom(z)) .ToArray(); @@ -38,8 +38,10 @@ public void Should_AllowSupportedCapabilities(IJsonRpcHandler handler, object in new SharedHandlerCollection( SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), Substitute.For(), new LspHandlerTypeDescriptorProvider( - new[] { - typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly, + new[] + { + typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, + typeof(IRegistrationManager).Assembly, typeof(LspRequestRouter).Assembly } ) @@ -50,13 +52,16 @@ public void Should_AllowSupportedCapabilities(IJsonRpcHandler handler, object in HasHandler(provider, instance).Should().BeTrue(); } - public static IEnumerable AllowSupportedCapabilities() => - GetItems( - Capabilities, type => { + public static IEnumerable AllowSupportedCapabilities() + { + return GetItems( + Capabilities, type => + { var handlerTypes = GetHandlerTypes(type); if (handlerTypes is { Length: 0 }) return null; var handler = Substitute.For(handlerTypes.ToArray(), new object[0]); - return new[] { + return new[] + { handler, Activator.CreateInstance( typeof(Supports<>).MakeGenericType(type), true, @@ -65,6 +70,7 @@ public void Should_AllowSupportedCapabilities(IJsonRpcHandler handler, object in }; } ); + } [Theory] [MemberData(nameof(AllowUnsupportedCapabilities))] @@ -77,8 +83,10 @@ public void Should_AllowUnsupportedCapabilities(IJsonRpcHandler handler, object new SharedHandlerCollection( SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), Substitute.For(), new LspHandlerTypeDescriptorProvider( - new[] { - typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly, + new[] + { + typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, + typeof(IRegistrationManager).Assembly, typeof(LspRequestRouter).Assembly } ) @@ -89,15 +97,18 @@ public void Should_AllowUnsupportedCapabilities(IJsonRpcHandler handler, object HasHandler(provider, instance).Should().BeTrue(); } - public static IEnumerable AllowUnsupportedCapabilities() => - GetItems( - Capabilities, type => { + public static IEnumerable AllowUnsupportedCapabilities() + { + return GetItems( + Capabilities, type => + { var handlerTypes = GetHandlerTypes(type); if (handlerTypes is { Length: 0 }) return null; var handler = Substitute.For(handlerTypes, new object[0]); return new[] { handler, Activator.CreateInstance(typeof(Supports<>).MakeGenericType(type), false) }; } ); + } [Theory] [MemberData(nameof(AllowNullSupportsCapabilities))] @@ -110,8 +121,10 @@ public void Should_AllowNullSupportedCapabilities(IJsonRpcHandler handler, objec new SharedHandlerCollection( SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), Substitute.For(), new LspHandlerTypeDescriptorProvider( - new[] { - typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly, + new[] + { + typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, + typeof(IRegistrationManager).Assembly, typeof(LspRequestRouter).Assembly } ) @@ -122,15 +135,18 @@ public void Should_AllowNullSupportedCapabilities(IJsonRpcHandler handler, objec HasHandler(provider, instance).Should().BeTrue(); } - public static IEnumerable AllowNullSupportsCapabilities() => - GetItems( - Capabilities, type => { + public static IEnumerable AllowNullSupportsCapabilities() + { + return GetItems( + Capabilities, type => + { var handlerTypes = GetHandlerTypes(type); if (handlerTypes is { Length: 0 }) return null; var handler = Substitute.For(handlerTypes.ToArray(), new object[0]); return new[] { handler, Activator.CreateInstance(typeof(Supports<>).MakeGenericType(type), true) }; } ); + } [Theory] @@ -144,8 +160,10 @@ public void Should_DisallowDynamicSupportedCapabilities(IJsonRpcHandler handler, new SharedHandlerCollection( SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), Substitute.For(), new LspHandlerTypeDescriptorProvider( - new[] { - typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly, + new[] + { + typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, + typeof(IRegistrationManager).Assembly, typeof(LspRequestRouter).Assembly } ) @@ -156,9 +174,11 @@ public void Should_DisallowDynamicSupportedCapabilities(IJsonRpcHandler handler, HasHandler(provider, instance).Should().BeFalse(); } - public static IEnumerable? DisallowDynamicSupportsCapabilities() => - GetItems( - Capabilities, type => { + public static IEnumerable? DisallowDynamicSupportsCapabilities() + { + return GetItems( + Capabilities, type => + { var handlerTypes = GetHandlerTypes(type); if (handlerTypes is { Length: 0 }) return null; var handler = Substitute.For(handlerTypes.ToArray(), new object[0]); @@ -168,6 +188,7 @@ public void Should_DisallowDynamicSupportedCapabilities(IJsonRpcHandler handler, { handler, Activator.CreateInstance(typeof(Supports<>).MakeGenericType(type), true, capability) }; } ); + } [Fact] public void Should_Handle_Mixed_Capabilities() @@ -183,23 +204,29 @@ public void Should_Handle_Mixed_Capabilities() new SharedHandlerCollection( SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), Substitute.For(), new LspHandlerTypeDescriptorProvider( - new[] { - typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly, + new[] + { + typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, + typeof(IRegistrationManager).Assembly, typeof(LspRequestRouter).Assembly } ) ) { textDocumentSyncHandler, codeActionHandler, definitionHandler, typeDefinitionHandler }; var provider = new ClientCapabilityProvider(collection, true); - var capabilities = new ClientCapabilities { - TextDocument = new TextDocumentClientCapabilities { + var capabilities = new ClientCapabilities + { + TextDocument = new TextDocumentClientCapabilities + { CodeAction = new Supports( - true, new CodeActionCapability { + true, new CodeActionCapability + { DynamicRegistration = false, } ), TypeDefinition = new Supports( - true, new TypeDefinitionCapability { + true, new TypeDefinitionCapability + { DynamicRegistration = true, } ) @@ -222,17 +249,22 @@ public void GH162_TextDocumentSync_Should_Work_Without_WillSave_Or_WillSaveWaitU new SharedHandlerCollection( SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), Substitute.For(), new LspHandlerTypeDescriptorProvider( - new[] { - typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly, + new[] + { + typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, + typeof(IRegistrationManager).Assembly, typeof(LspRequestRouter).Assembly } ) ) { textDocumentSyncHandler }; var provider = new ClientCapabilityProvider(collection, true); - var capabilities = new ClientCapabilities { - TextDocument = new TextDocumentClientCapabilities { - Synchronization = new SynchronizationCapability { + var capabilities = new ClientCapabilities + { + TextDocument = new TextDocumentClientCapabilities + { + Synchronization = new SynchronizationCapability + { DidSave = true, DynamicRegistration = false, WillSave = true, @@ -257,19 +289,25 @@ public void GH162_TextDocumentSync_Should_Work_With_WillSave_Or_WillSaveWaitUnti new SharedHandlerCollection( SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), Substitute.For(), new LspHandlerTypeDescriptorProvider( - new[] { - typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly, + new[] + { + typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, + typeof(IRegistrationManager).Assembly, typeof(LspRequestRouter).Assembly } ) - ) { + ) + { textDocumentSyncHandler, willSaveTextDocumentHandler, willSaveWaitUntilTextDocumentHandler, didSaveTextDocumentHandler }; - var provider = new ClientCapabilityProvider(collection ,true); - var capabilities = new ClientCapabilities { - TextDocument = new TextDocumentClientCapabilities { - Synchronization = new SynchronizationCapability { + var provider = new ClientCapabilityProvider(collection, true); + var capabilities = new ClientCapabilities + { + TextDocument = new TextDocumentClientCapabilities + { + Synchronization = new SynchronizationCapability + { DidSave = true, DynamicRegistration = false, WillSave = true, @@ -281,29 +319,38 @@ public void GH162_TextDocumentSync_Should_Work_With_WillSave_Or_WillSaveWaitUnti provider.HasStaticHandler(capabilities.TextDocument.Synchronization).Should().BeTrue(); } - private static bool HasHandler(ClientCapabilityProvider provider, object instance) => - (bool) typeof(ClientCapabilityProviderTests).GetTypeInfo() - .GetMethod(nameof(GenericHasHandler), BindingFlags.Static | BindingFlags.NonPublic)! - .MakeGenericMethod(instance.GetType().GetTypeInfo().GetGenericArguments()[0]) - .Invoke(null, new[] { provider, instance })!; + private static bool HasHandler(ClientCapabilityProvider provider, object instance) + { + return (bool)typeof(ClientCapabilityProviderTests).GetTypeInfo() + .GetMethod(nameof(GenericHasHandler), BindingFlags.Static | BindingFlags.NonPublic)! + .MakeGenericMethod(instance.GetType().GetTypeInfo().GetGenericArguments()[0]) + .Invoke(null, new[] { provider, instance })!; + } private static bool GenericHasHandler(ClientCapabilityProvider provider, Supports supports) - where T : DynamicCapability => - provider.HasStaticHandler(supports); - - private static IEnumerable GetItems(IEnumerable types, Func?> func) => - types.Select(func).Where(z => z is not null).Select(z => z!.ToArray()); - - private static Type[] GetHandlerTypes(Type type) => - HandlerProvider.KnownHandlers - .SelectMany(z => z.AsEnumerable()) - .Where(x => x.HasCapability && x.CapabilityType == type) - .Select(z => z.HandlerType) - .Where(z => z.IsInterface && !z.IsGenericType) // only testing our interfaces - .ToArray(); - - private static LspHandlerTypeDescriptorProvider HandlerProvider = new LspHandlerTypeDescriptorProvider( - new[] { + where T : DynamicCapability + { + return provider.HasStaticHandler(supports); + } + + private static IEnumerable GetItems(IEnumerable types, Func?> func) + { + return types.Select(func).Where(z => z is not null).Select(z => z!.ToArray()); + } + + private static Type[] GetHandlerTypes(Type type) + { + return HandlerProvider.KnownHandlers + .SelectMany(z => z.AsEnumerable()) + .Where(x => x.HasCapability && x.CapabilityType == type) + .Select(z => z.HandlerType) + .Where(z => z.IsInterface && !z.IsGenericType) // only testing our interfaces + .ToArray(); + } + + private static readonly LspHandlerTypeDescriptorProvider HandlerProvider = new LspHandlerTypeDescriptorProvider( + new[] + { typeof(AssemblyScanningHandlerTypeDescriptorProvider).Assembly, typeof(LspHandlerTypeDescriptorProvider).Assembly, typeof(LanguageServer).Assembly, diff --git a/test/Lsp.Tests/DiagnosticKindTests.cs b/test/Lsp.Tests/DiagnosticKindTests.cs index 6ebd6a48f..8391071b2 100644 --- a/test/Lsp.Tests/DiagnosticKindTests.cs +++ b/test/Lsp.Tests/DiagnosticKindTests.cs @@ -1,6 +1,4 @@ using FluentAssertions; -using OmniSharp.Extensions.LanguageServer.Protocol; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using Xunit; @@ -14,7 +12,8 @@ public void DefaultBehavior_Should_Only_Support_InitialDiagnosticTags() { var serializer = new LspSerializer(); var json = serializer.SerializeObject( - new Diagnostic { + new Diagnostic + { Tags = new Container(DiagnosticTag.Deprecated) } ); diff --git a/test/Lsp.Tests/FluentAssertionsExtensions.cs b/test/Lsp.Tests/FluentAssertionsExtensions.cs index 6c12fb871..abfc4ba60 100644 --- a/test/Lsp.Tests/FluentAssertionsExtensions.cs +++ b/test/Lsp.Tests/FluentAssertionsExtensions.cs @@ -1,10 +1,6 @@ -using System; using FluentAssertions.Equivalency; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Microsoft.Extensions.Options; using NSubstitute; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; @@ -13,38 +9,40 @@ namespace Lsp.Tests { public static class FluentAssertionsExtensions { - public static EquivalencyAssertionOptions ConfigureForSupports(this EquivalencyAssertionOptions options, ILogger? logger = null) => - options - .WithTracing(new TraceWriter(logger ?? NullLogger.Instance)) - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>() - .ComparingByMembers>(); + public static EquivalencyAssertionOptions ConfigureForSupports(this EquivalencyAssertionOptions options, ILogger? logger = null) + { + return options + .WithTracing(new TraceWriter(logger ?? NullLogger.Instance)) + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>() + .ComparingByMembers>(); + } } } diff --git a/test/Lsp.Tests/FoundationTests.cs b/test/Lsp.Tests/FoundationTests.cs index 22a1bcfab..88d01deee 100644 --- a/test/Lsp.Tests/FoundationTests.cs +++ b/test/Lsp.Tests/FoundationTests.cs @@ -18,7 +18,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; using OmniSharp.Extensions.LanguageServer.Protocol.Server; @@ -34,11 +33,17 @@ public class FoundationTests { private readonly ILogger _logger; - public FoundationTests(ITestOutputHelper outputHelper) => _logger = new TestLoggerFactory(outputHelper).CreateLogger(typeof(FoundationTests)); + public FoundationTests(ITestOutputHelper outputHelper) + { + _logger = new TestLoggerFactory(outputHelper).CreateLogger(typeof(FoundationTests)); + } [Theory] [ClassData(typeof(ActionDelegateData))] - public void All_Create_Methods_Should_Work(ActionDelegate createDelegate) => createDelegate.Method.Should().NotThrow(); + public void All_Create_Methods_Should_Work(ActionDelegate createDelegate) + { + createDelegate.Method.Should().NotThrow(); + } public class ActionDelegateData : TheoryData { @@ -62,7 +67,8 @@ void BaseDelegate(LanguageServerOptions o) Add(new ActionDelegate("from (server): options, cancellationToken", () => LanguageServer.From(baseOptions, CancellationToken.None))); Add( new ActionDelegate( - "from (server): options, serviceProvider, cancellationToken", () => LanguageServer.From(baseOptions, serviceProvider, CancellationToken.None) + "from (server): options, serviceProvider, cancellationToken", + () => LanguageServer.From(baseOptions, serviceProvider, CancellationToken.None) ) ); Add(new ActionDelegate("from (server): options, serviceProvider", () => LanguageServer.From(baseOptions, serviceProvider))); @@ -70,7 +76,8 @@ void BaseDelegate(LanguageServerOptions o) Add(new ActionDelegate("from (server): action, cancellationToken", () => LanguageServer.From(BaseDelegate, CancellationToken.None))); Add( new ActionDelegate( - "from (server): action, serviceProvider, cancellationToken", () => LanguageServer.From(BaseDelegate, serviceProvider, CancellationToken.None) + "from (server): action, serviceProvider, cancellationToken", + () => LanguageServer.From(BaseDelegate, serviceProvider, CancellationToken.None) ) ); Add(new ActionDelegate("from (server): action, serviceProvider", () => LanguageServer.From(BaseDelegate, serviceProvider))); @@ -93,7 +100,8 @@ void BaseDelegate(LanguageClientOptions o) Add(new ActionDelegate("from (client): options, cancellationToken", () => LanguageClient.From(baseOptions, CancellationToken.None))); Add( new ActionDelegate( - "from (client): options, serviceProvider, cancellationToken", () => LanguageClient.From(baseOptions, serviceProvider, CancellationToken.None) + "from (client): options, serviceProvider, cancellationToken", + () => LanguageClient.From(baseOptions, serviceProvider, CancellationToken.None) ) ); Add(new ActionDelegate("from (client): options, serviceProvider", () => LanguageClient.From(baseOptions, serviceProvider))); @@ -101,7 +109,8 @@ void BaseDelegate(LanguageClientOptions o) Add(new ActionDelegate("from (client): action, cancellationToken", () => LanguageClient.From(BaseDelegate, CancellationToken.None))); Add( new ActionDelegate( - "from (client): action, serviceProvider, cancellationToken", () => LanguageClient.From(BaseDelegate, serviceProvider, CancellationToken.None) + "from (client): action, serviceProvider, cancellationToken", + () => LanguageClient.From(BaseDelegate, serviceProvider, CancellationToken.None) ) ); Add(new ActionDelegate("from (client): action, serviceProvider", () => LanguageClient.From(BaseDelegate, serviceProvider))); @@ -120,7 +129,10 @@ public ActionDelegate(string name, Action method) Method = method; } - public override string ToString() => _name; + public override string ToString() + { + return _name; + } } @@ -130,8 +142,8 @@ public void Debugger_Display_Should_Not_Throw(Type type) { var instance = Activator.CreateInstance(type); var property = type.GetProperty("DebuggerDisplay", BindingFlags.NonPublic | BindingFlags.Instance)!; - Func a1 = () => ( property.GetValue(instance) as string )!; - Func a2 = () => instance!.ToString()!; + var a1 = () => ( property.GetValue(instance) as string )!; + var a2 = () => instance!.ToString()!; a1.Should().NotThrow().And.NotBeNull(); a2.Should().NotThrow().And.NotBeNull(); @@ -143,9 +155,12 @@ public DebuggerDisplayTypes() { foreach (var item in typeof(DocumentSymbol).Assembly.ExportedTypes .Where(z => !z.IsGenericTypeDefinition) - .Where(z => z.GetCustomAttributes().Any(x => x.Value.StartsWith("{DebuggerDisplay"))) + .Where( + z => z.GetCustomAttributes() + .Any(x => x.Value.StartsWith("{DebuggerDisplay")) + ) .Where(z => z.GetConstructors().Any(x => x.GetParameters().Length == 0)) - ) + ) { Add(item); } @@ -154,15 +169,19 @@ public DebuggerDisplayTypes() [Theory(DisplayName = "Params types should have a method attribute")] [ClassData(typeof(ParamsShouldHaveMethodAttributeData))] - public void ParamsShouldHaveMethodAttribute(Type type) => + public void ParamsShouldHaveMethodAttribute(Type type) + { MethodAttribute.AllFrom(type).Any(z => z.Direction != Direction.Unspecified).Should() .Be(true, $"{type.Name} is missing a method attribute or the direction is not specified"); + } [Theory(DisplayName = "Handler interfaces should have a method attribute")] [ClassData(typeof(HandlersShouldHaveMethodAttributeData))] - public void HandlersShouldHaveMethodAttribute(Type type) => + public void HandlersShouldHaveMethodAttribute(Type type) + { MethodAttribute.AllFrom(type).Any(z => z.Direction != Direction.Unspecified).Should() .Be(true, $"{type.Name} is missing a method attribute or the direction is not specified"); + } [Theory(DisplayName = "Handler method should match params method")] [ClassData(typeof(HandlersShouldHaveMethodAttributeData))] @@ -192,7 +211,8 @@ public void HandlersShouldAbstractClass(ILspHandlerTypeDescriptor descriptor) { _logger.LogInformation("Handler: {Type}", descriptor.HandlerType); // This test requires a refactor, the delegating handlers have been removed and replaced by shared implementations - var abstractHandler = descriptor.HandlerType.Assembly.ExportedTypes.FirstOrDefault(z => z.IsAbstract && z.IsClass && descriptor.HandlerType.IsAssignableFrom(z)); + var abstractHandler = + descriptor.HandlerType.Assembly.ExportedTypes.FirstOrDefault(z => z.IsAbstract && z.IsClass && descriptor.HandlerType.IsAssignableFrom(z)); abstractHandler.Should().NotBeNull($"{descriptor.HandlerType.FullName} is missing abstract base class"); var delegatingHandler = descriptor.HandlerType.Assembly.DefinedTypes.FirstOrDefault( @@ -206,7 +226,7 @@ public void HandlersShouldAbstractClass(ILspHandlerTypeDescriptor descriptor) _logger.LogInformation("Delegating Handler: {Type}", delegatingHandler); delegatingHandler.DeclaringType.Should().NotBeNull(); delegatingHandler.DeclaringType!.GetMethods(BindingFlags.Public | BindingFlags.Static).Any(z => z.Name.StartsWith("On")).Should() - .BeTrue($"{descriptor.HandlerType.FullName} is missing delegating extension method"); + .BeTrue($"{descriptor.HandlerType.FullName} is missing delegating extension method"); } } @@ -225,9 +245,11 @@ public void HandlersShouldExtensionMethodClassWithMethods( ); extensionClass.Should().NotBeNull($"{descriptor.HandlerType.FullName} is missing extension method class"); - extensionClass.GetMethods().Any(z => z.Name == onMethodName && typeof(IJsonRpcHandlerRegistry).IsAssignableFrom(z.GetParameters()[0].ParameterType)).Should() + extensionClass.GetMethods().Any(z => z.Name == onMethodName && typeof(IJsonRpcHandlerRegistry).IsAssignableFrom(z.GetParameters()[0].ParameterType)) + .Should() .BeTrue($"{descriptor.HandlerType.FullName} is missing event extension methods named {onMethodName}"); - extensionClass.GetMethods().Any(z => z.Name == sendMethodName && typeof(IResponseRouter).IsAssignableFrom(z.GetParameters()[0].ParameterType)).Should() + extensionClass.GetMethods().Any(z => z.Name == sendMethodName && typeof(IResponseRouter).IsAssignableFrom(z.GetParameters()[0].ParameterType)) + .Should() .BeTrue($"{descriptor.HandlerType.FullName} is missing execute extension methods named {sendMethodName}"); var registries = extensionClass.GetMethods(BindingFlags.Static | BindingFlags.Public) @@ -289,17 +311,26 @@ public void HandlersShouldHaveExpectedExtensionMethodsBasedOnDirection( extensionClass, extensionClassName, onMethodName, sendMethodName ); - var expectedEventRegistries = descriptor.Direction switch { - Direction.ClientToServer => new (string type, Func matcher)[] { ( "Server", info => info.ParameterType.Name.EndsWith("ServerRegistry") ) }, - Direction.ServerToClient => new (string type, Func matcher)[] { ( "Client", info => info.ParameterType.Name.EndsWith("ClientRegistry") ) }, + var expectedEventRegistries = descriptor.Direction switch + { + Direction.ClientToServer => new (string type, Func matcher)[] + { ( "Server", info => info.ParameterType.Name.EndsWith("ServerRegistry") ) }, + Direction.ServerToClient => new (string type, Func matcher)[] + { ( "Client", info => info.ParameterType.Name.EndsWith("ClientRegistry") ) }, Direction.Bidirectional => new (string type, Func matcher)[] - { ( "Server", info => info.ParameterType.Name.EndsWith("ServerRegistry") ), ( "Client", info => info.ParameterType.Name.EndsWith("ClientRegistry") ) }, + { + ( "Server", info => info.ParameterType.Name.EndsWith("ServerRegistry") ), + ( "Client", info => info.ParameterType.Name.EndsWith("ClientRegistry") ) + }, _ => throw new NotImplementedException(descriptor.HandlerType.FullName) }; - var expectedRequestHandlers = descriptor.Direction switch { - Direction.ClientToServer => new (string type, Func matcher)[] { ( "Server", info => info.ParameterType.Name.EndsWith("Client") ) }, - Direction.ServerToClient => new (string type, Func matcher)[] { ( "Client", info => info.ParameterType.Name.EndsWith("Server") ) }, + var expectedRequestHandlers = descriptor.Direction switch + { + Direction.ClientToServer => new (string type, Func matcher)[] + { ( "Server", info => info.ParameterType.Name.EndsWith("Client") ) }, + Direction.ServerToClient => new (string type, Func matcher)[] + { ( "Client", info => info.ParameterType.Name.EndsWith("Server") ) }, Direction.Bidirectional => new (string type, Func matcher)[] { ( "Server", info => info.ParameterType.Name.EndsWith("Client") ), ( "Client", info => info.ParameterType.Name.EndsWith("Server") ) }, _ => throw new NotImplementedException(descriptor.HandlerType.FullName) @@ -354,7 +385,9 @@ Func ForAnyParameter(Func m) return info => info.GetParameters().Any(m); } - var containsCancellationToken = ForAnyParameter(info => info.ParameterType.GetGenericArguments().Reverse().Take(2).Any(x => x == typeof(CancellationToken))); + var containsCancellationToken = ForAnyParameter( + info => info.ParameterType.GetGenericArguments().Reverse().Take(2).Any(x => x == typeof(CancellationToken)) + ); var returnType = descriptor.HasResponseType ? typeof(Task<>).MakeGenericType(descriptor.ResponseType!) : typeof(Task); var returns = ForAnyParameter(info => info.ParameterType.GetGenericArguments().LastOrDefault() == returnType); var isAction = ForAnyParameter(info => info.ParameterType.Name.StartsWith(nameof(Action))); @@ -365,24 +398,33 @@ Func ForAnyParameter(Func m) if (descriptor.IsRequest && TypeHandlerExtensionData.HandlersToSkip.All(z => descriptor.HandlerType != z)) { matcher.Match($"Func<{descriptor.ParamsType!.Name}, {returnType.Name}>", isFunc, takesParameter, returns); - matcher.Match($"Func<{descriptor.ParamsType.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, containsCancellationToken, returns); + matcher.Match( + $"Func<{descriptor.ParamsType.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, containsCancellationToken, returns + ); if (descriptor.HasCapability) { matcher.Match( - $"Func<{descriptor.ParamsType.Name}, {descriptor.CapabilityType!.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, + $"Func<{descriptor.ParamsType.Name}, {descriptor.CapabilityType!.Name}, CancellationToken, {returnType.Name}>", isFunc, + takesParameter, takesCapability, containsCancellationToken, returns ); } if (descriptor.HasPartialItem) { - var capability = ForAnyParameter(info => info.ParameterType.GetGenericArguments().Skip(2).FirstOrDefault() == descriptor.CapabilityType); + var capability = ForAnyParameter( + info => info.ParameterType.GetGenericArguments().Skip(2).FirstOrDefault() == descriptor.CapabilityType + ); var observesPartialResultType = ForAnyParameter( info => - info.ParameterType.GetGenericArguments().Skip(1).FirstOrDefault() == typeof(IObserver<>).MakeGenericType(descriptor.PartialItemType!) + info.ParameterType.GetGenericArguments().Skip(1).FirstOrDefault() + == typeof(IObserver<>).MakeGenericType(descriptor.PartialItemType!) ); - matcher.Match($"Action<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType!.Name}>>", isAction, takesParameter, observesPartialResultType); + matcher.Match( + $"Action<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType!.Name}>>", isAction, takesParameter, + observesPartialResultType + ); // matcher.Match($"Func<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType.Name}>, Task>", isFunc, takesParameter, observesPartialResultType, returnsTask); matcher.Match( $"Action<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType.Name}>, CancellationToken>", isAction, takesParameter, @@ -408,7 +450,9 @@ Func ForAnyParameter(Func m) if (descriptor.HasPartialItems) { - var capability = ForAnyParameter(info => info.ParameterType.GetGenericArguments().Skip(2).FirstOrDefault() == descriptor.CapabilityType); + var capability = ForAnyParameter( + info => info.ParameterType.GetGenericArguments().Skip(2).FirstOrDefault() == descriptor.CapabilityType + ); var observesPartialResultType = ForAnyParameter( info => info.ParameterType.GetGenericArguments().Skip(1).FirstOrDefault() == @@ -449,17 +493,21 @@ Func ForAnyParameter(Func m) if (descriptor.IsNotification) { matcher.Match($"Func<{descriptor.ParamsType!.Name}, {returnType.Name}>", isFunc, takesParameter, returns); - matcher.Match($"Func<{descriptor.ParamsType.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, containsCancellationToken, returns); + matcher.Match( + $"Func<{descriptor.ParamsType.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, containsCancellationToken, returns + ); matcher.Match($"Action<{descriptor.ParamsType.Name}>", isAction, takesParameter); matcher.Match($"Action<{descriptor.ParamsType.Name}, CancellationToken>", isAction, takesParameter, containsCancellationToken); if (descriptor.HasCapability) { matcher.Match( - $"Func<{descriptor.ParamsType.Name}, {descriptor.CapabilityType!.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, + $"Func<{descriptor.ParamsType.Name}, {descriptor.CapabilityType!.Name}, CancellationToken, {returnType.Name}>", isFunc, + takesParameter, takesCapability, containsCancellationToken, returns ); matcher.Match( - $"Action<{descriptor.ParamsType.Name}, {descriptor.CapabilityType.Name}, CancellationToken>", isAction, takesParameter, takesCapability, + $"Action<{descriptor.ParamsType.Name}, {descriptor.CapabilityType.Name}, CancellationToken>", isAction, takesParameter, + takesCapability, containsCancellationToken ); } @@ -467,7 +515,8 @@ Func ForAnyParameter(Func m) } { var matcher = new MethodMatcher(sendMethodRegistries, descriptor, extensionClass); - Func containsCancellationToken = info => info.GetParameters().Reverse().Take(2).Any(x => x.ParameterType == typeof(CancellationToken)); + Func containsCancellationToken = + info => info.GetParameters().Reverse().Take(2).Any(x => x.ParameterType == typeof(CancellationToken)); var returnType = descriptor.HasResponseType ? typeof(Task<>).MakeGenericType(descriptor.ResponseType!) : typeof(Task); Func returns = info => info.ReturnType == returnType; Func isAction = info => info.ReturnType.Name == "Void"; @@ -476,7 +525,9 @@ Func ForAnyParameter(Func m) if (descriptor.IsRequest && descriptor.HasPartialItems) { Func partialReturnType = info => - typeof(IRequestProgressObservable<,>).MakeGenericType(typeof(IEnumerable<>).MakeGenericType(descriptor.PartialItemsType!), descriptor.ResponseType!) + typeof(IRequestProgressObservable<,>).MakeGenericType( + typeof(IEnumerable<>).MakeGenericType(descriptor.PartialItemsType!), descriptor.ResponseType! + ) .IsAssignableFrom(info.ReturnType); matcher.Match( $"Func<{descriptor.ParamsType!.Name}, CancellationToken, IProgressObservable, {descriptor.ResponseType!.Name}>>", @@ -486,7 +537,8 @@ Func ForAnyParameter(Func m) else if (descriptor.IsRequest && descriptor.HasPartialItem) { Func partialReturnType = info => - typeof(IRequestProgressObservable<,>).MakeGenericType(descriptor.PartialItemType!, descriptor.ResponseType!).IsAssignableFrom(info.ReturnType); + typeof(IRequestProgressObservable<,>).MakeGenericType(descriptor.PartialItemType!, descriptor.ResponseType!) + .IsAssignableFrom(info.ReturnType); matcher.Match( $"Func<{descriptor.ParamsType!.Name}, CancellationToken, IProgressObservable<{descriptor.PartialItemType!.Name}, {descriptor.ResponseType!.Name}>>", takesParameter, containsCancellationToken, partialReturnType @@ -494,7 +546,9 @@ Func ForAnyParameter(Func m) } else if (descriptor.IsRequest) { - matcher.Match($"Func<{descriptor.ParamsType!.Name}, CancellationToken, {returnType.Name}>", takesParameter, containsCancellationToken, returns); + matcher.Match( + $"Func<{descriptor.ParamsType!.Name}, CancellationToken, {returnType.Name}>", takesParameter, containsCancellationToken, returns + ); } else if (descriptor.IsNotification) { @@ -548,7 +602,8 @@ public void Match(string description, params Func[] matchers) method.Invoke( null, - new[] { + new[] + { registrySub, Substitute.For(new[] { method.GetParameters()[1].ParameterType }, Array.Empty()), }.Concat( method.GetParameters().Skip(2).Select( @@ -563,7 +618,8 @@ public void Match(string description, params Func[] matchers) registrySub.Received().ReceivedCalls() .Any( - z => z.GetMethodInfo().Name == nameof(IJsonRpcHandlerRegistry>.AddHandler) && + z => z.GetMethodInfo().Name + == nameof(IJsonRpcHandlerRegistry>.AddHandler) && z.GetArguments().Length == 3 && z.GetArguments()[0].Equals(_descriptor.Method) ) @@ -615,9 +671,11 @@ public class ParamsShouldHaveMethodAttributeData : TheoryData public ParamsShouldHaveMethodAttributeData() { foreach (var type in typeof(CompletionParams).Assembly.ExportedTypes.Where( - z => - z.IsClass && !z.IsAbstract && z.GetInterfaces().Any(x => x.IsGenericType && typeof(IRequest<>).IsAssignableFrom(x.GetGenericTypeDefinition())) - )) + z => + z.IsClass && !z.IsAbstract && z.GetInterfaces().Any( + x => x.IsGenericType && typeof(IRequest<>).IsAssignableFrom(x.GetGenericTypeDefinition()) + ) + )) { Add(type); } @@ -631,7 +689,7 @@ public HandlersShouldHaveMethodAttributeData() foreach (var type in typeof(CompletionParams).Assembly.ExportedTypes.Where(z => z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z)) .Where(z => !z.Name.EndsWith("Manager")) .Except(new[] { typeof(ITextDocumentSyncHandler) }) - ) + ) { if (type.IsGenericTypeDefinition && !MethodAttribute.AllFrom(type).Any()) continue; Add(type); @@ -648,7 +706,7 @@ public RegistrationConverters() .Where(z => z.IsClass && !z.IsAbstract && typeof(IRegistrationOptionsConverter).IsAssignableFrom(z)) .Where(z => z.BaseType?.IsGenericType == true && z.BaseType.GetGenericArguments().Length == 2) .Where(z => !z.FullName?.Contains("TextDocumentSyncRegistrationOptions") == true) - ) + ) { Add(type); } @@ -661,7 +719,8 @@ public TypeHandlerData() { var handlerTypeDescriptorProvider = new LspHandlerTypeDescriptorProvider( - new[] { + new[] + { typeof(AssemblyScanningHandlerTypeDescriptorProvider).Assembly, typeof(LspHandlerTypeDescriptorProvider).Assembly, typeof(LanguageServer).Assembly, @@ -673,7 +732,7 @@ public TypeHandlerData() foreach (var type in typeof(CompletionParams).Assembly.ExportedTypes.Where(z => z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z)) .Where(z => !z.Name.EndsWith("Manager")) .Except(new[] { typeof(ITextDocumentSyncHandler), typeof(IExecuteCommandHandler<>) }) - ) + ) { if (type.IsGenericTypeDefinition && !MethodAttribute.AllFrom(type).Any()) continue; Add(handlerTypeDescriptorProvider.GetHandlerTypeDescriptor(type)!); @@ -683,7 +742,8 @@ public TypeHandlerData() public class TypeHandlerExtensionData : TheoryData { - public static Type[] HandlersToSkip = { + public static Type[] HandlersToSkip = + { typeof(ISemanticTokensFullHandler), typeof(ISemanticTokensDeltaHandler), typeof(ISemanticTokensRangeHandler), @@ -694,7 +754,8 @@ public TypeHandlerExtensionData() { var handlerTypeDescriptorProvider = new LspHandlerTypeDescriptorProvider( - new[] { + new[] + { typeof(AssemblyScanningHandlerTypeDescriptorProvider).Assembly, typeof(LspHandlerTypeDescriptorProvider).Assembly, typeof(LanguageServer).Assembly, @@ -707,14 +768,15 @@ public TypeHandlerExtensionData() .Where(z => z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z)) .Where(z => !z.Name.EndsWith("Manager")) .Except(new[] { typeof(ITextDocumentSyncHandler) }) - ) + ) { if (type.IsGenericTypeDefinition && !MethodAttribute.AllFrom(type).Any()) continue; if (type.Name.EndsWith("Manager")) continue; if (type == typeof(IExecuteCommandHandler<>)) continue; if (type == typeof(ICompletionResolveHandler) || type == typeof(ICodeLensResolveHandler) || type == typeof(IDocumentLinkResolveHandler) || type == typeof(ICodeActionResolveHandler)) continue; - if (type == typeof(ISemanticTokensFullHandler) || type == typeof(ISemanticTokensDeltaHandler) || type == typeof(ISemanticTokensRangeHandler)) continue; + if (type == typeof(ISemanticTokensFullHandler) || type == typeof(ISemanticTokensDeltaHandler) + || type == typeof(ISemanticTokensRangeHandler)) continue; var descriptor = handlerTypeDescriptorProvider.GetHandlerTypeDescriptor(type); if (descriptor == null) @@ -733,14 +795,19 @@ public TypeHandlerExtensionData() } } - private static string GetExtensionClassName(IHandlerTypeDescriptor descriptor) => SpecialCasedHandlerName(descriptor) + "Extensions"; + private static string GetExtensionClassName(IHandlerTypeDescriptor descriptor) + { + return SpecialCasedHandlerName(descriptor) + "Extensions"; + } - private static string SpecialCasedHandlerName(IHandlerTypeDescriptor descriptor) => - new Regex(@"(\w+(?:\`\d)?)$") + private static string SpecialCasedHandlerName(IHandlerTypeDescriptor descriptor) + { + return new Regex(@"(\w+(?:\`\d)?)$") .Replace( descriptor.HandlerType.Name, descriptor.HandlerType.Name.Substring(1, descriptor.HandlerType.Name.IndexOf("Handler", StringComparison.Ordinal) - 1) ); + } private static Type GetExtensionClass(IHandlerTypeDescriptor descriptor) { @@ -749,7 +816,10 @@ private static Type GetExtensionClass(IHandlerTypeDescriptor descriptor) .FirstOrDefault(z => z.IsClass && z.IsAbstract && ( z.Name == name || z.Name == name + "Base" ))!; } - private static string GetOnMethodName(IHandlerTypeDescriptor descriptor) => "On" + SpecialCasedHandlerName(descriptor); + private static string GetOnMethodName(IHandlerTypeDescriptor descriptor) + { + return "On" + SpecialCasedHandlerName(descriptor); + } private static string GetSendMethodName(ILspHandlerTypeDescriptor descriptor) { diff --git a/test/Lsp.Tests/Models/CodeLensTests.cs b/test/Lsp.Tests/Models/CodeLensTests.cs index aece16f03..fe8f94dda 100644 --- a/test/Lsp.Tests/Models/CodeLensTests.cs +++ b/test/Lsp.Tests/Models/CodeLensTests.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; -using System.Reflection; using FluentAssertions; -using FluentAssertions.Equivalency; using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using NSubstitute; @@ -28,14 +26,17 @@ public CodeLensTests(ITestOutputHelper testOutputHelper) [JsonFixture] public void SimpleTest(string expected) { - var model = new CodeLens { - Command = new Command { + var model = new CodeLens + { + Command = new Command + { Arguments = new JArray { 1, "2", true }, Name = "abc", Title = "Cool story bro" }, Data = JObject.FromObject( - new Dictionary { + new Dictionary + { { "somethingCool", 1 } } ), diff --git a/test/Lsp.Tests/Models/CompletionItemKindTests.cs b/test/Lsp.Tests/Models/CompletionItemKindTests.cs index 96eeda557..5f5b7c846 100644 --- a/test/Lsp.Tests/Models/CompletionItemKindTests.cs +++ b/test/Lsp.Tests/Models/CompletionItemKindTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using TestingUtils; using Xunit; namespace Lsp.Tests.Models diff --git a/test/Lsp.Tests/Models/DiagnosticSeverityTests.cs b/test/Lsp.Tests/Models/DiagnosticSeverityTests.cs index e39cbbfa0..731ae8f2b 100644 --- a/test/Lsp.Tests/Models/DiagnosticSeverityTests.cs +++ b/test/Lsp.Tests/Models/DiagnosticSeverityTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using TestingUtils; using Xunit; namespace Lsp.Tests.Models diff --git a/test/Lsp.Tests/Models/DocumentHighlightKindTests.cs b/test/Lsp.Tests/Models/DocumentHighlightKindTests.cs index 93222c6dd..64318b694 100644 --- a/test/Lsp.Tests/Models/DocumentHighlightKindTests.cs +++ b/test/Lsp.Tests/Models/DocumentHighlightKindTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using TestingUtils; using Xunit; namespace Lsp.Tests.Models diff --git a/test/Lsp.Tests/Models/FileChangeTypeTests.cs b/test/Lsp.Tests/Models/FileChangeTypeTests.cs index ebbb01dc0..f61096fc4 100644 --- a/test/Lsp.Tests/Models/FileChangeTypeTests.cs +++ b/test/Lsp.Tests/Models/FileChangeTypeTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using TestingUtils; using Xunit; namespace Lsp.Tests.Models diff --git a/test/Lsp.Tests/Models/InsertTextFormatTests.cs b/test/Lsp.Tests/Models/InsertTextFormatTests.cs index 296c57361..97927005f 100644 --- a/test/Lsp.Tests/Models/InsertTextFormatTests.cs +++ b/test/Lsp.Tests/Models/InsertTextFormatTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using TestingUtils; using Xunit; namespace Lsp.Tests.Models diff --git a/test/Lsp.Tests/Models/MessageTypeTests.cs b/test/Lsp.Tests/Models/MessageTypeTests.cs index 1bc6410a6..cf1dd7647 100644 --- a/test/Lsp.Tests/Models/MessageTypeTests.cs +++ b/test/Lsp.Tests/Models/MessageTypeTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using TestingUtils; using Xunit; namespace Lsp.Tests.Models diff --git a/test/Lsp.Tests/Models/SymbolKindTests.cs b/test/Lsp.Tests/Models/SymbolKindTests.cs index 9db4cef02..6a192c19f 100644 --- a/test/Lsp.Tests/Models/SymbolKindTests.cs +++ b/test/Lsp.Tests/Models/SymbolKindTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using TestingUtils; using Xunit; namespace Lsp.Tests.Models diff --git a/test/Lsp.Tests/Models/TextDocumentSaveReasonTests.cs b/test/Lsp.Tests/Models/TextDocumentSaveReasonTests.cs index 28111a0ac..75a6e2aa4 100644 --- a/test/Lsp.Tests/Models/TextDocumentSaveReasonTests.cs +++ b/test/Lsp.Tests/Models/TextDocumentSaveReasonTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using TestingUtils; using Xunit; namespace Lsp.Tests.Models diff --git a/test/Lsp.Tests/SemanticTokensDocumentTests.cs b/test/Lsp.Tests/SemanticTokensDocumentTests.cs index 0e780a36f..0c240ac45 100644 --- a/test/Lsp.Tests/SemanticTokensDocumentTests.cs +++ b/test/Lsp.Tests/SemanticTokensDocumentTests.cs @@ -4,13 +4,11 @@ using System.Linq; using System.Text; using Bogus; -using Bogus.Extensions; using FluentAssertions; using Microsoft.Extensions.Logging; using NSubstitute; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; using Xunit; using Xunit.Abstractions; using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; @@ -28,47 +26,50 @@ public SemanticTokensDocumentTests(ITestOutputHelper testOutputHelper) { var loggerFactory = new TestLoggerFactory(testOutputHelper); _logger = loggerFactory.CreateLogger(); - _legend = new SemanticTokensLegend { + _legend = new SemanticTokensLegend + { // specify a specific set so that additions to the default list do not cause breaks in the tests. - TokenModifiers = new[] { - new SemanticTokenModifier("documentation"), - new SemanticTokenModifier("declaration"), - new SemanticTokenModifier("definition"), - new SemanticTokenModifier("static"), - new SemanticTokenModifier("async"), - new SemanticTokenModifier("abstract"), - new SemanticTokenModifier("deprecated"), - new SemanticTokenModifier("readonly"), - new SemanticTokenModifier("modification"), - new SemanticTokenModifier("defaultLibrary") - } - .ToArray(), - TokenTypes = new[] { - new SemanticTokenType("comment"), - new SemanticTokenType("keyword"), - new SemanticTokenType("string"), - new SemanticTokenType("number"), - new SemanticTokenType("regexp"), - new SemanticTokenType("operator"), - new SemanticTokenType("namespace"), - new SemanticTokenType("type"), - new SemanticTokenType("struct"), - new SemanticTokenType("class"), - new SemanticTokenType("interface"), - new SemanticTokenType("enum"), - new SemanticTokenType("typeParameter"), - new SemanticTokenType("function"), - new SemanticTokenType("member"), - new SemanticTokenType("property"), - new SemanticTokenType("macro"), - new SemanticTokenType("variable"), - new SemanticTokenType("parameter"), - new SemanticTokenType("label"), - new SemanticTokenType("modifier"), - new SemanticTokenType("event"), - new SemanticTokenType("enumMember"), - } - .ToArray(), + TokenModifiers = new[] + { + new SemanticTokenModifier("documentation"), + new SemanticTokenModifier("declaration"), + new SemanticTokenModifier("definition"), + new SemanticTokenModifier("static"), + new SemanticTokenModifier("async"), + new SemanticTokenModifier("abstract"), + new SemanticTokenModifier("deprecated"), + new SemanticTokenModifier("readonly"), + new SemanticTokenModifier("modification"), + new SemanticTokenModifier("defaultLibrary") + } + .ToArray(), + TokenTypes = new[] + { + new SemanticTokenType("comment"), + new SemanticTokenType("keyword"), + new SemanticTokenType("string"), + new SemanticTokenType("number"), + new SemanticTokenType("regexp"), + new SemanticTokenType("operator"), + new SemanticTokenType("namespace"), + new SemanticTokenType("type"), + new SemanticTokenType("struct"), + new SemanticTokenType("class"), + new SemanticTokenType("interface"), + new SemanticTokenType("enum"), + new SemanticTokenType("typeParameter"), + new SemanticTokenType("function"), + new SemanticTokenType("member"), + new SemanticTokenType("property"), + new SemanticTokenType("macro"), + new SemanticTokenType("variable"), + new SemanticTokenType("parameter"), + new SemanticTokenType("label"), + new SemanticTokenType("modifier"), + new SemanticTokenType("event"), + new SemanticTokenType("enumMember"), + } + .ToArray(), }; } @@ -87,13 +88,19 @@ public void ReturnDocumentTokensFromScratch() result.ResultId.Should().Be(document.Id); var data = Normalize(ExampleDocumentText, result.Data).ToArray(); _logger.LogInformation("Some Data {Data}", data.AsEnumerable()); - var expectedResponse = new NormalizedToken[] { - "using (macro:async|deprecated)", "System (macro:async|deprecated)", "using (event:none)", "System (number:none)", "Collections (struct:readonly)", - "Generic (class:none)", "using (variable:modification|defaultLibrary)", "System (comment:static|deprecated)", "Linq (comment:definition)", "using (comment:none)", - "System (enumMember:none)", "Text (comment:static|deprecated)", "using (comment:none)", "System (comment:declaration)", "Threading (comment:static|defaultLibrary)", + var expectedResponse = new NormalizedToken[] + { + "using (macro:async|deprecated)", "System (macro:async|deprecated)", "using (event:none)", "System (number:none)", + "Collections (struct:readonly)", + "Generic (class:none)", "using (variable:modification|defaultLibrary)", "System (comment:static|deprecated)", "Linq (comment:definition)", + "using (comment:none)", + "System (enumMember:none)", "Text (comment:static|deprecated)", "using (comment:none)", "System (comment:declaration)", + "Threading (comment:static|defaultLibrary)", "Tasks (comment:none)", "namespace (comment:readonly)", "CSharpTutorials (comment:none)", "{ (struct:documentation)", "class (enumMember:none)", - "Program (comment:none)", "{ (comment:none)", "static (regexp:documentation)", "void (macro:none)", "Main (macro:none)", "string[] (property:declaration|abstract)", - "args (macro:none)", "{ (interface:documentation|declaration|deprecated)", "string (struct:none)", "message (enum:none)", "= (label:none)", "Hello (comment:none)", + "Program (comment:none)", "{ (comment:none)", "static (regexp:documentation)", "void (macro:none)", "Main (macro:none)", + "string[] (property:declaration|abstract)", + "args (macro:none)", "{ (interface:documentation|declaration|deprecated)", "string (struct:none)", "message (enum:none)", "= (label:none)", + "Hello (comment:none)", "World!! (enum:none)", "Console (interface:static)", "WriteLine (event:async|modification)", "message (interface:static)", "} (operator:none)", "} (enum:async|deprecated)", "} (function:declaration|async)" }; @@ -124,50 +131,66 @@ public class ReturnDocumentTokensFromScratchForRangeData : TheoryData expectedTokens builder.Commit(); originalTokens = document.GetSemanticTokens(); builder = document.Edit( - new SemanticTokensDeltaParams { + new SemanticTokensDeltaParams + { PreviousResultId = document.Id, } ); @@ -209,7 +233,7 @@ IEnumerable expectedTokens var edit1Tokens = originalTokens.Data .RemoveRange(edit1.Start, edit1.DeleteCount) - .InsertRange(edit1.Start, edit1.Data); + .InsertRange(edit1.Start, edit1.Data!); var edit1Data = Normalize(modifiedText, edit1Tokens).ToArray(); _logger.LogDebug("Some Data {Data}", edit1Data.AsEnumerable()); @@ -223,26 +247,36 @@ public ReturnDocumentEditsData() Add( ExampleDocumentText, ExampleDocumentText.Replace("namespace CSharpTutorials", "namespace Something.Else.Entirely"), - new NormalizedToken[] { - "using (macro:async|deprecated)", "System (macro:async|deprecated)", "using (event:none)", "System (number:none)", "Collections (struct:readonly)", - "Generic (class:none)", "using (variable:modification|defaultLibrary)", "System (comment:static|deprecated)", "Linq (comment:definition)", - "using (comment:none)", "System (enumMember:none)", "Text (comment:static|deprecated)", "using (comment:none)", "System (comment:declaration)", - "Threading (comment:static|defaultLibrary)", "Tasks (comment:none)", "namespace (property:defaultLibrary)", "Something (property:defaultLibrary)", - "Else (enum:deprecated)", "Entirely (operator:declaration|deprecated|modification)", "{ (struct:documentation)", "class (enumMember:none)", + new NormalizedToken[] + { + "using (macro:async|deprecated)", "System (macro:async|deprecated)", "using (event:none)", "System (number:none)", + "Collections (struct:readonly)", + "Generic (class:none)", "using (variable:modification|defaultLibrary)", "System (comment:static|deprecated)", + "Linq (comment:definition)", + "using (comment:none)", "System (enumMember:none)", "Text (comment:static|deprecated)", "using (comment:none)", + "System (comment:declaration)", + "Threading (comment:static|defaultLibrary)", "Tasks (comment:none)", "namespace (property:defaultLibrary)", + "Something (property:defaultLibrary)", + "Else (enum:deprecated)", "Entirely (operator:declaration|deprecated|modification)", "{ (struct:documentation)", + "class (enumMember:none)", "Program (comment:none)", "{ (comment:none)", "static (regexp:documentation)", "void (macro:none)", "Main (macro:none)", - "string[] (property:declaration|abstract)", "args (macro:none)", "{ (interface:documentation|declaration|deprecated)", "string (struct:none)", + "string[] (property:declaration|abstract)", "args (macro:none)", "{ (interface:documentation|declaration|deprecated)", + "string (struct:none)", "message (enum:none)", "= (label:none)", "Hello (comment:none)", "World!! (enum:none)", "Console (interface:static)", - "WriteLine (event:async|modification)", "message (interface:static)", "} (operator:none)", "} (enum:async|deprecated)", "} (function:declaration|async)" + "WriteLine (event:async|modification)", "message (interface:static)", "} (operator:none)", "} (enum:async|deprecated)", + "} (function:declaration|async)" } ); Add( "using", "using System;", - new NormalizedToken[] { + new NormalizedToken[] + { "using (macro:async|deprecated)", "System (macro:async|deprecated)" } ); Add( - "using System;", "using", new NormalizedToken[] { + "using System;", "using", new NormalizedToken[] + { "using (macro:async|deprecated)" } ); @@ -253,8 +287,11 @@ private class TokenizationValue { // ReSharper disable once UnusedAutoPropertyAccessor.Local public SemanticTokenType Type { get; set; } + // ReSharper disable once UnusedAutoPropertyAccessor.Local - public SemanticTokenModifier[] Modifiers { get; set; } = Array.Empty(); +#pragma warning disable CS8618 + public SemanticTokenModifier[] Modifiers { get; set; } +#pragma warning restore CS8618 } private void Tokenize(string document, SemanticTokensBuilder builder) @@ -276,7 +313,7 @@ private void Tokenize(string document, SemanticTokensBuilder builder) .OrNull(f, 0.2f) ); - foreach (var (line, text) in document.Split('\n').Select((text, line) => (line, text))) + foreach (var (line, text) in document.Split('\n').Select((text, line) => ( line, text ))) { var parts = text.TrimEnd().Split(';', ' ', '.', '"', '(', ')'); var index = 0; @@ -295,7 +332,7 @@ private void Tokenize(string document, SemanticTokensBuilder builder) else { // ensure range gets some love - builder.Push(((line, index), (line, part.Length + index)), item.Type, item.Modifiers); + builder.Push(( ( line, index ), ( line, part.Length + index ) ), item.Type, item.Modifiers); } } } @@ -326,7 +363,10 @@ public NormalizedToken(string text, SemanticTokenType type, params SemanticToken Modifiers = modifiers; } - public bool Equals(string? other) => string.Equals(ToString(), other); + public bool Equals(string? other) + { + return string.Equals(ToString(), other); + } public bool Equals(NormalizedToken? other) { @@ -342,7 +382,10 @@ public override bool Equals(object? obj) return obj.GetType() == GetType() && Equals((NormalizedToken)obj); } - public override int GetHashCode() => HashCode.Combine(Text, Type, Modifiers); + public override int GetHashCode() + { + return HashCode.Combine(Text, Type, Modifiers); + } public override string ToString() { @@ -373,9 +416,15 @@ public static implicit operator NormalizedToken(string value) ); } - public static bool operator ==(NormalizedToken left, NormalizedToken right) => Equals(left, right); + public static bool operator ==(NormalizedToken left, NormalizedToken right) + { + return Equals(left, right); + } - public static bool operator !=(NormalizedToken left, NormalizedToken right) => !Equals(left, right); + public static bool operator !=(NormalizedToken left, NormalizedToken right) + { + return !Equals(left, right); + } public string Text { get; } public SemanticTokenType Type { get; } @@ -386,8 +435,8 @@ public static implicit operator NormalizedToken(string value) { var parts = Decompose(values).ToArray(); return parts - .Select((item, index) => GetNormalizedToken(document, parts, index)) - .Where(z => z != null) + .Select((item, index) => GetNormalizedToken(document, parts, index)!) + .Where(z => z != null!) .ToArray(); } @@ -432,7 +481,7 @@ IReadOnlyList values { for (var i = 0; i < values.Count; i += 5) { - yield return (values[i], values[i + 1], values[i + 2], values[i + 3], values[i + 4]); + yield return ( values[i], values[i + 1], values[i + 2], values[i + 3], values[i + 4] ); } } diff --git a/test/Lsp.Tests/SemanticTokensLegendTests.cs b/test/Lsp.Tests/SemanticTokensLegendTests.cs index 48f962c46..8d376399d 100644 --- a/test/Lsp.Tests/SemanticTokensLegendTests.cs +++ b/test/Lsp.Tests/SemanticTokensLegendTests.cs @@ -2,7 +2,6 @@ using FluentAssertions; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using Xunit; @@ -16,30 +15,34 @@ public void CustomBehavior_When_SymbolKind_Defined_By_Client() { var serializer = new LspSerializer(); serializer.SetClientCapabilities( - new ClientCapabilities { - TextDocument = new TextDocumentClientCapabilities { - SemanticTokens = new SemanticTokensCapability() { + new ClientCapabilities + { + TextDocument = new TextDocumentClientCapabilities + { + SemanticTokens = new SemanticTokensCapability + { DynamicRegistration = true, Formats = new Container(SemanticTokenFormat.Relative), MultilineTokenSupport = true, OverlappingTokenSupport = true, TokenModifiers = new Container(SemanticTokenModifier.Deprecated), TokenTypes = new Container(SemanticTokenType.Comment), - Requests = new SemanticTokensCapabilityRequests() { - Full = new SemanticTokensCapabilityRequestFull() { + Requests = new SemanticTokensCapabilityRequests + { + Full = new SemanticTokensCapabilityRequestFull + { Delta = true }, - Range = new SemanticTokensCapabilityRequestRange() { - } + Range = new SemanticTokensCapabilityRequestRange() } }, - } } ); var json = serializer.SerializeObject( - new SemanticTokensLegend { + new SemanticTokensLegend + { TokenModifiers = new Container(SemanticTokenModifier.Deprecated), TokenTypes = new Container(SemanticTokenType.Comment), } @@ -55,12 +58,16 @@ public void CustomBehavior_When_SymbolKind_Defined_By_Server() { var serializer = new LspSerializer(); serializer.SetServerCapabilities( - new ServerCapabilities { - SemanticTokensProvider = new SemanticTokensRegistrationOptions.StaticOptions() { - Full = new SemanticTokensCapabilityRequestFull { + new ServerCapabilities + { + SemanticTokensProvider = new SemanticTokensRegistrationOptions.StaticOptions + { + Full = new SemanticTokensCapabilityRequestFull + { Delta = true }, - Legend = new SemanticTokensLegend { + Legend = new SemanticTokensLegend + { TokenModifiers = new Container(SemanticTokenModifier.Deprecated), TokenTypes = new Container(SemanticTokenType.Comment), }, @@ -70,7 +77,8 @@ public void CustomBehavior_When_SymbolKind_Defined_By_Server() ); var json = serializer.SerializeObject( - new SemanticTokensLegend { + new SemanticTokensLegend + { TokenModifiers = new Container(SemanticTokenModifier.Deprecated), TokenTypes = new Container(SemanticTokenType.Comment), } diff --git a/test/Lsp.Tests/SupportedCapabilitiesFixture.cs b/test/Lsp.Tests/SupportedCapabilitiesFixture.cs index 030681472..1df0e5a83 100644 --- a/test/Lsp.Tests/SupportedCapabilitiesFixture.cs +++ b/test/Lsp.Tests/SupportedCapabilitiesFixture.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; using OmniSharp.Extensions.LanguageServer.Shared; @@ -18,9 +14,15 @@ private class AlwaysTrueSupportedCapabilities : SupportedCapabilitiesBase, ISupp { // ReSharper disable once UnusedParameter.Local // ReSharper disable once UnusedMember.Local - public bool AllowsDynamicRegistration(ILspHandlerDescriptor descriptor) => true; + public bool AllowsDynamicRegistration(ILspHandlerDescriptor descriptor) + { + return true; + } - public bool AllowsDynamicRegistration(Type capabilityType) => true; + public bool AllowsDynamicRegistration(Type capabilityType) + { + return true; + } protected override bool TryGetCapability(Type capabilityType, [NotNullWhen(true)] out object? capability) { @@ -33,9 +35,15 @@ private class AlwaysFalseSupportedCapabilities : SupportedCapabilitiesBase, ISup { // ReSharper disable once UnusedParameter.Local // ReSharper disable once UnusedMember.Local - public bool AllowsDynamicRegistration(ILspHandlerDescriptor descriptor) => false; + public bool AllowsDynamicRegistration(ILspHandlerDescriptor descriptor) + { + return false; + } - public bool AllowsDynamicRegistration(Type capabilityType) => false; + public bool AllowsDynamicRegistration(Type capabilityType) + { + return false; + } protected override bool TryGetCapability(Type capabilityType, [NotNullWhen(true)] out object? capability) { diff --git a/test/TestingUtils/AutoNSubstitute/TestLogger.cs b/test/TestingUtils/AutoNSubstitute/TestLogger.cs index bf9a8f3dc..e974b4405 100644 --- a/test/TestingUtils/AutoNSubstitute/TestLogger.cs +++ b/test/TestingUtils/AutoNSubstitute/TestLogger.cs @@ -2,13 +2,12 @@ using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; -using Castle.DynamicProxy.Contributors; using Microsoft.Extensions.Logging; // ReSharper disable once CheckNamespace namespace NSubstitute { - class TestLogger : ILogger + internal class TestLogger : ILogger { private readonly IEnumerable _loggers; diff --git a/test/TestingUtils/AutoNSubstitute/TestLoggerFactory.cs b/test/TestingUtils/AutoNSubstitute/TestLoggerFactory.cs index efc57e822..4840f5393 100644 --- a/test/TestingUtils/AutoNSubstitute/TestLoggerFactory.cs +++ b/test/TestingUtils/AutoNSubstitute/TestLoggerFactory.cs @@ -4,7 +4,6 @@ using System.Reactive.Subjects; using System.Threading; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions.Internal; using Serilog; using Serilog.Events; using Serilog.Extensions.Logging; @@ -42,7 +41,7 @@ public TestLoggerFactory( ILogger ILoggerFactory.CreateLogger(string categoryName) { return _additionalLoggerProviders.Count > 0 - ? new TestLogger(new [] { _loggerProvider }.Concat(_additionalLoggerProviders).Select(z => z.CreateLogger(categoryName))) + ? new TestLogger(new[] { _loggerProvider }.Concat(_additionalLoggerProviders).Select(z => z.CreateLogger(categoryName))) : _loggerProvider.CreateLogger(categoryName); } @@ -75,11 +74,20 @@ public void Swap(ITestOutputHelper testOutputHelper) Interlocked.Exchange(ref _testOutputHelper, testOutputHelper); } - public void WriteLine(string message) => _testOutputHelper?.WriteLine(message); + public void WriteLine(string message) + { + _testOutputHelper?.WriteLine(message); + } - public void WriteLine(string format, params object[] args) => _testOutputHelper?.WriteLine(format, args); + public void WriteLine(string format, params object[] args) + { + _testOutputHelper?.WriteLine(format, args); + } } - public IDisposable Subscribe(IObserver observer) => _subject.Subscribe(observer); + public IDisposable Subscribe(IObserver observer) + { + return _subject.Subscribe(observer); + } } } diff --git a/test/TestingUtils/FactWithSkipOnAttribute.cs b/test/TestingUtils/FactWithSkipOnAttribute.cs index ba1122eca..212dfd786 100644 --- a/test/TestingUtils/FactWithSkipOnAttribute.cs +++ b/test/TestingUtils/FactWithSkipOnAttribute.cs @@ -1,5 +1,4 @@ -using System.Collections; -using System.Linq; +using System.Linq; using Xunit; namespace TestingUtils diff --git a/test/TestingUtils/RetryTheoryAttribute.cs b/test/TestingUtils/RetryTheoryAttribute.cs index c8181eafa..bbd11ebef 100644 --- a/test/TestingUtils/RetryTheoryAttribute.cs +++ b/test/TestingUtils/RetryTheoryAttribute.cs @@ -1,8 +1,6 @@ // See https://github.com/JoshKeegan/xRetry using System; -using System.Linq; -using System.Reflection; using Xunit.Sdk; namespace TestingUtils @@ -15,7 +13,11 @@ namespace TestingUtils [AttributeUsage(AttributeTargets.Method)] public class RetryTheoryAttribute : RetryFactAttribute { - /// - public RetryTheoryAttribute(int maxRetries = 3, int delayBetweenRetriesMs = 0, params SkipOnPlatform[] skipOn) : base(maxRetries, delayBetweenRetriesMs, skipOn) { } + /// + public RetryTheoryAttribute(int maxRetries = 3, int delayBetweenRetriesMs = 0, params SkipOnPlatform[] skipOn) : base( + maxRetries, delayBetweenRetriesMs, skipOn + ) + { + } } }