diff --git a/.azure-pipelines.yml b/.azure-pipelines.yml index fbef5d6f1..2854ab770 100644 --- a/.azure-pipelines.yml +++ b/.azure-pipelines.yml @@ -30,7 +30,7 @@ resources: - repository: rsg type: github name: RocketSurgeonsGuild/AzureDevopsTemplates - ref: refs/tags/v0.13.0 + ref: refs/tags/v0.13.1 endpoint: github variables: @@ -63,9 +63,9 @@ jobs: Linux: BuildName: 'Linux' ImageName: 'ubuntu-latest' - macOS: - BuildName: 'macOS' - ImageName: 'macOS-latest' + # macOS: + # BuildName: 'macOS' + # ImageName: 'macOS-latest' pool: vmImage: $(ImageName) steps: diff --git a/.build/.build.csproj b/.build/.build.csproj index b3e4dba53..509faac59 100644 --- a/.build/.build.csproj +++ b/.build/.build.csproj @@ -2,18 +2,18 @@ Exe - net5.0 + net6.0 false False CS0649;CS0169 + 1 - diff --git a/.build/Build.cs b/.build/Build.cs index 836d1713f..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] @@ -28,8 +27,7 @@ public partial class Solution : NukeBuild, IGenerateCodeCoverageReport, IGenerateCodeCoverageSummary, IGenerateCodeCoverageBadges, - IHaveConfiguration, - ICanLint + IHaveConfiguration { /// /// Support plugins are available for: @@ -38,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/.build/Solution.cs b/.build/Solution.cs index 47f084d9a..15cf58c19 100644 --- a/.build/Solution.cs +++ b/.build/Solution.cs @@ -1,90 +1,160 @@ using System.Collections.Generic; using System.Linq; using Nuke.Common.CI.GitHubActions; -using Rocket.Surgery.Nuke; +using Nuke.Common.CI.GitHubActions.Configuration; using Rocket.Surgery.Nuke.ContinuousIntegration; using Rocket.Surgery.Nuke.DotNetCore; using Rocket.Surgery.Nuke.GithubActions; -[AzurePipelinesSteps( + +internal class LocalConstants +{ + public static string[] PathsIgnore = + { + ".codecov.yml", + ".editorconfig", + ".gitattributes", + ".gitignore", + ".gitmodules", + ".lintstagedrc.js", + ".prettierignore", + ".prettierrc", + "LICENSE", + "nukeeper.settings.json", + "omnisharp.json", + "package-lock.json", + "package.json", + "Readme.md", + ".github/dependabot.yml", + ".github/labels.yml", + ".github/release.yml", + ".github/renovate.json", + }; +} + +[GitHubActionsSteps( + "ci-ignore", + GitHubActionsImage.WindowsLatest, + GitHubActionsImage.UbuntuLatest, AutoGenerate = false, - InvokeTargets = new[] { nameof(Default) }, - NonEntryTargets = new[] { - nameof(ICIEnvironment.CIEnvironment), - nameof(ITriggerCodeCoverageReports.Trigger_Code_Coverage_Reports), - nameof(ITriggerCodeCoverageReports.Generate_Code_Coverage_Report_Cobertura), - nameof(IGenerateCodeCoverageBadges.Generate_Code_Coverage_Badges), - nameof(IGenerateCodeCoverageReport.Generate_Code_Coverage_Report), - nameof(IGenerateCodeCoverageSummary.Generate_Code_Coverage_Summary), - nameof(Default) - }, - ExcludedTargets = new[] - { nameof(ICanClean.Clean), nameof(ICanRestoreWithDotNetCore.Restore), nameof(ICanRestoreWithDotNetCore.DotnetToolRestore) }, - Parameters = new[] { - nameof(IHaveCodeCoverage.CoverageDirectory), nameof(IHaveOutputArtifacts.ArtifactsDirectory), nameof(Verbosity), - nameof(IHaveConfiguration.Configuration) - } + On = new[] { GitHubActionsTrigger.Push }, + OnPushTags = new[] { "v*" }, + OnPushBranches = new[] { "master", "main", "next" }, + OnPullRequestBranches = new[] { "master", "main", "next" }, + Enhancements = new[] { nameof(CiIgnoreMiddleware) } )] [GitHubActionsSteps( - "ci", GitHubActionsImage.MacOsLatest, GitHubActionsImage.WindowsLatest, GitHubActionsImage.UbuntuLatest, + "ci", + GitHubActionsImage.MacOsLatest, + GitHubActionsImage.WindowsLatest, + GitHubActionsImage.UbuntuLatest, AutoGenerate = false, On = new[] { GitHubActionsTrigger.Push }, OnPushTags = new[] { "v*" }, - OnPushBranches = new[] { "master", "next" }, - OnPullRequestBranches = new[] { "master", "next" }, + OnPushBranches = new[] { "master", "main", "next" }, + OnPullRequestBranches = new[] { "master", "main", "next" }, InvokedTargets = new[] { nameof(Default) }, - NonEntryTargets = new[] { + NonEntryTargets = new[] + { nameof(ICIEnvironment.CIEnvironment), - nameof(ITriggerCodeCoverageReports.Trigger_Code_Coverage_Reports), - nameof(ITriggerCodeCoverageReports.Generate_Code_Coverage_Report_Cobertura), - nameof(IGenerateCodeCoverageBadges.Generate_Code_Coverage_Badges), - nameof(IGenerateCodeCoverageReport.Generate_Code_Coverage_Report), - nameof(IGenerateCodeCoverageSummary.Generate_Code_Coverage_Summary), + nameof(ITriggerCodeCoverageReports.TriggerCodeCoverageReports), + nameof(ITriggerCodeCoverageReports.GenerateCodeCoverageReportCobertura), + nameof(IGenerateCodeCoverageBadges.GenerateCodeCoverageBadges), + nameof(IGenerateCodeCoverageReport.GenerateCodeCoverageReport), + nameof(IGenerateCodeCoverageSummary.GenerateCodeCoverageSummary), nameof(Default) }, ExcludedTargets = new[] { nameof(ICanClean.Clean), nameof(ICanRestoreWithDotNetCore.DotnetToolRestore) }, - Enhancements = new[] { nameof(Middleware) } + Enhancements = new[] { nameof(CiMiddleware) } )] [PrintBuildVersion] [PrintCIEnvironment] [UploadLogs] +[TitleEvents] public partial class Solution { - public static RocketSurgeonGitHubActionsConfiguration Middleware(RocketSurgeonGitHubActionsConfiguration configuration) + public static RocketSurgeonGitHubActionsConfiguration CiIgnoreMiddleware( + RocketSurgeonGitHubActionsConfiguration configuration + ) + { + foreach (var item in configuration.DetailedTriggers.OfType()) + { + item.IncludePaths = LocalConstants.PathsIgnore; + } + + configuration.Jobs.RemoveAt(1); + ( (RocketSurgeonsGithubActionsJob)configuration.Jobs[0] ).Steps = new List + { + new RunStep("N/A") + { + Run = "echo \"No build required\"" + } + }; + + return configuration; + } + + public static RocketSurgeonGitHubActionsConfiguration CiMiddleware( + RocketSurgeonGitHubActionsConfiguration configuration + ) { - var buildJob = configuration.Jobs.First(z => z.Name == "Build"); + foreach (var item in configuration.DetailedTriggers.OfType()) + { + item.ExcludePaths = LocalConstants.PathsIgnore; + } + + var buildJob = configuration.Jobs.OfType().First(z => z.Name == "Build"); + buildJob.FailFast = false; var checkoutStep = buildJob.Steps.OfType().Single(); // For fetch all checkoutStep.FetchDepth = 0; + buildJob.Environment["NUGET_PACKAGES"] = "${{ github.workspace }}/.nuget/packages"; buildJob.Steps.InsertRange( - buildJob.Steps.IndexOf(checkoutStep) + 1, new BaseGitHubActionsStep[] { - new RunStep("Fetch all history for all tags and branches") { + buildJob.Steps.IndexOf(checkoutStep) + 1, + new BaseGitHubActionsStep[] + { + new RunStep("Fetch all history for all tags and branches") + { Run = "git fetch --prune" }, - new SetupDotNetStep("Use .NET Core 2.1 SDK") { - DotNetVersion = "2.1.x" + new UsingStep("NuGet Cache") + { + Uses = "actions/cache@v2", + With = + { + ["path"] = "${{ github.workspace }}/.nuget/packages", + // keep in mind using central package versioning here + ["key"] = + "${{ runner.os }}-nuget-${{ hashFiles('**/Directory.Packages.props') }}-${{ hashFiles('**/Directory.Packages.support.props') }}", + ["restore-keys"] = @"| + ${{ runner.os }}-nuget-" + } }, - new SetupDotNetStep("Use .NET Core 3.1 SDK") { + new SetupDotNetStep("Use .NET Core 3.1 SDK") + { DotNetVersion = "3.1.x" }, - new SetupDotNetStep("Use .NET Core 5.0 SDK") { - DotNetVersion = "5.0.x" + new SetupDotNetStep("Use .NET Core 6.0 SDK") + { + DotNetVersion = "6.0.x" }, } ); buildJob.Steps.Add( - new UsingStep("Publish Coverage") { + new UsingStep("Publish Coverage") + { Uses = "codecov/codecov-action@v1", - With = new Dictionary { + With = new Dictionary + { ["name"] = "actions-${{ matrix.os }}", - ["fail_ci_if_error"] = "true", } } ); buildJob.Steps.Add( - new UploadArtifactStep("Publish logs") { + new UploadArtifactStep("Publish logs") + { Name = "logs", Path = "artifacts/logs/", If = "always()" @@ -92,7 +162,8 @@ public static RocketSurgeonGitHubActionsConfiguration Middleware(RocketSurgeonGi ); buildJob.Steps.Add( - new UploadArtifactStep("Publish coverage data") { + new UploadArtifactStep("Publish coverage data") + { Name = "coverage", Path = "coverage/", If = "always()" @@ -100,7 +171,8 @@ public static RocketSurgeonGitHubActionsConfiguration Middleware(RocketSurgeonGi ); buildJob.Steps.Add( - new UploadArtifactStep("Publish test data") { + new UploadArtifactStep("Publish test data") + { Name = "test data", Path = "artifacts/test/", If = "always()" @@ -108,31 +180,23 @@ public static RocketSurgeonGitHubActionsConfiguration Middleware(RocketSurgeonGi ); buildJob.Steps.Add( - new UploadArtifactStep("Publish NuGet Packages") { + new UploadArtifactStep("Publish NuGet Packages") + { Name = "nuget", Path = "artifacts/nuget/", If = "always()" } ); + buildJob.Steps.Add( + new UploadArtifactStep("Publish Docs") + { + Name = "docs", + Path = "artifacts/docs/", + If = "always()" + } + ); - /* - - - publish: "${{ parameters.Artifacts }}/logs/" - displayName: Publish Logs - artifact: "Logs${{ parameters.Postfix }}" - condition: always() - - - publish: ${{ parameters.Coverage }} - displayName: Publish Coverage - artifact: "Coverage${{ parameters.Postfix }}" - condition: always() - - - publish: "${{ parameters.Artifacts }}/nuget/" - displayName: Publish NuGet Artifacts - artifact: "NuGet${{ parameters.Postfix }}" - condition: always() - */ return configuration; } } diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 19029998d..e1a1594e1 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -1,48 +1,54 @@ { - "version": 1, - "isRoot": true, - "tools": { - "cake.tool": { - "version": "1.1.0", - "commands": [ - "dotnet-cake" - ] - }, - "gitversion.tool": { - "version": "5.7.0", - "commands": [ - "dotnet-gitversion" - ] - }, - "dotnet-reportgenerator-globaltool": { - "version": "4.8.12", - "commands": [ - "reportgenerator" - ] - }, - "codecov.tool": { - "version": "1.13.0", - "commands": [ - "codecov" - ] - }, - "nuke.globaltool": { - "version": "5.3.0", - "commands": [ - "nuke" - ] - }, - "nukeeper": { - "version": "0.34.0", - "commands": [ - "nukeeper" - ] - }, - "jetbrains.resharper.globaltools": { - "version": "2021.2.1", - "commands": [ - "jb" - ] + "version": 1, + "isRoot": true, + "tools": { + "dotnet-outdated": { + "version": "2.11.0", + "commands": [ + "dotnet-outdated" + ] + }, + "gitversion.tool": { + "version": "5.10.1", + "commands": [ + "dotnet-gitversion" + ] + }, + "dotnet-reportgenerator-globaltool": { + "version": "5.1.6", + "commands": [ + "reportgenerator" + ] + }, + "nuke.globaltool": { + "version": "6.0.3", + "commands": [ + "nuke" + ] + }, + "codecov.tool": { + "version": "1.13.0", + "commands": [ + "codecov" + ] + }, + "jetbrains.resharper.globaltools": { + "version": "2022.1.1", + "commands": [ + "jb" + ] + }, + "dotnet-format": { + "version": "5.1.250801", + "commands": [ + "dotnet-format" + ] + }, + "nukeeper": { + "version": "0.35.0", + "commands": [ + "nukeeper" + ] + } } - } -} \ No newline at end of file +} diff --git a/.editorconfig b/.editorconfig index 81d812533..bb7e8b5d2 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,168 +1,1045 @@ -root=true +root = true + +[*.{cs, cshtml}] +charset = utf-8 +indent_style = space +indent_size = 4 +max_line_length = 160 +insert_final_newline = true + +[*.{js, ts, vue}] +indent_style = space +indent_size = 4 +insert_final_newline = true +max_line_length = 160 + +[*.{json, xml, yml, yaml}] +indent_style = space +indent_size = 2 +insert_final_newline = true +max_line_length = 160 + [*] -charset=utf-8 -indent_style=space -indent_size=4 -trim_trailing_whitespace=true -insert_final_newline=true -max_line_length=180 -end_of_line=crlf +#### .NET Coding Conventions #### -# Microsoft .NET properties -csharp_new_line_before_members_in_object_initializers=false -csharp_new_line_before_open_brace=types,methods,properties,indexers,events,event_accessors,control_blocks,anonymous_types,object_collections,array_initializers,local_functions -csharp_preferred_modifier_order=public, private, protected, internal, new, abstract, virtual, sealed, override, static, readonly, extern, unsafe, volatile, async:suggestion -csharp_space_between_parentheses=expressions -csharp_style_expression_bodied_accessors=true:suggestion -csharp_style_expression_bodied_constructors=true:none -csharp_style_expression_bodied_indexers=true:none -csharp_style_expression_bodied_methods=true:none -csharp_style_expression_bodied_operators=true:none -csharp_style_expression_bodied_properties=true:suggestion -csharp_style_var_elsewhere=true:warning -csharp_style_var_for_built_in_types=true:warning -csharp_style_var_when_type_is_apparent=true:warning -dotnet_style_parentheses_in_arithmetic_binary_operators=never_if_unnecessary:warning -dotnet_style_parentheses_in_other_binary_operators=never_if_unnecessary:warning -dotnet_style_parentheses_in_relational_binary_operators=never_if_unnecessary:warning -dotnet_style_predefined_type_for_locals_parameters_members=true:error -dotnet_style_predefined_type_for_member_access=true:error -dotnet_style_qualification_for_event=false:warning -dotnet_style_qualification_for_field=false:warning -dotnet_style_qualification_for_method=false:warning -dotnet_style_qualification_for_property=false:warning -dotnet_style_require_accessibility_modifiers=for_non_interface_members:suggestion -# Sort using and Import directives with System.* appearing first -dotnet_sort_system_directives_first=true -# Suggest more modern language features when available -dotnet_style_coalesce_expression=true:error -dotnet_style_collection_initializer=true:suggestion -dotnet_style_explicit_tuple_names=true:error -dotnet_style_null_propagation=true:warning -dotnet_style_object_initializer=true:warning - -# Naming Conventions: -# Pascal Casing -#dotnet_naming_symbols.method_and_property_symbols.applicable_kinds= method,property,enum -#dotnet_naming_symbols.method_and_property_symbols.applicable_accessibilities = * -#dotnet_naming_style.pascal_case_style.capitalization = pascal_case -csharp_style_conditional_delegate_call=true:suggestion -csharp_style_inlined_variable_declaration=true:error -csharp_style_pattern_matching_over_as_with_null_check=true:error -csharp_style_pattern_matching_over_is_with_cast_check=true:error -csharp_style_throw_expression=true:suggestion -csharp_new_line_before_catch=true -csharp_new_line_before_else=true -csharp_new_line_before_finally=true -csharp_new_line_before_members_in_anonymous_types=true +# Organize usings +dotnet_separate_import_directive_groups = false +dotnet_sort_system_directives_first = true + +# this. and Me. preferences +dotnet_style_qualification_for_event = false:warning +dotnet_style_qualification_for_field = false:warning +dotnet_style_qualification_for_method = false:warning +dotnet_style_qualification_for_property = false:warning + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:warning +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:warning +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:warning +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:warning + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members:suggestion + +# Expression-level preferences +csharp_style_deconstructed_variable_declaration = true:warning +csharp_style_inlined_variable_declaration = true:warning +csharp_style_throw_expression = true:warning +dotnet_style_coalesce_expression = true:warning +dotnet_style_collection_initializer = true:warning +dotnet_style_explicit_tuple_names = true:warning +dotnet_style_null_propagation = true:warning +dotnet_style_object_initializer = true:warning +dotnet_style_prefer_auto_properties = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_return = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning +dotnet_style_prefer_inferred_tuple_names = true:warning +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning + +# Field preferences +dotnet_style_readonly_field = true:warning + +# Parameter preferences +dotnet_code_quality_unused_parameters = non_public:suggestion + +#### C# Coding Conventions #### + +# var preferences +csharp_style_var_elsewhere = true:suggestion +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion + +# Expression-bodied members +csharp_style_expression_bodied_accessors = true:suggestion +csharp_style_expression_bodied_constructors = true:suggestion +csharp_style_expression_bodied_indexers = true:suggestion +csharp_style_expression_bodied_lambdas = true:suggestion +csharp_style_expression_bodied_local_functions = true:suggestion +csharp_style_expression_bodied_methods = true:suggestion +csharp_style_expression_bodied_operators = true:suggestion +csharp_style_expression_bodied_properties = true:suggestion + +# Pattern matching preferences +csharp_style_pattern_matching_over_as_with_null_check = true:warning +csharp_style_pattern_matching_over_is_with_cast_check = true:warning +csharp_style_prefer_switch_expression = true:warning + +# Null-checking preferences +csharp_style_conditional_delegate_call = true:warning + +# Modifier preferences +csharp_prefer_static_local_function = true:warning +csharp_preferred_modifier_order = public, private, protected, internal, new, abstract, virtual, sealed, static, readonly, override, extern, unsafe, volatile, async:suggestion + +# Code-block preferences +csharp_prefer_braces = true:none +csharp_prefer_simple_using_statement = true:suggestion + +# Expression-level preferences +csharp_prefer_simple_default_expression = true:warning +csharp_style_pattern_local_over_anonymous_function = true:warning +csharp_style_prefer_index_operator = true:warning +csharp_style_prefer_range_operator = true:warning +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +csharp_style_unused_value_expression_statement_preference = discard_variable:suggestion + +# 'using' directive preferences + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_catch = true +csharp_new_line_before_else = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = false +csharp_new_line_before_open_brace = all +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = no_change +csharp_indent_switch_labels = true + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = expressions +csharp_space_between_square_brackets = false + +# Wrapping preferences +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true + +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.type_parameter_should_be_begins_with_t.severity = suggestion +dotnet_naming_rule.type_parameter_should_be_begins_with_t.symbols = type_parameter +dotnet_naming_rule.type_parameter_should_be_begins_with_t.style = begins_with_t + +dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion +dotnet_naming_rule.locals_should_be_camel_case.symbols = local +dotnet_naming_rule.locals_should_be_camel_case.style = camel_case + +dotnet_naming_rule.static_field_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.static_field_should_be_pascal_case.symbols = static_field +dotnet_naming_rule.static_field_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.const_field_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.const_field_should_be_pascal_case.symbols = const_field +dotnet_naming_rule.const_field_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.private_field_members_should_be_underscore_camel_case.severity = suggestion +dotnet_naming_rule.private_field_members_should_be_underscore_camel_case.symbols = private_field +dotnet_naming_rule.private_field_members_should_be_underscore_camel_case.style = _camel_case + +dotnet_naming_rule.field_should_be_camel_case.severity = suggestion +dotnet_naming_rule.field_should_be_camel_case.symbols = field +dotnet_naming_rule.field_should_be_camel_case.style = camel_case + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = * +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.local.applicable_kinds = local, local_function +dotnet_naming_symbols.local.applicable_accessibilities = * +dotnet_naming_symbols.local.required_modifiers = +dotnet_naming_symbols.type_parameter.applicable_kinds = type_parameter +dotnet_naming_symbols.type_parameter.applicable_accessibilities = * +dotnet_naming_symbols.type_parameter.required_modifiers = +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum, delegate +dotnet_naming_symbols.types.applicable_accessibilities = * +dotnet_naming_symbols.types.required_modifiers = +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = * +dotnet_naming_symbols.non_field_members.required_modifiers = +dotnet_naming_symbols.private_field.applicable_kinds = field +dotnet_naming_symbols.private_field.applicable_accessibilities = private, private_protected +dotnet_naming_symbols.private_field.required_modifiers = +dotnet_naming_symbols.field.applicable_kinds = field +dotnet_naming_symbols.field.applicable_accessibilities = public, protected, internal, protected_internal, private_protected +dotnet_naming_symbols.field.required_modifiers = +dotnet_naming_symbols.static_field.applicable_kinds = field +dotnet_naming_symbols.static_field.applicable_accessibilities = +dotnet_naming_symbols.static_field.required_modifiers = static + +dotnet_naming_symbols.const_field.applicable_kinds = field +dotnet_naming_symbols.const_field.applicable_accessibilities = * +dotnet_naming_symbols.const_field.required_modifiers = const + +# Naming styles + +# dotnet_naming_style.pascal_case.required_prefix = +# dotnet_naming_style.pascal_case.required_suffix = +# dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +# dotnet_naming_style.camel_case.required_prefix = +# dotnet_naming_style.camel_case.required_suffix = +# dotnet_naming_style.camel_case.word_separator = +dotnet_naming_style.camel_case.capitalization = camel_case + +dotnet_naming_style._camel_case.required_prefix = _ +# dotnet_naming_style._camel_case.required_suffix = +# dotnet_naming_style._camel_case.word_separator = +dotnet_naming_style._camel_case.capitalization = camel_case + +dotnet_naming_style.begins_with_i.required_prefix = I +# dotnet_naming_style.begins_with_i.required_suffix = +# dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +dotnet_naming_style.begins_with_t.required_prefix = T +# dotnet_naming_style.begins_with_t.required_suffix = +# dotnet_naming_style.begins_with_t.word_separator = +dotnet_naming_style.begins_with_t.capitalization = pascal_case + +dotnet_diagnostic.ide0058.severity = none + +# CodeQuality +# CA1000: Do not declare static members on generic types +# dotnet_diagnostic.CA1000.severity = warning + +# CA1001: Types that own disposable fields should be disposable +# dotnet_diagnostic.CA1001.severity = warning + +# CA1003: Use generic event handler instances +# dotnet_diagnostic.CA1003.severity = none + +# CA1008: Enums should have zero value +# dotnet_diagnostic.CA1008.severity = none + +# CA1010: Collections should implement generic interface +# dotnet_diagnostic.CA1010.severity = warning + +# CA1012: Abstract types should not have constructors +# dotnet_diagnostic.CA1012.severity = none + +# CA1014: Mark assemblies with CLSCompliant +# dotnet_diagnostic.CA1014.severity = none + +# CA1016: Mark assemblies with assembly version +# dotnet_diagnostic.CA1016.severity = warning + +# CA1017: Mark assemblies with ComVisible +# dotnet_diagnostic.CA1017.severity = none + +# CA1018: Mark attributes with AttributeUsageAttribute +# dotnet_diagnostic.CA1018.severity = warning + +# CA1019: Define accessors for attribute arguments +# dotnet_diagnostic.CA1019.severity = none + +# CA1024: Use properties where appropriate +# dotnet_diagnostic.CA1024.severity = none + +# CA1027: Mark enums with FlagsAttribute +# dotnet_diagnostic.CA1027.severity = none + +# CA1028: Enum Storage should be Int32 +# dotnet_diagnostic.CA1028.severity = warning + +# CA1030: Use events where appropriate +# dotnet_diagnostic.CA1030.severity = warning + +# CA1031: Do not catch general exception types +# dotnet_diagnostic.CA1031.severity = warning + +# CA1032: Implement standard exception constructors +# dotnet_diagnostic.CA1032.severity = warning + +# CA1033: Interface methods should be callable by child types +# dotnet_diagnostic.CA1033.severity = none + +# CA1034: Nested types should not be visible +# dotnet_diagnostic.CA1034.severity = warning + +# CA1036: Override methods on comparable types +# dotnet_diagnostic.CA1036.severity = warning + +# CA1040: Avoid empty interfaces +# dotnet_diagnostic.CA1040.severity = warning + +# CA1041: Provide ObsoleteAttribute message +# dotnet_diagnostic.CA1041.severity = warning + +# CA1043: Use Integral Or String Argument For Indexers +# dotnet_diagnostic.CA1043.severity = warning + +# CA1044: Properties should not be write only +# dotnet_diagnostic.CA1044.severity = warning + +# CA1050: Declare types in namespaces +# dotnet_diagnostic.CA1050.severity = none + +# CA1051: Do not declare visible instance fields +# dotnet_diagnostic.CA1051.severity = warning + +# CA1052: Static holder types should be Static or NotInheritable +# dotnet_diagnostic.CA1052.severity = warning + +# CA1054: Uri parameters should not be strings +# dotnet_diagnostic.CA1054.severity = warning + +# CA1055: Uri return values should not be strings +# dotnet_diagnostic.CA1055.severity = warning + +# CA1056: Uri properties should not be strings +# dotnet_diagnostic.CA1056.severity = warning + +# CA1060: Move pinvokes to native methods class +# dotnet_diagnostic.CA1060.severity = none + +# CA1061: Do not hide base class methods +# dotnet_diagnostic.CA1061.severity = warning + +# CA1062: Validate arguments of public methods +dotnet_diagnostic.ca1062.severity = none + +# CA1063: Implement IDisposable Correctly +# dotnet_diagnostic.CA1063.severity = none + +# CA1064: Exceptions should be public +# dotnet_diagnostic.CA1064.severity = warning + +# CA1065: Do not raise exceptions in unexpected locations +# dotnet_diagnostic.CA1065.severity = warning + +# CA1066: Type {0} should implement IEquatable because it overrides Equals +# dotnet_diagnostic.CA1066.severity = warning + +# CA1067: Override Object.Equals(object) when implementing IEquatable +# dotnet_diagnostic.CA1067.severity = warning + +# CA1068: CancellationToken parameters must come last +# dotnet_diagnostic.CA1068.severity = warning + +# CA1200: Avoid using cref tags with a prefix +# dotnet_diagnostic.CA1200.severity = warning + +# CA1501: Avoid excessive inheritance +# dotnet_diagnostic.CA1501.severity = none + +# CA1502: Avoid excessive complexity +# dotnet_diagnostic.CA1502.severity = none + +# CA1505: Avoid unmaintainable code +# dotnet_diagnostic.CA1505.severity = none + +# CA1506: Avoid excessive class coupling +# dotnet_diagnostic.CA1506.severity = none + +# CA1507: Use nameof to express symbol names +# dotnet_diagnostic.CA1507.severity = warning + +# CA1508: Avoid dead conditional code +# dotnet_diagnostic.CA1508.severity = none + +# CA1509: Invalid entry in code metrics rule specification file +# dotnet_diagnostic.CA1509.severity = none + +# CA1707: Identifiers should not contain underscores +# dotnet_diagnostic.CA1707.severity = none + +# CA1708: Identifiers should differ by more than case +# dotnet_diagnostic.CA1708.severity = none + +# CA1710: Identifiers should have correct suffix +# dotnet_diagnostic.CA1710.severity = warning + +# CA1711: Identifiers should not have incorrect suffix +# dotnet_diagnostic.CA1711.severity = none + +# CA1712: Do not prefix enum values with type name +# dotnet_diagnostic.CA1712.severity = warning + +# CA1714: Flags enums should have plural names +# dotnet_diagnostic.CA1714.severity = warning + +# CA1715: Identifiers should have correct prefix +# dotnet_diagnostic.CA1715.severity = warning + +# CA1716: Identifiers should not match keywords +# dotnet_diagnostic.CA1716.severity = warning + +# CA1717: Only FlagsAttribute enums should have plural names +# dotnet_diagnostic.CA1717.severity = warning + +# CA1720: Identifier contains type name +# dotnet_diagnostic.CA1720.severity = warning + +# CA1721: Property names should not match get methods +# dotnet_diagnostic.CA1721.severity = warning + +# CA1724: Type names should not match namespaces +# dotnet_diagnostic.CA1724.severity = warning + +# CA1725: Parameter names should match base declaration +# dotnet_diagnostic.CA1725.severity = none + +# CA1801: Review unused parameters +# dotnet_diagnostic.CA1801.severity = warning + +# CA1802: Use literals where appropriate +# dotnet_diagnostic.CA1802.severity = warning + +# CA1806: Do not ignore method results +# dotnet_diagnostic.CA1806.severity = warning + +# CA1812: Avoid uninstantiated internal classes +# dotnet_diagnostic.CA1812.severity = none + +# CA1814: Prefer jagged arrays over multidimensional +# dotnet_diagnostic.CA1814.severity = warning + +# CA1815: Override equals and operator equals on value types +# dotnet_diagnostic.CA1815.severity = warning + +# CA1819: Properties should not return arrays +# dotnet_diagnostic.CA1819.severity = warning + +# CA1821: Remove empty Finalizers +# dotnet_diagnostic.CA1821.severity = warning + +# CA1822: Mark members as static +# dotnet_diagnostic.CA1822.severity = warning + +# CA1823: Avoid unused private fields +# dotnet_diagnostic.CA1823.severity = warning + +# CA2007: Consider calling ConfigureAwait on the awaited task +dotnet_diagnostic.ca2007.severity = none + +# CA2119: Seal methods that satisfy private interfaces +# dotnet_diagnostic.CA2119.severity = warning + +# CA2200: Rethrow to preserve stack details. +# dotnet_diagnostic.CA2200.severity = warning + +# CA2211: Non-constant fields should not be visible +# dotnet_diagnostic.CA2211.severity = warning + +# CA2214: Do not call overridable methods in constructors +# dotnet_diagnostic.CA2214.severity = warning + +# CA2217: Do not mark enums with FlagsAttribute +# dotnet_diagnostic.CA2217.severity = none + +# CA2218: Override GetHashCode on overriding Equals +# dotnet_diagnostic.CA2218.severity = warning + +# CA2219: Do not raise exceptions in finally clauses +# dotnet_diagnostic.CA2219.severity = warning + +# CA2224: Override Equals on overloading operator equals +# dotnet_diagnostic.CA2224.severity = warning + +# CA2225: Operator overloads have named alternates +# dotnet_diagnostic.CA2225.severity = warning + +# CA2226: Operators should have symmetrical overloads +# dotnet_diagnostic.CA2226.severity = warning + +# CA2227: Collection properties should be read only +# dotnet_diagnostic.CA2227.severity = warning + +# CA2231: Overload operator equals on overriding value type Equals +# dotnet_diagnostic.CA2231.severity = warning + +# CA2234: Pass system uri objects instead of strings +# dotnet_diagnostic.CA2234.severity = warning + +# CA2244: Do not duplicate indexed element initializations +# dotnet_diagnostic.CA2244.severity = warning + +# CA2245: Do not assign a property to itself. +# dotnet_diagnostic.CA2245.severity = warning + +# CA2246: Assigning symbol and its member in the same statement. +# dotnet_diagnostic.CA2246.severity = warning + +# NetCore + +# CA1303: Do not pass literals as localized parameters +# dotnet_diagnostic.CA1303.severity = none + +# CA1304: Specify CultureInfo +# dotnet_diagnostic.CA1304.severity = none + +# CA1305: Specify IFormatProvider +# dotnet_diagnostic.CA1305.severity = none + +# CA1307: Specify StringComparison +# dotnet_diagnostic.CA1307.severity = warning + +# CA1308: Normalize strings to uppercase +# dotnet_diagnostic.CA1308.severity = warning + +# CA1309: Use ordinal stringcomparison +# dotnet_diagnostic.CA1309.severity = none + +# CA1401: P/Invokes should not be visible +# dotnet_diagnostic.CA1401.severity = warning + +# CA1810: Initialize reference type static fields inline +# dotnet_diagnostic.CA1810.severity = warning + +# CA1813: Avoid unsealed attributes +# dotnet_diagnostic.CA1813.severity = none + +# CA1816: Dispose methods should call SuppressFinalize +# dotnet_diagnostic.CA1816.severity = none + +# CA1820: Test for empty strings using string length +# dotnet_diagnostic.CA1820.severity = warning + +# CA1824: Mark assemblies with NeutralResourcesLanguageAttribute +# dotnet_diagnostic.CA1824.severity = warning + +# CA1825: Avoid zero-length array allocations. +# dotnet_diagnostic.CA1825.severity = warning + +# CA1826: Do not use Enumerable methods on indexable collections. Instead use the collection directly +# dotnet_diagnostic.CA1826.severity = warning + +# CA1827: Do not use Count() or LongCount() when Any() can be used +# dotnet_diagnostic.CA1827.severity = warning + +# CA1828: Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used +# dotnet_diagnostic.CA1828.severity = warning + +# CA1829: Use Length/Count property instead of Count() when available +# dotnet_diagnostic.CA1829.severity = warning + +# CA2000: Dispose objects before losing scope +# dotnet_diagnostic.CA2000.severity = warning + +# CA2002: Do not lock on objects with weak identity +# dotnet_diagnostic.CA2002.severity = warning + +# CA2008: Do not create tasks without passing a TaskScheduler +# dotnet_diagnostic.CA2008.severity = warning + +# CA2009: Do not call ToImmutableCollection on an ImmutableCollection value +# dotnet_diagnostic.CA2009.severity = warning + +# CA2010: Always consume the value returned by methods marked with PreserveSigAttribute +# dotnet_diagnostic.CA2010.severity = warning + +# CA2100: Review SQL queries for security vulnerabilities +# dotnet_diagnostic.CA2100.severity = warning + +# CA2101: Specify marshaling for P/Invoke string arguments +# dotnet_diagnostic.CA2101.severity = warning + +# CA2201: Do not raise reserved exception types +# dotnet_diagnostic.CA2201.severity = none + +# CA2207: Initialize value type static fields inline +# dotnet_diagnostic.CA2207.severity = warning + +# CA2208: Instantiate argument exceptions correctly +# dotnet_diagnostic.CA2208.severity = warning + +# CA2213: Disposable fields should be disposed +# dotnet_diagnostic.CA2213.severity = warning + +# CA2216: Disposable types should declare finalizer +# dotnet_diagnostic.CA2216.severity = warning + +# CA2229: Implement serialization constructors +# dotnet_diagnostic.CA2229.severity = warning + +# CA2235: Mark all non-serializable fields +# dotnet_diagnostic.CA2235.severity = warning + +# CA2237: Mark ISerializable types with serializable +# dotnet_diagnostic.CA2237.severity = warning + +# CA2241: Provide correct arguments to formatting methods +# dotnet_diagnostic.CA2241.severity = warning + +# CA2242: Test for NaN correctly +# dotnet_diagnostic.CA2242.severity = warning + +# CA2243: Attribute string literals should parse correctly +# dotnet_diagnostic.CA2243.severity = warning + +# CA2300: Do not use insecure deserializer BinaryFormatter +# dotnet_diagnostic.CA2300.severity = none + +# CA2301: Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder +# dotnet_diagnostic.CA2301.severity = none + +# CA2302: Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize +# dotnet_diagnostic.CA2302.severity = none + +# CA2305: Do not use insecure deserializer LosFormatter +# dotnet_diagnostic.CA2305.severity = none + +# CA2310: Do not use insecure deserializer NetDataContractSerializer +# dotnet_diagnostic.CA2310.severity = none + +# CA2311: Do not deserialize without first setting NetDataContractSerializer.Binder +# dotnet_diagnostic.CA2311.severity = none + +# CA2312: Ensure NetDataContractSerializer.Binder is set before deserializing +# dotnet_diagnostic.CA2312.severity = none + +# CA2315: Do not use insecure deserializer ObjectStateFormatter +# dotnet_diagnostic.CA2315.severity = none + +# CA2321: Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver +# dotnet_diagnostic.CA2321.severity = none + +# CA2322: Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing +# dotnet_diagnostic.CA2322.severity = none + +# CA2326: Do not use TypeNameHandling values other than None +# dotnet_diagnostic.CA2326.severity = none + +# CA2327: Do not use insecure JsonSerializerSettings +# dotnet_diagnostic.CA2327.severity = none + +# CA2328: Ensure that JsonSerializerSettings are secure +# dotnet_diagnostic.CA2328.severity = none + +# CA2329: Do not deserialize with JsonSerializer using an insecure configuration +# dotnet_diagnostic.CA2329.severity = none + +# CA2330: Ensure that JsonSerializer has a secure configuration when deserializing +# dotnet_diagnostic.CA2330.severity = none + +# CA3001: Review code for SQL injection vulnerabilities +# dotnet_diagnostic.CA3001.severity = none + +# CA3002: Review code for XSS vulnerabilities +# dotnet_diagnostic.CA3002.severity = none + +# CA3003: Review code for file path injection vulnerabilities +# dotnet_diagnostic.CA3003.severity = none + +# CA3004: Review code for information disclosure vulnerabilities +# dotnet_diagnostic.CA3004.severity = none + +# CA3005: Review code for LDAP injection vulnerabilities +# dotnet_diagnostic.CA3005.severity = none + +# CA3006: Review code for process command injection vulnerabilities +# dotnet_diagnostic.CA3006.severity = none + +# CA3007: Review code for open redirect vulnerabilities +# dotnet_diagnostic.CA3007.severity = none + +# CA3008: Review code for XPath injection vulnerabilities +# dotnet_diagnostic.CA3008.severity = none + +# CA3009: Review code for XML injection vulnerabilities +# dotnet_diagnostic.CA3009.severity = none + +# CA3010: Review code for XAML injection vulnerabilities +# dotnet_diagnostic.CA3010.severity = none + +# CA3011: Review code for DLL injection vulnerabilities +# dotnet_diagnostic.CA3011.severity = none + +# CA3012: Review code for regex injection vulnerabilities +# dotnet_diagnostic.CA3012.severity = none + +# CA3061: Do Not Add Schema By URL +# dotnet_diagnostic.CA3061.severity = warning + +# CA5350: Do Not Use Weak Cryptographic Algorithms +# dotnet_diagnostic.CA5350.severity = warning + +# CA5351: Do Not Use Broken Cryptographic Algorithms +# dotnet_diagnostic.CA5351.severity = warning + +# CA5358: Do Not Use Unsafe Cipher Modes +# dotnet_diagnostic.CA5358.severity = none + +# CA5359: Do Not Disable Certificate Validation +# dotnet_diagnostic.CA5359.severity = warning + +# CA5360: Do Not Call Dangerous Methods In Deserialization +# dotnet_diagnostic.CA5360.severity = warning + +# CA5361: Do Not Disable SChannel Use of Strong Crypto +# dotnet_diagnostic.CA5361.severity = warning + +# CA5362: Do Not Refer Self In Serializable Class +# dotnet_diagnostic.CA5362.severity = none + +# CA5363: Do Not Disable Request Validation +# dotnet_diagnostic.CA5363.severity = warning + +# CA5364: Do Not Use Deprecated Security Protocols +# dotnet_diagnostic.CA5364.severity = warning + +# CA5365: Do Not Disable HTTP Header Checking +# dotnet_diagnostic.CA5365.severity = warning + +# CA5366: Use XmlReader For DataSet Read Xml +# dotnet_diagnostic.CA5366.severity = warning + +# CA5367: Do Not Serialize Types With Pointer Fields +# dotnet_diagnostic.CA5367.severity = none + +# CA5368: Set ViewStateUserKey For Classes Derived From Page +# dotnet_diagnostic.CA5368.severity = warning + +# CA5369: Use XmlReader For Deserialize +# dotnet_diagnostic.CA5369.severity = warning + +# CA5370: Use XmlReader For Validating Reader +# dotnet_diagnostic.CA5370.severity = warning + +# CA5371: Use XmlReader For Schema Read +# dotnet_diagnostic.CA5371.severity = warning + +# CA5372: Use XmlReader For XPathDocument +# dotnet_diagnostic.CA5372.severity = warning + +# CA5373: Do not use obsolete key derivation function +# dotnet_diagnostic.CA5373.severity = warning + +# CA5374: Do Not Use XslTransform +# dotnet_diagnostic.CA5374.severity = warning + +# CA5375: Do Not Use Account Shared Access Signature +# dotnet_diagnostic.CA5375.severity = none + +# CA5376: Use SharedAccessProtocol HttpsOnly +# dotnet_diagnostic.CA5376.severity = warning + +# CA5377: Use Container Level Access Policy +# dotnet_diagnostic.CA5377.severity = warning + +# CA5378: Do not disable ServicePointManagerSecurityProtocols +# dotnet_diagnostic.CA5378.severity = warning + +# CA5379: Do Not Use Weak Key Derivation Function Algorithm +# dotnet_diagnostic.CA5379.severity = warning + +# CA5380: Do Not Add Certificates To Root Store +# dotnet_diagnostic.CA5380.severity = warning + +# CA5381: Ensure Certificates Are Not Added To Root Store +# dotnet_diagnostic.CA5381.severity = warning + +# CA5382: Use Secure Cookies In ASP.Net Core +# dotnet_diagnostic.CA5382.severity = none + +# CA5383: Ensure Use Secure Cookies In ASP.Net Core +# dotnet_diagnostic.CA5383.severity = none + +# CA5384: Do Not Use Digital Signature Algorithm (DSA) +# dotnet_diagnostic.CA5384.severity = warning + +# CA5385: Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size +# dotnet_diagnostic.CA5385.severity = warning + +# CA5386: Avoid hardcoding SecurityProtocolType value +# dotnet_diagnostic.CA5386.severity = none + +# CA5387: Do Not Use Weak Key Derivation Function With Insufficient Iteration Count +# dotnet_diagnostic.CA5387.severity = none + +# CA5388: Ensure Sufficient Iteration Count When Using Weak Key Derivation Function +# dotnet_diagnostic.CA5388.severity = none + +# CA5389: Do Not Add Archive Item's Path To The Target File System Path +# dotnet_diagnostic.CA5389.severity = none + +# CA5390: Do not hard-code encryption key +# dotnet_diagnostic.CA5390.severity = none + +# CA5391: Use antiforgery tokens in ASP.NET Core MVC controllers +# dotnet_diagnostic.CA5391.severity = none + +# CA5392: Use DefaultDllImportSearchPaths attribute for P/Invokes +# dotnet_diagnostic.CA5392.severity = none + +# CA5393: Do not use unsafe DllImportSearchPath value +# dotnet_diagnostic.CA5393.severity = none + +# CA5394: Do not use insecure randomness +# dotnet_diagnostic.CA5394.severity = none + +# CA5395: Miss HttpVerb attribute for action methods +# dotnet_diagnostic.CA5395.severity = none + +# CA5396: Set HttpOnly to true for HttpCookie +# dotnet_diagnostic.CA5396.severity = none + +# CA5397: Do not use deprecated SslProtocols values +# dotnet_diagnostic.CA5397.severity = warning + +# CA5398: Avoid hardcoded SslProtocols values +# dotnet_diagnostic.CA5398.severity = none + +# CA5399: HttpClients should enable certificate revocation list checks +# dotnet_diagnostic.CA5399.severity = none + +# CA5400: Ensure HttpClient certificate revocation list check is not disabled +# dotnet_diagnostic.CA5400.severity = none + +# CA5401: Do not use CreateEncryptor with non-default IV +# dotnet_diagnostic.CA5401.severity = none + +# CA5402: Use CreateEncryptor with the default IV +# dotnet_diagnostic.CA5402.severity = none + +# CA5403: Do not hard-code certificate +# dotnet_diagnostic.CA5403.severity = none + +# NetFramework + +# CA1058: Types should not extend certain base types +# dotnet_diagnostic.CA1058.severity = warning + +# CA2153: Do Not Catch Corrupted State Exceptions +# dotnet_diagnostic.CA2153.severity = warning + +# CA3075: Insecure DTD processing in XML +# dotnet_diagnostic.CA3075.severity = warning + +# CA3076: Insecure XSLT script processing. +# dotnet_diagnostic.CA3076.severity = warning + +# CA3077: Insecure Processing in API Design, XmlDocument and XmlTextReader +# dotnet_diagnostic.CA3077.severity = warning + +# CA3147: Mark Verb Handlers With Validate Antiforgery Token +# dotnet_diagnostic.CA3147.severity = warning + +# PublicApi + +# RS0016: Add public types and members to the declared API +# dotnet_diagnostic.RS0016.severity = warning + +# RS0017: Remove deleted types and members from the declared API +# dotnet_diagnostic.RS0017.severity = warning + +# RS0022: Constructor make noninheritable base class inheritable +# dotnet_diagnostic.RS0022.severity = warning + +# RS0024: The contents of the public API files are invalid +# dotnet_diagnostic.RS0024.severity = warning + +# RS0025: Do not duplicate symbols in public API files +# dotnet_diagnostic.RS0025.severity = warning + +# RS0026: Do not add multiple public overloads with optional parameters +# dotnet_diagnostic.RS0026.severity = warning + +# RS0027: Public API with optional parameter(s) should have the most parameters amongst its public overloads. +# dotnet_diagnostic.RS0027.severity = warning # ReSharper properties -resharper_accessor_declaration_braces=end_of_line -resharper_align_linq_query=true -resharper_align_multiline_argument=true -resharper_align_multiline_calls_chain=true -resharper_align_multiline_extends_list=true -resharper_align_multiline_for_stmt=true -resharper_align_multiline_parameter=true -resharper_align_multiple_declaration=true -resharper_align_multline_type_parameter_constrains=true -resharper_align_multline_type_parameter_list=true -resharper_align_tuple_components=true -resharper_autodetect_indent_settings=true -resharper_constructor_or_destructor_body=expression_body -resharper_csharp_anonymous_method_declaration_braces=end_of_line -resharper_csharp_outdent_commas=true -resharper_csharp_outdent_dots=true -resharper_csharp_space_within_parentheses=true -resharper_csharp_wrap_after_declaration_lpar=true -resharper_csharp_wrap_after_invocation_lpar=true -resharper_csharp_wrap_before_binary_opsign=true -resharper_csharp_wrap_before_declaration_rpar=true -resharper_csharp_wrap_before_invocation_rpar=true -resharper_enforce_line_ending_style=true -resharper_initializer_braces=end_of_line -resharper_int_align_switch_expressions=true -resharper_int_align_switch_sections=true -resharper_keep_existing_enum_arrangement=true -resharper_keep_existing_switch_expression_arrangement=false -resharper_max_initializer_elements_on_line=2 -resharper_method_or_operator_body=expression_body -resharper_outdent_binary_ops=true -resharper_place_comments_at_first_column=true -resharper_place_simple_enum_on_single_line=true -resharper_space_around_arrow_op=true -resharper_space_within_single_line_array_initializer_braces=true -resharper_use_heuristics_for_body_style=false -resharper_use_indent_from_vs=false -resharper_wrap_lines=true -resharper_xmldoc_allow_far_alignment=true -resharper_xmldoc_attribute_style=on_single_line -resharper_xmldoc_indent_text=ZeroIndent -resharper_xmldoc_max_blank_lines_between_tags=1 -resharper_xmldoc_pi_attribute_style=on_single_line -resharper_xmldoc_space_after_last_pi_attribute=true +resharper_align_linq_query = true +resharper_align_multiline_argument = true +resharper_align_multiline_array_and_object_initializer = false +resharper_align_multiline_binary_expressions_chain = false +resharper_align_multiline_calls_chain = true +resharper_align_multiline_expression = true +resharper_align_multiline_extends_list = true +resharper_align_multiline_for_stmt = true +resharper_align_multiline_parameter = true +resharper_align_multiline_switch_expression = false +resharper_align_multiple_declaration = true +resharper_align_multline_type_parameter_constrains = true +resharper_align_multline_type_parameter_list = true +resharper_align_tuple_components = true +resharper_arguments_anonymous_function = positional +resharper_autodetect_indent_settings = true +resharper_braces_for_for = not_required +resharper_braces_for_foreach = not_required +resharper_braces_for_ifelse = not_required_for_both +resharper_braces_for_while = not_required +resharper_braces_redundant = false +resharper_constructor_or_destructor_body = block_body +resharper_continuous_indent_multiplier = 1 +resharper_cpp_empty_block_style = multiline +resharper_cpp_outdent_commas = false +resharper_cpp_outdent_dots = false +resharper_cpp_wrap_after_declaration_lpar = false +resharper_cpp_wrap_after_invocation_lpar = false +resharper_cpp_wrap_before_declaration_rpar = false +resharper_cpp_wrap_before_invocation_rpar = false +resharper_csharp_align_multiline_argument = true +resharper_csharp_align_multiline_binary_expressions_chain = true +resharper_csharp_align_multiline_expression = false +resharper_csharp_brace_style = next_line +resharper_csharp_empty_block_style = multiline +resharper_csharp_outdent_commas = true +resharper_csharp_outdent_dots = true +resharper_csharp_place_comments_at_first_column = true +resharper_csharp_wrap_after_declaration_lpar = true +resharper_csharp_wrap_after_invocation_lpar = true +resharper_csharp_wrap_before_binary_opsign = true +resharper_csharp_wrap_before_declaration_rpar = true +resharper_csharp_wrap_before_invocation_rpar = true +resharper_csharp_wrap_multiple_declaration_style = chop_if_long +resharper_empty_block_style = together_same_line +resharper_indent_anonymous_method_block = false +resharper_int_align_switch_expressions = true +resharper_int_align_switch_sections = true +resharper_keep_existing_declaration_block_arrangement = false +resharper_keep_existing_embedded_block_arrangement = false +resharper_keep_existing_enum_arrangement = true +resharper_keep_existing_invocation_parens_arrangement = true +resharper_keep_existing_linebreaks = true +resharper_keep_existing_switch_expression_arrangement = false +resharper_keep_user_linebreaks = true +resharper_max_initializer_elements_on_line = 2 +resharper_method_or_operator_body = block_body +resharper_outdent_binary_ops = true +resharper_outdent_commas = true +resharper_outdent_dots = true +resharper_space_around_arrow_op = true +resharper_space_within_single_line_array_initializer_braces = true +resharper_use_heuristics_for_body_style = true +resharper_use_indent_from_vs = false +resharper_wrap_after_declaration_lpar = true +resharper_wrap_after_invocation_lpar = true +resharper_wrap_arguments_style = wrap_if_long +resharper_wrap_before_declaration_rpar = true +resharper_wrap_before_invocation_rpar = true +resharper_wrap_chained_method_calls = wrap_if_long +resharper_wrap_multiple_declaration_style = chop_if_long +resharper_wrap_object_and_collection_initializer_style = chop_if_long +resharper_xmldoc_attribute_style = on_single_line +resharper_xmldoc_pi_attribute_style = on_single_line +resharper_xmldoc_space_after_last_pi_attribute = true +resharper_xmldoc_space_before_self_closing = true # ReSharper inspection severities -resharper_annotate_can_be_null_parameter_highlighting=warning -resharper_annotate_can_be_null_type_member_highlighting=warning -resharper_arrange_missing_parentheses_highlighting=warning -resharper_arrange_this_qualifier_highlighting=warning -resharper_built_in_type_reference_style_for_member_access_highlighting=error -resharper_built_in_type_reference_style_highlighting=error -resharper_enforce_do_while_statement_braces_highlighting=warning -resharper_enforce_fixed_statement_braces_highlighting=warning -resharper_enforce_foreach_statement_braces_highlighting=warning -resharper_enforce_for_statement_braces_highlighting=warning -resharper_enforce_if_statement_braces_highlighting=warning -resharper_enforce_lock_statement_braces_highlighting=warning -resharper_enforce_using_statement_braces_highlighting=warning -resharper_enforce_while_statement_braces_highlighting=warning -resharper_redundant_default_member_initializer_highlighting=hint -resharper_remove_redundant_braces_highlighting=warning -resharper_suggest_var_or_type_built_in_types_highlighting=warning -resharper_suggest_var_or_type_elsewhere_highlighting=warning -resharper_suggest_var_or_type_simple_types_highlighting=warning -resharper_unnecessary_whitespace_highlighting=warning -resharper_use_null_propagation_when_possible_highlighting=suggestion -resharper_web_config_module_not_resolved_highlighting=warning -resharper_web_config_type_not_resolved_highlighting=warning -resharper_web_config_wrong_module_highlighting=warning - -# .NET Analzyer settings -# VSTHRD200: Use "Async" suffix for awaitable methods -dotnet_diagnostic.VSTHRD200.severity = none -# CA2007: Do not directly await a Task -dotnet_diagnostic.CA2007.severity = error - -[*.{cs,cshtml}] -charset=utf-8 -indent_style=space -indent_size=4 -insert_final_newline=true - -[*.{js,ts,vue}] -indent_style=space -indent_size=4 -insert_final_newline=true - -[*.{xml,yml,yaml}] -indent_style=space -indent_size=2 -insert_final_newline=true - -[*.json] -indent_style=space -indent_size=4 -insert_final_newline=true - -[*.{xml,csproj,props,targets}] -indent_style=space - -[{*.har,*.inputactions,*.jsb2,*.jsb3,.babelrc,.eslintrc,.prettierrc,.stylelintrc,bowerrc,jest.config}] -indent_style=space -indent_size=2 - -[*.{appxmanifest,asax,ascx,aspx,build,cg,cginc,compute,cs,cshtml,dtd,fs,fsi,fsscript,fsx,hlsl,hlsli,hlslinc,master,ml,mli,nuspec,razor,resw,resx,shader,skin,usf,ush,vb,xaml,xamlx,xoml,xsd}] -indent_style=space -indent_size=4 -tab_width=4 +resharper_annotate_can_be_null_parameter_highlighting = warning +resharper_annotate_can_be_null_type_member_highlighting = warning +resharper_arrange_constructor_or_destructor_body_highlighting = none +resharper_arrange_method_or_operator_body_highlighting = none +resharper_arrange_redundant_parentheses_highlighting = hint +resharper_arrange_this_qualifier_highlighting = hint +resharper_arrange_type_member_modifiers_highlighting = hint +resharper_arrange_type_modifiers_highlighting = hint +resharper_built_in_type_reference_style_for_member_access_highlighting = hint +resharper_built_in_type_reference_style_highlighting = hint +resharper_enforce_do_while_statement_braces_highlighting = warning +resharper_enforce_fixed_statement_braces_highlighting = warning +resharper_enforce_foreach_statement_braces_highlighting = warning +resharper_enforce_for_statement_braces_highlighting = warning +resharper_enforce_if_statement_braces_highlighting = warning +resharper_enforce_lock_statement_braces_highlighting = warning +resharper_enforce_using_statement_braces_highlighting = warning +resharper_enforce_while_statement_braces_highlighting = warning +resharper_redundant_base_qualifier_highlighting = warning +resharper_redundant_default_member_initializer_highlighting = hint +resharper_remove_redundant_braces_highlighting = warning +resharper_suggest_var_or_type_built_in_types_highlighting = hint +resharper_suggest_var_or_type_elsewhere_highlighting = hint +resharper_suggest_var_or_type_simple_types_highlighting = hint +resharper_unnecessary_whitespace_highlighting = warning +resharper_use_null_propagation_when_possible_highlighting = suggestion +resharper_web_config_module_not_resolved_highlighting = warning +resharper_web_config_type_not_resolved_highlighting = warning +resharper_web_config_wrong_module_highlighting = warning +resharper_partial_type_with_single_part_highlighting = none + +ij_xml_align_attributes = true +ij_xml_align_text = false +ij_xml_attribute_wrap = normal +ij_xml_block_comment_at_first_column = true +ij_xml_keep_blank_lines = 2 +ij_xml_keep_indents_on_empty_lines = false +ij_xml_keep_line_breaks = true +ij_xml_keep_line_breaks_in_text = true +ij_xml_keep_whitespaces = true +ij_xml_keep_whitespaces_around_cdata = preserve +ij_xml_keep_whitespaces_inside_cdata = false +ij_xml_line_comment_at_first_column = true +ij_xml_space_after_tag_name = false +ij_xml_space_around_equals_in_attribute = false +ij_xml_space_inside_empty_tag = true +ij_xml_text_wrap = off + +# Microsoft .NET properties +dotnet_naming_rule.unity_serialized_field_rule.import_to_resharper = True +dotnet_naming_rule.unity_serialized_field_rule.resharper_description = Unity serialized field +dotnet_naming_rule.unity_serialized_field_rule.resharper_guid = 5f0fdb63-c892-4d2c-9324-15c80b22a7ef +dotnet_naming_rule.unity_serialized_field_rule.severity = warning +dotnet_naming_rule.unity_serialized_field_rule.style = lower_camel_case_style +dotnet_naming_rule.unity_serialized_field_rule.symbols = unity_serialized_field_symbols +dotnet_naming_style.lower_camel_case_style.capitalization = camel_case +dotnet_naming_symbols.unity_serialized_field_symbols.applicable_accessibilities = * +dotnet_naming_symbols.unity_serialized_field_symbols.applicable_kinds = +dotnet_naming_symbols.unity_serialized_field_symbols.resharper_applicable_kinds = unity_serialised_field +dotnet_naming_symbols.unity_serialized_field_symbols.resharper_required_modifiers = instance + +[*.{appxmanifest,asax,ascx,aspx,axaml,build,cg,cginc,compute,dtd,fs,fsi,fsscript,fsx,hlsl,hlsli,hlslinc,master,ml,mli,nuspec,paml,resw,resx,shader,skin,usf,ush,vb,xaml,xamlx,xoml,xsd}] +indent_style = space +indent_size = 4 +tab_width = 4 diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index eba8bd573..000000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,28 +0,0 @@ -version: 2 -updates: - - package-ecosystem: 'github-actions' - directory: '/' - schedule: - interval: 'daily' - assignees: - - 'david-driscoll' - open-pull-requests-limit: 100 - - - package-ecosystem: 'npm' - directory: '/' - schedule: - interval: 'daily' - assignees: - - 'david-driscoll' - open-pull-requests-limit: 100 - - - package-ecosystem: 'nuget' - directory: '/' - schedule: - interval: 'daily' - assignees: - - 'david-driscoll' - ignore: - - dependency-name: Microsoft.Extensions.* - - dependency-name: Microsoft.AspNetCore.* - open-pull-requests-limit: 100 diff --git a/.github/label-commenter-dependabot.yml b/.github/label-commenter-dependabot.yml deleted file mode 100644 index 0e71df27b..000000000 --- a/.github/label-commenter-dependabot.yml +++ /dev/null @@ -1,5 +0,0 @@ -labels: - - name: 'merge' - labeled: - pr: - body: '@dependabot squash and merge' diff --git a/.github/labels.yml b/.github/labels.yml index a94e5d5d9..bee0d5482 100644 --- a/.github/labels.yml +++ b/.github/labels.yml @@ -1,54 +1,66 @@ -- name: "bug" - color: "d73a4a" +- name: 'bug' + color: 'd73a4a' description: "Something isn't working" -- name: "documentation" +- name: 'documentation' color: 0075ca - description: "Improvements or additions to documentation" -- name: "duplicate" - color: "cfd3d7" - description: "This issue or pull request already exists" -- name: "enhancement" - color: "a2eeef" - description: "New feature or request" -- name: "help wanted" - color: "008672" - description: "Extra attention is needed" -- name: "good first issue" - color: "7057ff" - description: "Good for newcomers" -- name: "invalid" - color: "e4e669" + description: 'Improvements or additions to documentation' +- name: 'duplicate' + color: 'cfd3d7' + description: 'This issue or pull request already exists' +- name: 'enhancement' + color: 'a2eeef' + description: 'New feature or request' +- name: 'help wanted' + color: '008672' + description: 'Extra attention is needed' +- name: 'good first issue' + color: '7057ff' + description: 'Good for newcomers' +- name: 'invalid' + color: 'e4e669' description: "This doesn't seem right" -- name: "question" - color: "d876e3" - description: "Further information is requested" -- name: "wontfix" - color: "ffffff" - description: "This will not be worked on" -- name: "feature" - color: "ccf5ff" - description: "This adds some form of new functionality" -- name: "breaking change" - color: "efa7ae" - description: "This breaks existing behavior" -- name: "mysterious" - color: "cccccc" - description: "We forgot to label this" -- name: "chore" - color: "27127c" - description: "Just keeping things neat and tidy" -- name: "dependencies" - color: "edc397" - description: "Pull requests that update a dependency file" -- name: "merge" - color: "98ed98" - description: "Shipit!" -- name: "deprecated" - color: "dd824d" - description: "Deprecated functionality" -- name: "removed" - color: "fce99f" - description: "Removed functionality" -- name: "security" - color: "cbce1e" - description: "Security related issue" +- name: 'question' + color: 'd876e3' + description: 'Further information is requested' +- name: 'wontfix' + color: 'ffffff' + description: 'This will not be worked on' +- name: 'feature' + color: 'ccf5ff' + description: 'This adds some form of new functionality' +- name: 'breaking change' + color: 'efa7ae' + description: 'This breaks existing behavior' +- name: 'mysterious' + color: 'cccccc' + description: 'We forgot to label this' +- name: 'chore' + color: '27127c' + description: 'Just keeping things neat and tidy' +- name: 'dependencies' + color: 'edc397' + description: 'Pull requests that update a dependency file' +- name: 'merge' + color: '98ed98' + description: 'Shipit!' +- name: 'deprecated' + color: 'dd824d' + description: 'Deprecated functionality' +- name: 'removed' + color: 'fce99f' + description: 'Removed functionality' +- name: 'security' + color: 'cbce1e' + description: 'Security related issue' +- name: 'private-dependencies' + color: 'edc397' + description: 'Private dependency' +- name: 'rebase' + color: 'ffcc66' + description: 'Rebase branch' +- name: 'stop updating' + color: '800000' + description: 'Stop Updating' +- name: 'blocked' + color: 'FF5600' + description: 'Issue is blocked waiting for something or someone' diff --git a/.github/renovate.json b/.github/renovate.json new file mode 100644 index 000000000..1769b4f1d --- /dev/null +++ b/.github/renovate.json @@ -0,0 +1,196 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": [ + "config:base", + ":automergePatch", + ":separateMajorReleases", + ":combinePatchMinorReleases", + ":enableVulnerabilityAlertsWithLabel(:old_key: security)", + ":dependencyDashboard" + ], + "prHourlyLimit": 10, + "prConcurrentLimit": 0, + "hostRules": [ + { + "concurrentRequestLimit": 999 + } + ], + "platformAutomerge": true, + "automergeType": "pr", + "automergeStrategy": "rebase", + "rebaseWhen": "auto", + "labels": [":package: dependencies"], + "rebaseLabel": ":trident: rebase", + "stopUpdatingLabel": ":vertical_traffic_light: stop updating", + "github-actions": { + "fileMatch": ["(^workflow-templates|\\.github\\/workflows)\\/[^/]+\\.ya?ml$", "(^|\\/)action\\.ya?ml$"], + "automerge": true, + "groupName": "github actions", + "labels": [":truck: private-dependencies"] + }, + "packageRules": [ + { + "matchManagers": ["nuget"], + "groupName": "build dependencies", + "matchPackagePatterns": ["^Nuke.Common", "^Microsoft\\.NET\\.Test\\.Sdk$", "^Rocket\\.Surgery\\.MSBuild$", "^Rocket\\.Surgery\\.Nuke$"], + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^Roslynator"], + "groupName": "roslynator", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^FluentAssertions"], + "groupName": "fluentassertions", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^NSubstitute"], + "groupName": "nsubstitute", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^Moq"], + "groupName": "moq", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^FakeItEasy"], + "groupName": "fakeiteasy", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^coverlet"], + "groupName": "coverlet", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^Bogus"], + "groupName": "bogus", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^ReportGenerator", "^reportgenerator", "^dotnet-reportgenerator"], + "groupName": "reportgenerator", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^JetBrains", "^jetbrains"], + "groupName": "jetbrains", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^GitVersion", "^gitversion"], + "groupName": "gitversion", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^xunit"], + "groupName": "xunit", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^bunit"], + "groupName": "bunit", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^FluentValidation"], + "groupName": "fluentvalidation", + "labels": [":package: dependencies"], + "automerge": false + }, + { + "matchPackagePatterns": ["^NodaTime"], + "groupName": "nodatime", + "labels": [":package: dependencies"], + "automerge": false + }, + { + "matchPackagePatterns": ["^DryIoc"], + "groupName": "dryioc", + "labels": [":package: dependencies"], + "automerge": false + }, + { + "matchPackagePatterns": ["^FluentAssertions"], + "groupName": "fluentassertions", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchPackagePatterns": ["^Verify"], + "groupName": "verify", + "labels": [":truck: private-dependencies"], + "automerge": true + }, + { + "matchManagers": ["nuget"], + "matchPackagePatterns": ["^System\\.Collections\\.Immutable", "^System\\.Interactive", "^System\\.Reactive", "^Humanizer"], + "labels": [":package: dependencies"], + "automerge": true + }, + { + "matchSourceUrlPrefixes": ["https://github.com/RocketSurgeonsGuild"], + "labels": [":package: dependencies"], + "groupName": "Rocket Surgery Other" + }, + { + "matchSourceUrlPrefixes": ["https://github.com/RocketSurgeonsGuild/Conventions"], + "labels": [":package: dependencies"], + "groupName": "Rocket Surgery Conventions" + }, + { + "matchSourceUrlPrefixes": ["https://github.com/RocketSurgeonsGuild/Testing"], + "labels": [":truck: private-dependencies"], + "groupName": "Rocket Surgery Testing" + }, + { + "matchSourceUrlPrefixes": ["https://github.com/RocketSurgeonsGuild/Extensions"], + "labels": [":package: dependencies"], + "groupName": "Rocket Surgery Extensions" + }, + { + "description": "dotnet monorepo", + "groupName": "dotnet monorepo", + "enabled": false, + "matchSourceUrlPrefixes": [ + "https://github.com/dotnet/aspnetcore", + "https://github.com/dotnet/efcore", + "https://github.com/dotnet/extensions", + "https://github.com/dotnet/runtime" + ] + }, + { + "description": "dotnet monorepo [minor/patch]", + "groupName": "dotnet monorepo [minor/patch]", + "enabled": true, + "matchUpdateTypes": ["minor", "patch"], + "matchSourceUrlPrefixes": [ + "https://github.com/dotnet/aspnetcore", + "https://github.com/dotnet/efcore", + "https://github.com/dotnet/extensions", + "https://github.com/dotnet/runtime" + ] + }, + { + "description": "dotnet msbuild", + "groupName": "dotnet msbuild", + "matchSourceUrlPrefixes": ["https://github.com/dotnet/msbuild"] + } + ] +} diff --git a/.github/workflows/ci-ignore.yml b/.github/workflows/ci-ignore.yml new file mode 100644 index 000000000..a5c03cbb6 --- /dev/null +++ b/.github/workflows/ci-ignore.yml @@ -0,0 +1,80 @@ +# ------------------------------------------------------------------------------ +# +# +# This code was generated. +# +# - To turn off auto-generation set: +# +# [GitHubActionsSteps (AutoGenerate = false)] +# +# - To trigger manual generation invoke: +# +# nuke --generate-configuration GitHubActions_ci-ignore --host GitHubActions +# +# +# ------------------------------------------------------------------------------ + +name: ci-ignore + +on: + push: + branches: + - 'master' + - 'main' + - 'next' + tags: + - 'v*' + paths: + - '.codecov.yml' + - '.editorconfig' + - '.gitattributes' + - '.gitignore' + - '.gitmodules' + - '.lintstagedrc.js' + - '.prettierignore' + - '.prettierrc' + - 'LICENSE' + - 'nukeeper.settings.json' + - 'omnisharp.json' + - 'package-lock.json' + - 'package.json' + - 'Readme.md' + - '.github/dependabot.yml' + - '.github/labels.yml' + - '.github/release.yml' + - '.github/renovate.json' + pull_request: + branches: + - 'master' + - 'main' + - 'next' + paths: + - '.codecov.yml' + - '.editorconfig' + - '.gitattributes' + - '.gitignore' + - '.gitmodules' + - '.lintstagedrc.js' + - '.prettierignore' + - '.prettierrc' + - 'LICENSE' + - 'nukeeper.settings.json' + - 'omnisharp.json' + - 'package-lock.json' + - 'package.json' + - 'Readme.md' + - '.github/dependabot.yml' + - '.github/labels.yml' + - '.github/release.yml' + - '.github/renovate.json' + +jobs: + Build: + strategy: + matrix: + os: [windows-latest, ubuntu-latest] + runs-on: ${{ matrix.os }} + steps: + - name: N/A + run: | + echo "No build required" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 677ae4f85..f36ecefe5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,43 +19,91 @@ name: ci on: push: branches: - - master - - next + - 'master' + - 'main' + - 'next' tags: - - v* + - 'v*' + paths-ignore: + - '.codecov.yml' + - '.editorconfig' + - '.gitattributes' + - '.gitignore' + - '.gitmodules' + - '.lintstagedrc.js' + - '.prettierignore' + - '.prettierrc' + - 'LICENSE' + - 'nukeeper.settings.json' + - 'omnisharp.json' + - 'package-lock.json' + - 'package.json' + - 'Readme.md' + - '.github/dependabot.yml' + - '.github/labels.yml' + - '.github/release.yml' + - '.github/renovate.json' pull_request: branches: - - master - - next + - 'master' + - 'main' + - 'next' + paths-ignore: + - '.codecov.yml' + - '.editorconfig' + - '.gitattributes' + - '.gitignore' + - '.gitmodules' + - '.lintstagedrc.js' + - '.prettierignore' + - '.prettierrc' + - 'LICENSE' + - 'nukeeper.settings.json' + - 'omnisharp.json' + - 'package-lock.json' + - 'package.json' + - 'Readme.md' + - '.github/dependabot.yml' + - '.github/labels.yml' + - '.github/release.yml' + - '.github/renovate.json' jobs: Build: + env: + NUGET_PACKAGES: '${{ github.workspace }}/.nuget/packages' strategy: fail-fast: false matrix: - os: [macOS-latest, windows-latest, ubuntu-latest] + os: + # - macOS-latest + - windows-latest + - ubuntu-latest runs-on: ${{ matrix.os }} steps: - name: Checkout - uses: actions/checkout@v2.3.4 + uses: actions/checkout@v3.0.2 with: clean: 'false' fetch-depth: '0' - name: Fetch all history for all tags and branches run: | git fetch --prune - - name: 🔨 Use .NET Core 2.1 SDK - uses: actions/setup-dotnet@v1.8.1 + - name: NuGet Cache + uses: actions/cache@v3 with: - dotnet-version: '2.1.x' + path: '${{ github.workspace }}/.nuget/packages' + key: "${{ runner.os }}-nuget-${{ hashFiles('**/Directory.Packages.props') }}-${{ hashFiles('**/Directory.Packages.support.props') }}" + restore-keys: | + ${{ runner.os }}-nuget- - name: 🔨 Use .NET Core 3.1 SDK - uses: actions/setup-dotnet@v1.8.1 + uses: actions/setup-dotnet@v2.1.0 with: dotnet-version: '3.1.x' - - name: 🔨 Use .NET Core 5.0 SDK - uses: actions/setup-dotnet@v1.8.1 + - name: 🔨 Use .NET Core 6.0 SDK + uses: actions/setup-dotnet@v2.1.0 with: - dotnet-version: '5.0.x' + dotnet-version: '6.0.x' - name: 🎁 dotnet tool restore run: | dotnet tool restore @@ -67,39 +115,48 @@ jobs: dotnet nuke Build --skip - name: 🚦 Test run: | - dotnet nuke Test Trigger_Code_Coverage_Reports Generate_Code_Coverage_Report_Cobertura Generate_Code_Coverage_Badges Generate_Code_Coverage_Summary Generate_Code_Coverage_Report --skip + dotnet nuke Test TriggerCodeCoverageReports GenerateCodeCoverageReportCobertura GenerateCodeCoverageBadges GenerateCodeCoverageSummary GenerateCodeCoverageReport --skip - name: 📦 Pack run: | dotnet nuke Pack --skip - name: 🐿 Publish Coverage - uses: codecov/codecov-action@v1 + uses: codecov/codecov-action@v3 with: name: 'actions-${{ matrix.os }}' - fail_ci_if_error: 'true' - name: 🏺 Publish logs if: always() - continue-on-error: true - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v3 with: name: 'logs' path: 'artifacts/logs/' - name: 🏺 Publish coverage data if: always() - continue-on-error: true - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v3 with: name: 'coverage' path: 'coverage/' - name: 🏺 Publish test data if: always() - continue-on-error: true - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v3 with: name: 'test data' path: 'artifacts/test/' - name: 🏺 Publish NuGet Packages if: always() - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v3 with: name: 'nuget' path: 'artifacts/nuget/' + - name: 🏺 Publish Docs + if: always() + uses: actions/upload-artifact@v3 + with: + name: 'docs' + path: 'artifacts/docs/' + Publish: + needs: + - Build + secrets: + RSG_NUGET_API_KEY: '${{ secrets.RSG_NUGET_API_KEY }}' + RSG_AZURE_DEVOPS: '${{ secrets.RSG_AZURE_DEVOPS }}' + uses: RocketSurgeonsGuild/actions/.github/workflows/publish-nuget.yml@v0.3.1 diff --git a/.github/workflows/close-milestone.yml b/.github/workflows/close-milestone.yml index 5d59734f6..42e5d0c0a 100644 --- a/.github/workflows/close-milestone.yml +++ b/.github/workflows/close-milestone.yml @@ -1,30 +1,32 @@ name: Close Milestone + on: release: types: - released + jobs: close_milestone: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v2.3.4 + uses: actions/checkout@v3.0.2 with: fetch-depth: 0 - name: Install GitVersion - uses: gittools/actions/gitversion/setup@v0.9.10 + uses: gittools/actions/gitversion/setup@v0.9.13 with: versionSpec: '5.x' - name: Install GitReleaseManager - uses: gittools/actions/gitreleasemanager/setup@v0.9.10 + uses: gittools/actions/gitreleasemanager/setup@v0.9.13 with: versionSpec: '0.11.x' - name: Use GitVersion id: gitversion - uses: gittools/actions/gitversion/execute@v0.9.10 + uses: gittools/actions/gitversion/execute@v0.9.13 # Ensure the milestone exists - name: Create Milestone @@ -37,7 +39,7 @@ jobs: # move any issues to that milestone in the event the release is renamed - name: sync milestones - uses: RocketSurgeonsGuild/actions/sync-milestone@v0.2.4 + uses: RocketSurgeonsGuild/actions/sync-milestone@v0.3.1 with: default-label: 'mysterious' github-token: ${{ secrets.OMNISHARP_BOT_TOKEN }} diff --git a/.github/workflows/dependabot-merge.yml b/.github/workflows/dependabot-merge.yml index 28515c4a5..5da81288a 100644 --- a/.github/workflows/dependabot-merge.yml +++ b/.github/workflows/dependabot-merge.yml @@ -4,34 +4,80 @@ on: pull_request_target: types: - labeled + - opened + - reopened + - closed + - synchronize jobs: comment: - runs-on: ubuntu-18.04 + runs-on: ubuntu-latest + if: | + (github.event.action == 'labeled' || github.event.action == 'opened' || github.event.action == 'reopened') steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" + - name: Dump job context env: JOB_CONTEXT: ${{ toJson(job) }} run: echo "$JOB_CONTEXT" + - name: Dump steps context env: STEPS_CONTEXT: ${{ toJson(steps) }} run: echo "$STEPS_CONTEXT" + - name: Dump runner context env: RUNNER_CONTEXT: ${{ toJson(runner) }} run: echo "$RUNNER_CONTEXT" - - uses: actions/checkout@v2.3.4 + + - name: GitHub Automerge + if: | + contains(github.event.pull_request.labels.*.name, ':shipit: merge') + || contains(github.event.pull_request.labels.*.name, 'javascript') + || contains(github.event.pull_request.labels.*.name, 'github-actions') + uses: alexwilson/enable-github-automerge-action@1.0.0 + continue-on-error: true with: - ref: master - - name: Dependabot Commenter + github-token: '${{ secrets.OMNISHARP_BOT_TOKEN }}' + merge-method: 'SQUASH' + + labeler: + runs-on: ubuntu-latest + if: | + (github.event.action == 'closed' || github.event.action == 'opened' || github.event.action == 'reopened') + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + + - name: Dump job context + env: + JOB_CONTEXT: ${{ toJson(job) }} + run: echo "$JOB_CONTEXT" + + - name: Dump steps context + env: + STEPS_CONTEXT: ${{ toJson(steps) }} + run: echo "$STEPS_CONTEXT" + + - name: Dump runner context + env: + RUNNER_CONTEXT: ${{ toJson(runner) }} + run: echo "$RUNNER_CONTEXT" + + - name: GitHub Remove Labels if: | - (github.event.label.name == 'merge') && (github.event.pull_request.user.login == 'dependabot[bot]' || github.event.pull_request.user.login == 'dependabot-preview[bot]') - uses: peaceiris/actions-label-commenter@v1.10.0 + github.event.action == 'closed' + uses: actions-ecosystem/action-remove-labels@v1 with: - github_token: ${{ secrets.OMNISHARP_BOT_TOKEN }} - config_file: .github/label-commenter-dependabot.yml + labels: | + :shipit: merge + github-actions + javascript + .NET diff --git a/.github/workflows/draft-release.yml b/.github/workflows/draft-release.yml index 315e6f01b..21d01ef67 100644 --- a/.github/workflows/draft-release.yml +++ b/.github/workflows/draft-release.yml @@ -1,16 +1,20 @@ name: Create Milestone and Draft Release + on: push: branches: - master paths-ignore: - '**/*.md' + schedule: + - cron: '0 0 * * 4' + jobs: create_milestone_and_draft_release: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v2.3.4 + uses: actions/checkout@v3.0.2 with: fetch-depth: 0 @@ -18,18 +22,13 @@ jobs: run: git fetch --prune - name: Install GitVersion - uses: gittools/actions/gitversion/setup@v0.9.10 + uses: gittools/actions/gitversion/setup@v0.9.13 with: versionSpec: '5.x' - - name: Install GitReleaseManager - uses: gittools/actions/gitreleasemanager/setup@v0.9.10 - with: - versionSpec: '0.12.x' - - name: Use GitVersion id: gitversion - uses: gittools/actions/gitversion/execute@v0.9.10 + uses: gittools/actions/gitversion/execute@v0.9.13 - name: Create Milestone uses: WyriHaximus/github-action-create-milestone@v1 @@ -39,34 +38,19 @@ jobs: GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' continue-on-error: true - - name: Get Repo and Owner - shell: pwsh - id: repository - run: | - $parts = $ENV:GITHUB_REPOSITORY.Split('/') - echo "::set-output name=owner::$($parts[0])" - echo "::set-output name=repository::$($parts[1])" - - name: sync milestones - uses: RocketSurgeonsGuild/actions/sync-milestone@v0.2.4 + uses: RocketSurgeonsGuild/actions/sync-milestone@v0.3.1 with: default-label: 'mysterious' github-token: ${{ secrets.GITHUB_TOKEN }} - - name: Create Draft Release - shell: pwsh - run: | - dotnet gitreleasemanager create ` - -o "${{ steps.repository.outputs.owner }}" ` - -r "${{ steps.repository.outputs.repository }}" ` - --token "${{ secrets.OMNISHARP_BOT_TOKEN }}" ` - -m "v${{ steps.gitversion.outputs.majorMinorPatch }}" - - - name: Export Changelog - shell: pwsh - run: | - dotnet gitreleasemanager export ` - -o "${{ steps.repository.outputs.owner }}" ` - -r "${{ steps.repository.outputs.repository }}" ` - --token "${{ secrets.GITHUB_TOKEN }}" ` - -f CHANGELOG.md + - uses: ncipollo/release-action@v1 + with: + allowUpdates: true + generateReleaseNotes: true + draft: true + omitNameDuringUpdate: true + name: 'v${{ steps.gitversion.outputs.majorMinorPatch }}' + tag: 'v${{ steps.gitversion.outputs.majorMinorPatch }}' + token: ${{ secrets.OMNISHARP_BOT_TOKEN }} + commit: ${{ github.base_ref }} diff --git a/.github/workflows/publish-nuget.yml b/.github/workflows/publish-nuget.yml new file mode 100644 index 000000000..586ed7dd5 --- /dev/null +++ b/.github/workflows/publish-nuget.yml @@ -0,0 +1,38 @@ +name: Publish Nuget Packages + +on: + workflow_call: + # inputs: + secrets: + RSG_NUGET_API_KEY: + required: true + RSG_AZURE_DEVOPS: + required: false + +jobs: + publish: + runs-on: ubuntu-latest + + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + + - uses: nuget/setup-nuget@v1 + with: + nuget-version: '5.x' + + - uses: actions/download-artifact@v3 + with: + name: nuget + + - name: nuget.org + # continue-on-error: true + if: startsWith(github.ref, 'refs/tags/') # this is the best approximation for a tag + env: + ApiKey: ${{ secrets.RSG_NUGET_API_KEY }} + shell: pwsh + run: | + dotnet nuget push **/*.nupkg --skip-duplicate -s nuget.org --api-key $ENV:ApiKey + dotnet nuget push **/*.snupkg --skip-duplicate -s nuget.org --api-key $ENV:ApiKey diff --git a/.github/workflows/sync-labels.yml b/.github/workflows/sync-labels.yml index c6ec4b475..f1710e13b 100644 --- a/.github/workflows/sync-labels.yml +++ b/.github/workflows/sync-labels.yml @@ -1,5 +1,7 @@ name: Sync Labels + on: + workflow_call: push: branches: - master @@ -14,14 +16,13 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v2.3.4 + uses: actions/checkout@v3.0.2 - name: Run Labeler if: success() uses: crazy-max/ghaction-github-labeler@v3.1.1 with: - yaml_file: .github/labels.yml - skip_delete: false - dry_run: false - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + yaml-file: .github/labels.yml + skip-delete: false + dry-run: false + github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/update-milestone.yml b/.github/workflows/update-milestone.yml index 120c6e1c8..118cc29c5 100644 --- a/.github/workflows/update-milestone.yml +++ b/.github/workflows/update-milestone.yml @@ -1,4 +1,5 @@ name: Update Milestone + on: pull_request_target: types: @@ -12,10 +13,42 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v2.3.4 + uses: actions/checkout@v3.0.2 + with: + ref: ${{ github.sha }} + fetch-depth: 0 + + - name: Fetch all history for all tags and branches + run: git fetch --prune + + - name: Install GitVersion + if: ${{ github.event.action == 'opened' }} + uses: gittools/actions/gitversion/setup@v0.9.13 + with: + versionSpec: '5.x' + + - name: Install GitReleaseManager + if: ${{ github.event.action == 'opened' }} + uses: gittools/actions/gitreleasemanager/setup@v0.9.13 + with: + versionSpec: '0.11.x' + + - name: Use GitVersion + if: ${{ github.event.action == 'opened' }} + id: gitversion + uses: gittools/actions/gitversion/execute@v0.9.13 + + - name: Create Milestone + if: ${{ github.event.action == 'opened' }} + uses: WyriHaximus/github-action-create-milestone@v1 + with: + title: v${{ steps.gitversion.outputs.majorMinorPatch }} + env: + GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' + continue-on-error: true - name: sync milestones - uses: RocketSurgeonsGuild/actions/sync-milestone@v0.2.4 + uses: RocketSurgeonsGuild/actions/sync-milestone@v0.3.1 with: default-label: 'mysterious' github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index 97caab569..f2f6f24b6 100644 --- a/.gitignore +++ b/.gitignore @@ -45,3 +45,4 @@ coverage.json coverage.info /codealike.json .tmp/ +.nuke/temp/ diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 000000000..3f6421029 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,9 @@ +#!/bin/sh +. "$(dirname "$0")/_/husky.sh" + +npx lint-staged -d -r +dotnet nuke --generate-configuration GitHubActions_ci --host GitHubActions +dotnet nuke --generate-configuration GitHubActions_ci-ignore --host GitHubActions +git add .github/workflows/ci.yml +git add .github/workflows/ci-ignore.yml +git add .nuke/build.schema.json diff --git a/.huskyrc b/.huskyrc deleted file mode 100644 index 80f5453bb..000000000 --- a/.huskyrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "hooks": { - "pre-commit": "lint-staged" - } -} \ No newline at end of file diff --git a/.lintstagedrc b/.lintstagedrc deleted file mode 100644 index 3dff2b2fb..000000000 --- a/.lintstagedrc +++ /dev/null @@ -1,8 +0,0 @@ -{ - "*.{cs,vb}": [ - "dotnet nuke lint --no-logo --lint-files" - ], - "*.{js,ts,jsx,tsx,json,yml,yaml}": [ - "prettier --write" - ] -} diff --git a/.lintstagedrc.js b/.lintstagedrc.js new file mode 100644 index 000000000..0e6af2f49 --- /dev/null +++ b/.lintstagedrc.js @@ -0,0 +1,26 @@ +function forEachChunk(chunks, callback, chunkSize = 50) { + var mappedFiles = []; + var files = chunks.concat(); + while (files.length > 0) { + var chunk = files.splice(0, chunkSize); + mappedFiles = mappedFiles.concat(callback(chunk)); + } + return mappedFiles; +} + +function cleanupcode(filenames) { + var sln = require('./.nuke/parameters.json').Solution; + return forEachChunk(filenames, chunk => [ + `dotnet jb cleanupcode ${sln} "--profile=Full Cleanup" "--disable-settings-layers=GlobalAll;GlobalPerProduct;SolutionPersonal;ProjectPersonal" "--include=${chunk.join( + ';' + )}"`, + ]); +} + +module.exports = { + '*.cs': 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(`' '`)}'`]), +}; diff --git a/.mergify.yml b/.mergify.yml deleted file mode 100644 index f8cd7f329..000000000 --- a/.mergify.yml +++ /dev/null @@ -1,101 +0,0 @@ -pull_request_rules: - - name: automatic merge when GitHub branch protection passes (others) - conditions: - - base=master - - -author~=^dependabot(|-preview)\[bot\]$ - - 'label=merge' - actions: - merge: - method: squash - strict: smart+fasttrack - - name: automatic merge when GitHub branch protection passes - conditions: - - merged - - 'label=merge' - actions: - label: - remove: - - 'merge' - - name: delete head branch after merge - conditions: - - merged - actions: - label: - remove: - - 'merge' - - 'github-actions' - - 'javascript' - - '.NET' - delete_head_branch: {} - - name: automatic merge for JetBrains.ReSharper.CommandLineTools pull requests - conditions: - - title~=^Bump JetBrains\.ReSharper\.CommandLineTools.*$ - - author~=^dependabot(|-preview)\[bot\]$ - actions: - label: - add: - - 'merge' - - name: automatic merge for ReportGenerator pull requests - conditions: - - title~=^Bump ReportGenerator.*$ - - author~=^dependabot(|-preview)\[bot\]$ - actions: - label: - add: - - 'merge' - - name: automatic merge for GitVersion.Tool pull requests - conditions: - - title~=^Bump GitVersion\.Tool.*$ - - author~=^dependabot(|-preview)\[bot\]$ - actions: - label: - add: - - 'merge' - - name: automatic merge for Bogus pull requests - conditions: - - title~=^Bump Bogus.*$ - - author~=^dependabot(|-preview)\[bot\]$ - actions: - label: - add: - - 'merge' - - name: automatic merge for coverlet pull requests - conditions: - - title~=^Bump coverlet.*$ - - author~=^dependabot(|-preview)\[bot\]$ - actions: - label: - add: - - 'merge' - - name: automatic merge for FakeItEasy pull requests - conditions: - - title~=^Bump FakeItEasy.*$ - - author~=^dependabot(|-preview)\[bot\]$ - actions: - label: - add: - - 'merge' - - name: automatic merge for FluentAssertions pull requests - conditions: - - title~=^Bump FluentAssertions.*$ - - author~=^dependabot(|-preview)\[bot\]$ - actions: - label: - add: - - 'merge' - - name: automatic merge for xunit pull requests - conditions: - - title~=^Bump xunit.*$ - - author~=^dependabot(|-preview)\[bot\]$ - actions: - label: - add: - - 'merge' - - name: automatic merge for Microsoft.NET.Test.Sdk pull requests - conditions: - - title~=^Bump Microsoft\.NET\.Test\.Sdk.*$ - - author~=^dependabot(|-preview)\[bot\]$ - actions: - label: - add: - - 'merge' diff --git a/.nuke b/.nuke deleted file mode 100644 index d1bf89faf..000000000 --- a/.nuke +++ /dev/null @@ -1,2 +0,0 @@ -LSP.sln - diff --git a/.nuke/build.schema.json b/.nuke/build.schema.json new file mode 100644 index 000000000..f99d257e6 --- /dev/null +++ b/.nuke/build.schema.json @@ -0,0 +1,157 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "Build Schema", + "$ref": "#/definitions/build", + "definitions": { + "build": { + "type": "object", + "properties": { + "Artifacts": { + "type": "string", + "description": "The directory where artifacts are to be dropped" + }, + "Configuration": { + "type": "string", + "description": "Configuration to build", + "enum": [ + "Debug", + "Release" + ] + }, + "Continue": { + "type": "boolean", + "description": "Indicates to continue a previously failed build attempt" + }, + "Coverage": { + "type": "string", + "description": "The directory where coverage artifacts are to be dropped" + }, + "Help": { + "type": "boolean", + "description": "Shows the help text for this build assembly" + }, + "Host": { + "type": "string", + "description": "Host for execution. Default is 'automatic'", + "enum": [ + "AppVeyor", + "AzurePipelines", + "Bamboo", + "Bitrise", + "GitHubActions", + "GitLab", + "Jenkins", + "Rider", + "SpaceAutomation", + "TeamCity", + "Terminal", + "TravisCI", + "VisualStudio", + "VSCode" + ] + }, + "NoLogo": { + "type": "boolean", + "description": "Disables displaying the NUKE logo" + }, + "Partition": { + "type": "string", + "description": "Partition to use on CI" + }, + "Plan": { + "type": "boolean", + "description": "Shows the execution plan (HTML)" + }, + "Profile": { + "type": "array", + "description": "Defines the profiles to load", + "items": { + "type": "string" + } + }, + "Root": { + "type": "string", + "description": "Root directory during build execution" + }, + "Skip": { + "type": "array", + "description": "List of targets to be skipped. Empty list skips all dependencies", + "items": { + "type": "string", + "enum": [ + "Build", + "BuildVersion", + "Clean", + "CoreBuild", + "CorePack", + "CoreRestore", + "CoreTest", + "Default", + "DotnetToolRestore", + "Generate_Code_Coverage_Badges", + "Generate_Code_Coverage_Report", + "Generate_Code_Coverage_Report_Cobertura", + "Generate_Code_Coverage_Summary", + "GenerateCodeCoverageBadges", + "GenerateCodeCoverageReport", + "GenerateCodeCoverageReportCobertura", + "GenerateCodeCoverageSummary", + "GenerateReadme", + "Pack", + "Restore", + "Test", + "Trigger_Code_Coverage_Reports", + "TriggerCodeCoverageReports" + ] + } + }, + "Solution": { + "type": "string", + "description": "Path to a solution file that is automatically loaded" + }, + "Target": { + "type": "array", + "description": "List of targets to be invoked. Default is '{default_target}'", + "items": { + "type": "string", + "enum": [ + "Build", + "BuildVersion", + "Clean", + "CoreBuild", + "CorePack", + "CoreRestore", + "CoreTest", + "Default", + "DotnetToolRestore", + "Generate_Code_Coverage_Badges", + "Generate_Code_Coverage_Report", + "Generate_Code_Coverage_Report_Cobertura", + "Generate_Code_Coverage_Summary", + "GenerateCodeCoverageBadges", + "GenerateCodeCoverageReport", + "GenerateCodeCoverageReportCobertura", + "GenerateCodeCoverageSummary", + "GenerateReadme", + "Pack", + "Restore", + "Test", + "Trigger_Code_Coverage_Reports", + "TriggerCodeCoverageReports" + ] + } + }, + "Verbosity": { + "type": "string", + "description": "Logging verbosity during build execution. Default is 'Normal'", + "enum": [ + "Minimal", + "Normal", + "Quiet", + "Verbose" + ] + } + } + } + } +} \ No newline at end of file diff --git a/.nuke/parameters.json b/.nuke/parameters.json new file mode 100644 index 000000000..2d4a451b6 --- /dev/null +++ b/.nuke/parameters.json @@ -0,0 +1,4 @@ +{ + "$schema": "./build.schema.json", + "Solution": "LSP.sln" +} \ No newline at end of file diff --git a/.prettierignore b/.prettierignore index 2faf38352..33227515d 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,2 +1,4 @@ azure-pipelines.nuke.yml .github/workflows/ci.yml +.github/workflows/ci-ignore.yml +.nuke/build.schema.json diff --git a/Directory.Build.props b/Directory.Build.props index 2b19c9ec0..c824ab2bf 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -14,21 +14,34 @@ lsp;language server;language server protocol;language client;language server client $(MSBuildThisFileDirectory)\lsp.snk + AllEnabledByDefault + preview + true true + 1 + true + enable true true snupkg true - $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb $(AllowedReferenceRelatedFileExtensions);.pdb true - + diff --git a/Directory.Build.targets b/Directory.Build.targets index 90a5f37bb..4cc7c05d3 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,53 +1,12 @@ - - - - $(BaseIntermediateOutputPath)\GeneratedFiles - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + $(BaseIntermediateOutputPath)\GeneratedFiles + + + + + + + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 000000000..6916daa35 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,63 @@ + + + + $(BaseIntermediateOutputPath)\GeneratedFiles + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Directory.Packages.supports.props b/Directory.Packages.supports.props new file mode 100644 index 000000000..665086a69 --- /dev/null +++ b/Directory.Packages.supports.props @@ -0,0 +1,15 @@ + + + + + + + + + + + + + diff --git a/LSP.sln b/LSP.sln index 7ca6d6531..68d6c34bf 100644 --- a/LSP.sln +++ b/LSP.sln @@ -12,6 +12,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{2F323ED5-E ProjectSection(SolutionItems) = preProject test\Directory.Build.props = test\Directory.Build.props test\Directory.Build.targets = test\Directory.Build.targets + test\.editorconfig = test\.editorconfig EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".config", ".config", "{AE4D7807-6F78-428C-A0D9-914BA583A104}" @@ -25,6 +26,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".config", ".config", "{AE4D Directory.Build.props = Directory.Build.props nuget.config = nuget.config Directory.Build.targets = Directory.Build.targets + Directory.Packages.props = Directory.Packages.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JsonRpc", "src\JsonRpc\JsonRpc.csproj", "{9AF43FA2-EF35-435E-B59E-724877E44DDA}" diff --git a/azure-pipelines.nuke.yml b/azure-pipelines.nuke.yml index 633418b1c..308824ac0 100644 --- a/azure-pipelines.nuke.yml +++ b/azure-pipelines.nuke.yml @@ -23,7 +23,7 @@ parameters: steps: - pwsh: dotnet nuke Build --skip --artifacts '${{ parameters.Artifacts }}' --coverage '${{ parameters.Coverage }}' --configuration '${{ parameters.Configuration }}' --verbosity '${{ parameters.Verbosity }}' displayName: '⚙ Build' - - pwsh: dotnet nuke Test Trigger_Code_Coverage_Reports Generate_Code_Coverage_Report_Cobertura Generate_Code_Coverage_Badges Generate_Code_Coverage_Summary Generate_Code_Coverage_Report --skip --artifacts '${{ parameters.Artifacts }}' --coverage '${{ parameters.Coverage }}' --configuration '${{ parameters.Configuration }}' --verbosity '${{ parameters.Verbosity }}' + - pwsh: dotnet nuke Test TriggerCodeCoverageReports GenerateCodeCoverageReportCobertura GenerateCodeCoverageBadges GenerateCodeCoverageSummary GenerateCodeCoverageReport --skip --artifacts '${{ parameters.Artifacts }}' --coverage '${{ parameters.Coverage }}' --configuration '${{ parameters.Configuration }}' --verbosity '${{ parameters.Verbosity }}' displayName: '🚦 Test' - pwsh: dotnet nuke Pack --skip --artifacts '${{ parameters.Artifacts }}' --coverage '${{ parameters.Coverage }}' --configuration '${{ parameters.Configuration }}' --verbosity '${{ parameters.Verbosity }}' displayName: '📦 Pack' diff --git a/benchmarks/Pipeline/Pipeline.csproj b/benchmarks/Pipeline/Pipeline.csproj index 15cca63e3..c20468ddb 100644 --- a/benchmarks/Pipeline/Pipeline.csproj +++ b/benchmarks/Pipeline/Pipeline.csproj @@ -1,15 +1,14 @@ - net472;netcoreapp3.1 + net472;netcoreapp3.1;net6.0 Exe false - - + diff --git a/build.cmd b/build.cmd new file mode 100755 index 000000000..b08cc590f --- /dev/null +++ b/build.cmd @@ -0,0 +1,7 @@ +:; set -eo pipefail +:; SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd) +:; ${SCRIPT_DIR}/build.sh "$@" +:; exit $? + +@ECHO OFF +powershell -ExecutionPolicy ByPass -NoProfile -File "%~dp0build.ps1" %* diff --git a/build.ps1 b/build.ps1 index 91f068d7d..9f908eb3d 100644 --- a/build.ps1 +++ b/build.ps1 @@ -4,9 +4,9 @@ Param( [string[]]$BuildArguments ) -Write-Output "Windows PowerShell $($Host.Version)" +Write-Output "PowerShell $($PSVersionTable.PSEdition) version $($PSVersionTable.PSVersion)" -Set-StrictMode -Version 2.0; $ErrorActionPreference = "Stop"; $ConfirmPreference = "None"; trap { exit 1 } +Set-StrictMode -Version 2.0; $ErrorActionPreference = "Stop"; $ConfirmPreference = "None"; trap { Write-Error $_ -ErrorAction Continue; exit 1 } $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent ########################################################################### @@ -14,14 +14,15 @@ $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent ########################################################################### $BuildProjectFile = "$PSScriptRoot\.build\.build.csproj" -$TempDirectory = "$PSScriptRoot\\.tmp" +$TempDirectory = "$PSScriptRoot\\.nuke\temp" $DotNetGlobalFile = "$PSScriptRoot\\global.json" -$DotNetInstallUrl = "https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain/dotnet-install.ps1" +$DotNetInstallUrl = "https://dot.net/v1/dotnet-install.ps1" $DotNetChannel = "Current" $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = 1 $env:DOTNET_CLI_TELEMETRY_OPTOUT = 1 +$env:DOTNET_MULTILEVEL_LOOKUP = 0 ########################################################################### # EXECUTION @@ -32,37 +33,37 @@ function ExecSafe([scriptblock] $cmd) { if ($LASTEXITCODE) { exit $LASTEXITCODE } } -# If global.json exists, load expected version -if (Test-Path $DotNetGlobalFile) { - $DotNetGlobal = $(Get-Content $DotNetGlobalFile | Out-String | ConvertFrom-Json) - if ($DotNetGlobal.PSObject.Properties["sdk"] -and $DotNetGlobal.sdk.PSObject.Properties["version"]) { - $DotNetVersion = $DotNetGlobal.sdk.version - } -} - -# If dotnet is installed locally, and expected version is not set or installation matches the expected version -if ((Get-Command "dotnet" -ErrorAction SilentlyContinue) -ne $null -and ` - (!(Test-Path variable:DotNetVersion) -or $(& dotnet --version) -eq $DotNetVersion)) { +# If dotnet CLI is installed globally and it matches requested version, use for execution +if ($null -ne (Get-Command "dotnet" -ErrorAction SilentlyContinue) -and ` + $(dotnet --version) -and $LASTEXITCODE -eq 0) { $env:DOTNET_EXE = (Get-Command "dotnet").Path } else { - $DotNetDirectory = "$TempDirectory\dotnet-win" - $env:DOTNET_EXE = "$DotNetDirectory\dotnet.exe" - # Download install script $DotNetInstallFile = "$TempDirectory\dotnet-install.ps1" - md -force $TempDirectory > $null + New-Item -ItemType Directory -Path $TempDirectory -Force | Out-Null + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 (New-Object System.Net.WebClient).DownloadFile($DotNetInstallUrl, $DotNetInstallFile) + # If global.json exists, load expected version + if (Test-Path $DotNetGlobalFile) { + $DotNetGlobal = $(Get-Content $DotNetGlobalFile | Out-String | ConvertFrom-Json) + if ($DotNetGlobal.PSObject.Properties["sdk"] -and $DotNetGlobal.sdk.PSObject.Properties["version"]) { + $DotNetVersion = $DotNetGlobal.sdk.version + } + } + # Install by channel or version + $DotNetDirectory = "$TempDirectory\dotnet-win" if (!(Test-Path variable:DotNetVersion)) { - ExecSafe { & $DotNetInstallFile -InstallDir $DotNetDirectory -Channel $DotNetChannel -NoPath } + ExecSafe { & powershell $DotNetInstallFile -InstallDir $DotNetDirectory -Channel $DotNetChannel -NoPath } } else { - ExecSafe { & $DotNetInstallFile -InstallDir $DotNetDirectory -Version $DotNetVersion -NoPath } + ExecSafe { & powershell $DotNetInstallFile -InstallDir $DotNetDirectory -Version $DotNetVersion -NoPath } } + $env:DOTNET_EXE = "$DotNetDirectory\dotnet.exe" } Write-Output "Microsoft (R) .NET Core SDK version $(& $env:DOTNET_EXE --version)" -ExecSafe { & $env:DOTNET_EXE build $BuildProjectFile /nodeReuse:false } +ExecSafe { & $env:DOTNET_EXE build $BuildProjectFile /nodeReuse:false /p:UseSharedCompilation=false -nologo -clp:NoSummary --verbosity quiet } ExecSafe { & $env:DOTNET_EXE run --project $BuildProjectFile --no-build -- $BuildArguments } diff --git a/build.sh b/build.sh index 25b34f4c2..75f7d9930 100755 --- a/build.sh +++ b/build.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -echo $(bash --version 2>&1 | head -n 1) +bash --version 2>&1 | head -n 1 set -eo pipefail SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd) @@ -10,53 +10,53 @@ SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd) ########################################################################### BUILD_PROJECT_FILE="$SCRIPT_DIR/.build/.build.csproj" -TEMP_DIRECTORY="$SCRIPT_DIR//.tmp" +TEMP_DIRECTORY="$SCRIPT_DIR//.nuke/temp" DOTNET_GLOBAL_FILE="$SCRIPT_DIR//global.json" -DOTNET_INSTALL_URL="https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain/dotnet-install.sh" +DOTNET_INSTALL_URL="https://dot.net/v1/dotnet-install.sh" DOTNET_CHANNEL="Current" export DOTNET_CLI_TELEMETRY_OPTOUT=1 export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 +export DOTNET_MULTILEVEL_LOOKUP=0 ########################################################################### # EXECUTION ########################################################################### function FirstJsonValue { - perl -nle 'print $1 if m{"'$1'": "([^"\-]+)",?}' <<< ${@:2} + perl -nle 'print $1 if m{"'"$1"'": "([^"]+)",?}' <<< "${@:2}" } -# If global.json exists, load expected version -if [ -f "$DOTNET_GLOBAL_FILE" ]; then - DOTNET_VERSION=$(FirstJsonValue "version" $(cat "$DOTNET_GLOBAL_FILE")) - if [ "$DOTNET_VERSION" == "" ]; then - unset DOTNET_VERSION - fi -fi - -# If dotnet is installed locally, and expected version is not set or installation matches the expected version -if [[ -x "$(command -v dotnet)" && (-z ${DOTNET_VERSION+x} || $(dotnet --version) == "$DOTNET_VERSION") ]]; then +# If dotnet CLI is installed globally and it matches requested version, use for execution +if [ -x "$(command -v dotnet)" ] && dotnet --version &>/dev/null; then export DOTNET_EXE="$(command -v dotnet)" else - DOTNET_DIRECTORY="$TEMP_DIRECTORY/dotnet-unix" - export DOTNET_EXE="$DOTNET_DIRECTORY/dotnet" - # Download install script DOTNET_INSTALL_FILE="$TEMP_DIRECTORY/dotnet-install.sh" mkdir -p "$TEMP_DIRECTORY" curl -Lsfo "$DOTNET_INSTALL_FILE" "$DOTNET_INSTALL_URL" chmod +x "$DOTNET_INSTALL_FILE" + # If global.json exists, load expected version + if [[ -f "$DOTNET_GLOBAL_FILE" ]]; then + DOTNET_VERSION=$(FirstJsonValue "version" "$(cat "$DOTNET_GLOBAL_FILE")") + if [[ "$DOTNET_VERSION" == "" ]]; then + unset DOTNET_VERSION + fi + fi + # Install by channel or version - if [ -z ${DOTNET_VERSION+x} ]; then + DOTNET_DIRECTORY="$TEMP_DIRECTORY/dotnet-unix" + if [[ -z ${DOTNET_VERSION+x} ]]; then "$DOTNET_INSTALL_FILE" --install-dir "$DOTNET_DIRECTORY" --channel "$DOTNET_CHANNEL" --no-path else "$DOTNET_INSTALL_FILE" --install-dir "$DOTNET_DIRECTORY" --version "$DOTNET_VERSION" --no-path fi + export DOTNET_EXE="$DOTNET_DIRECTORY/dotnet" fi echo "Microsoft (R) .NET Core SDK version $("$DOTNET_EXE" --version)" -"$DOTNET_EXE" build "$BUILD_PROJECT_FILE" /nodeReuse:false +"$DOTNET_EXE" build "$BUILD_PROJECT_FILE" /nodeReuse:false /p:UseSharedCompilation=false -nologo -clp:NoSummary --verbosity quiet "$DOTNET_EXE" run --project "$BUILD_PROJECT_FILE" --no-build -- "$@" diff --git a/docs/lsp.md b/docs/lsp.md index 305ad1f2b..49267c860 100644 --- a/docs/lsp.md +++ b/docs/lsp.md @@ -5,7 +5,7 @@ The goal of this library is to implement [Language Server Protocol](https://micr Included in this library is a full-fidelity `LanguageServer` but also full `LanguageClient` implementation that could be implemented in an editor, but mainly it is used to help make Unit Testing easier, more consistent (and maybe even fun!). # Concepts -The language server is built oin a few concepts. At it's core is the [MediatR](https://github.com/jbogard/MediatR) library that you will build language specific handlers around. Around that core is a bunch of knowledge of the LSP protocol +The language server is built on a few concepts. At it's core is the [MediatR](https://github.com/jbogard/MediatR) library that you will build language specific handlers around. Around that core is a bunch of knowledge of the LSP protocol with the goal of making it more ".NET" like and less protocol centric. LSP revolves around features ( eg Completion, Hover, etc ) that define the inputs (request object) the outputs (response object) as well as Client Capabilities and Server Registration Options. diff --git a/global.json b/global.json new file mode 100644 index 000000000..4fda00640 --- /dev/null +++ b/global.json @@ -0,0 +1,6 @@ +{ + "sdk": { + "version": "6.0.200", + "rollForward": "latestMinor" + } +} diff --git a/package-lock.json b/package-lock.json index c5e6bd47e..e560ad123 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2,90 +2,25 @@ "requires": true, "lockfileVersion": 1, "dependencies": { - "@babel/code-frame": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.14.5.tgz", - "integrity": "sha512-9pzDqyc6OLDaqe+zbACgFkb6fKMNG6CObKpnYXChRsvYGyEdc7CA2BaqeOM+vOtCS5ndmJicPJhKAwYRI6UfFw==", + "@prettier/plugin-xml": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@prettier/plugin-xml/-/plugin-xml-1.2.0.tgz", + "integrity": "sha512-bFvVAZKs59XNmntYjyefn3K4TBykS6E+d6ZW8IcylAs88ZO+TzLhp0dPpi0VKfPzq1Nb+kpDnPRTiwb4zY6NgA==", "dev": true, "requires": { - "@babel/highlight": "^7.14.5" + "@xml-tools/parser": "^1.0.11", + "prettier": ">=2.3" } }, - "@babel/helper-validator-identifier": { - "version": "7.14.9", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.9.tgz", - "integrity": "sha512-pQYxPY0UP6IHISRitNe8bsijHex4TWZXi2HwKVsjPiltzlhse2znVcm9Ace510VT1kxIHjGJCZZQBX2gJDbo0g==", - "dev": true - }, - "@babel/highlight": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.14.5.tgz", - "integrity": "sha512-qf9u2WFWVV0MppaL877j2dBtQIDgmidgjGk5VIMw3OadXvYaXn66U1BFlH2t4+t3i+8PhedppRv+i40ABzd+gg==", + "@xml-tools/parser": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@xml-tools/parser/-/parser-1.0.11.tgz", + "integrity": "sha512-aKqQ077XnR+oQtHJlrAflaZaL7qZsulWc/i/ZEooar5JiWj1eLt0+Wg28cpa+XLney107wXqneC+oG1IZvxkTA==", "dev": true, "requires": { - "@babel/helper-validator-identifier": "^7.14.5", - "chalk": "^2.0.0", - "js-tokens": "^4.0.0" - }, - "dependencies": { - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "requires": { - "color-convert": "^1.9.0" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", - "dev": true - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } + "chevrotain": "7.1.1" } }, - "@types/parse-json": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz", - "integrity": "sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA==", - "dev": true - }, "aggregate-error": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", @@ -96,12 +31,6 @@ "indent-string": "^4.0.0" } }, - "ansi-colors": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", - "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", - "dev": true - }, "ansi-escapes": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", @@ -112,19 +41,16 @@ } }, "ansi-regex": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", - "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", "dev": true }, "ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "requires": { - "color-convert": "^2.0.1" - } + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.1.0.tgz", + "integrity": "sha512-VbqNsoz55SYGczauuup0MFUyXNQviSpFTj1RQtFzmQLk18qbVSpTFFGMT293rmDaQuKCT6InmbuEyUne4mTuxQ==", + "dev": true }, "astral-regex": { "version": "2.0.0", @@ -141,20 +67,13 @@ "fill-range": "^7.0.1" } }, - "callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true - }, - "chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "chevrotain": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-7.1.1.tgz", + "integrity": "sha512-wy3mC1x4ye+O+QkEinVJkPf5u2vsrDIYW9G7ZuwFl6v/Yu0LwUuT2POsb+NUWApebyxfkQq6+yDfRExbnI5rcw==", "dev": true, "requires": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" + "regexp-to-ast": "0.5.0" } }, "clean-stack": { @@ -173,13 +92,13 @@ } }, "cli-truncate": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz", - "integrity": "sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-3.1.0.tgz", + "integrity": "sha512-wfOBkjXteqSnI59oPcJkcPl/ZmwvMMOj340qUIY1SKZCv0B9Cf4D4fAucRkIKQmsIuYK3x1rrgU7MeGRruiuiA==", "dev": true, "requires": { - "slice-ansi": "^3.0.0", - "string-width": "^4.2.0" + "slice-ansi": "^5.0.0", + "string-width": "^5.0.0" } }, "color-convert": { @@ -198,30 +117,17 @@ "dev": true }, "colorette": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.2.2.tgz", - "integrity": "sha512-MKGMzyfeuutC/ZJ1cba9NqcNpfeqMUcYmyF1ZFY6/Cn7CNSAKx6a+s48sqLqyAiZuaP2TcqMhoo+dlwFnVxT9w==", + "version": "2.0.16", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.16.tgz", + "integrity": "sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g==", "dev": true }, "commander": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", - "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz", + "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==", "dev": true }, - "cosmiconfig": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.0.0.tgz", - "integrity": "sha512-pondGvTuVYDk++upghXJabWzL6Kxu6f26ljFw64Swq9v6sQPUL3EUlVDV56diOjpCayKihL6hVe8exIACU4XcA==", - "dev": true, - "requires": { - "@types/parse-json": "^4.0.0", - "import-fresh": "^3.2.1", - "parse-json": "^5.0.0", - "path-type": "^4.0.0", - "yaml": "^1.10.0" - } - }, "cross-spawn": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", @@ -234,42 +140,24 @@ } }, "debug": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", - "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz", + "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", "dev": true, "requires": { "ms": "2.1.2" } }, - "emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", "dev": true }, - "enquirer": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz", - "integrity": "sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==", - "dev": true, - "requires": { - "ansi-colors": "^4.1.1" - } - }, - "error-ex": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", - "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", - "dev": true, - "requires": { - "is-arrayish": "^0.2.1" - } - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", "dev": true }, "execa": { @@ -298,24 +186,12 @@ "to-regex-range": "^5.0.1" } }, - "get-own-enumerable-property-symbols": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz", - "integrity": "sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g==", - "dev": true - }, "get-stream": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", "dev": true }, - "has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true - }, "human-signals": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", @@ -323,37 +199,21 @@ "dev": true }, "husky": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/husky/-/husky-7.0.2.tgz", - "integrity": "sha512-8yKEWNX4z2YsofXAMT7KvA1g8p+GxtB1ffV8XtpAEGuXNAbCV5wdNKH+qTpw8SM9fh4aMPDR+yQuKfgnreyZlg==", + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/husky/-/husky-7.0.4.tgz", + "integrity": "sha512-vbaCKN2QLtP/vD4yvs6iz6hBEo6wkSzs8HpRah1Z6aGmF2KW5PdYuAd7uX5a+OyBZHBhd+TFLqgjUgytQr4RvQ==", "dev": true }, - "import-fresh": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", - "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", - "dev": true, - "requires": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - } - }, "indent-string": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", "dev": true }, - "is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", - "dev": true - }, "is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz", + "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==", "dev": true }, "is-number": { @@ -362,99 +222,129 @@ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "dev": true }, - "is-obj": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", - "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=", - "dev": true - }, - "is-regexp": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-regexp/-/is-regexp-1.0.0.tgz", - "integrity": "sha1-/S2INUXEa6xaYz57mgnof6LLUGk=", - "dev": true - }, "is-stream": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", "dev": true }, - "is-unicode-supported": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", - "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", - "dev": true - }, "isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", "dev": true }, - "js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true - }, - "json-parse-even-better-errors": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true - }, - "lines-and-columns": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz", - "integrity": "sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA=", + "lilconfig": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-2.0.4.tgz", + "integrity": "sha512-bfTIN7lEsiooCocSISTWXkiWJkRqtL9wYtYy+8EK3Y41qh3mpwPU0ycTOgjdY9ErwXCc8QyrQp82bdL0Xkm9yA==", "dev": true }, "lint-staged": { - "version": "11.1.2", - "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-11.1.2.tgz", - "integrity": "sha512-6lYpNoA9wGqkL6Hew/4n1H6lRqF3qCsujVT0Oq5Z4hiSAM7S6NksPJ3gnr7A7R52xCtiZMcEUNNQ6d6X5Bvh9w==", - "dev": true, - "requires": { - "chalk": "^4.1.1", - "cli-truncate": "^2.1.0", - "commander": "^7.2.0", - "cosmiconfig": "^7.0.0", - "debug": "^4.3.1", - "enquirer": "^2.3.6", - "execa": "^5.0.0", - "listr2": "^3.8.2", - "log-symbols": "^4.1.0", + "version": "12.3.4", + "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-12.3.4.tgz", + "integrity": "sha512-yv/iK4WwZ7/v0GtVkNb3R82pdL9M+ScpIbJLJNyCXkJ1FGaXvRCOg/SeL59SZtPpqZhE7BD6kPKFLIDUhDx2/w==", + "dev": true, + "requires": { + "cli-truncate": "^3.1.0", + "colorette": "^2.0.16", + "commander": "^8.3.0", + "debug": "^4.3.3", + "execa": "^5.1.1", + "lilconfig": "2.0.4", + "listr2": "^4.0.1", "micromatch": "^4.0.4", "normalize-path": "^3.0.0", - "please-upgrade-node": "^3.2.0", - "string-argv": "0.3.1", - "stringify-object": "^3.3.0" + "object-inspect": "^1.12.0", + "string-argv": "^0.3.1", + "supports-color": "^9.2.1", + "yaml": "^1.10.2" } }, "listr2": { - "version": "3.11.0", - "resolved": "https://registry.npmjs.org/listr2/-/listr2-3.11.0.tgz", - "integrity": "sha512-XLJVe2JgXCyQTa3FbSv11lkKExYmEyA4jltVo8z4FX10Vt1Yj8IMekBfwim0BSOM9uj1QMTJvDQQpHyuPbB/dQ==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/listr2/-/listr2-4.0.4.tgz", + "integrity": "sha512-vJOm5KD6uZXjSsrwajr+mNacIjf87gWvlBEltPWLbTkslUscWAzquyK4xfe9Zd4RDgO5nnwFyV06FC+uVR+5mg==", "dev": true, "requires": { "cli-truncate": "^2.1.0", - "colorette": "^1.2.2", + "colorette": "^2.0.16", "log-update": "^4.0.0", "p-map": "^4.0.0", - "rxjs": "^6.6.7", + "rfdc": "^1.3.0", + "rxjs": "^7.5.4", "through": "^2.3.8", "wrap-ansi": "^7.0.0" - } - }, - "log-symbols": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", - "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", - "dev": true, - "requires": { - "chalk": "^4.1.0", - "is-unicode-supported": "^0.1.0" + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true + }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "cli-truncate": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz", + "integrity": "sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==", + "dev": true, + "requires": { + "slice-ansi": "^3.0.0", + "string-width": "^4.2.0" + } + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "slice-ansi": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz", + "integrity": "sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + } + }, + "string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + } + }, + "strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.1" + } + } } }, "log-update": { @@ -469,6 +359,33 @@ "wrap-ansi": "^6.2.0" }, "dependencies": { + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true + }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, "slice-ansi": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", @@ -480,6 +397,26 @@ "is-fullwidth-code-point": "^3.0.0" } }, + "string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + } + }, + "strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.1" + } + }, "wrap-ansi": { "version": "6.2.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", @@ -536,6 +473,12 @@ "path-key": "^3.0.0" } }, + "object-inspect": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.0.tgz", + "integrity": "sha512-Ho2z80bVIvJloH+YzRmpZVQe87+qASmBUKZDWgx9cu+KDrX2ZDH/3tMy+gXbZETVGs2M8YdxObOh7XAtim9Y0g==", + "dev": true + }, "onetime": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", @@ -554,64 +497,28 @@ "aggregate-error": "^3.0.0" } }, - "parent-module": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dev": true, - "requires": { - "callsites": "^3.0.0" - } - }, - "parse-json": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-even-better-errors": "^2.3.0", - "lines-and-columns": "^1.1.6" - } - }, "path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", "dev": true }, - "path-type": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", - "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", - "dev": true - }, "picomatch": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz", - "integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", "dev": true }, - "please-upgrade-node": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz", - "integrity": "sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg==", - "dev": true, - "requires": { - "semver-compare": "^1.0.0" - } - }, "prettier": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.3.2.tgz", - "integrity": "sha512-lnJzDfJ66zkMy58OL5/NY5zp70S7Nz6KqcKkXYzn2tMVrNxvbqaBpg7H3qHaLxCJ5lNMsGuM8+ohS7cZrthdLQ==", + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.1.tgz", + "integrity": "sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==", "dev": true }, - "resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "regexp-to-ast": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/regexp-to-ast/-/regexp-to-ast-0.5.0.tgz", + "integrity": "sha512-tlbJqcMHnPKI9zSrystikWKwHkBqu2a/Sgw01h3zFjvYrMxEDYHzzoMZnUrbIfpTFEsoRnnviOXNCzFiSc54Qw==", "dev": true }, "restore-cursor": { @@ -624,21 +531,21 @@ "signal-exit": "^3.0.2" } }, + "rfdc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.3.0.tgz", + "integrity": "sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA==", + "dev": true + }, "rxjs": { - "version": "6.6.7", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", - "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.5.4.tgz", + "integrity": "sha512-h5M3Hk78r6wAheJF0a5YahB1yRQKCsZ4MsGdZ5O9ETbVtjPcScGfrMmoOq7EBsCRzd4BDkvDJ7ogP8Sz5tTFiQ==", "dev": true, "requires": { - "tslib": "^1.9.0" + "tslib": "^2.1.0" } }, - "semver-compare": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", - "integrity": "sha1-De4hahyUGrN+nvsXiPavxf9VN/w=", - "dev": true - }, "shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -655,20 +562,19 @@ "dev": true }, "signal-exit": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", - "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==", + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "dev": true }, "slice-ansi": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz", - "integrity": "sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz", + "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==", "dev": true, "requires": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" + "ansi-styles": "^6.0.0", + "is-fullwidth-code-point": "^4.0.0" } }, "string-argv": { @@ -678,34 +584,23 @@ "dev": true }, "string-width": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz", - "integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.0.tgz", + "integrity": "sha512-7x54QnN21P+XL/v8SuNKvfgsUre6PXpN7mc77N3HlZv+f1SBRGmjxtOud2Z6FZ8DmdkD/IdjCaf9XXbnqmTZGQ==", "dev": true, "requires": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.0" - } - }, - "stringify-object": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-3.3.0.tgz", - "integrity": "sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw==", - "dev": true, - "requires": { - "get-own-enumerable-property-symbols": "^3.0.0", - "is-obj": "^1.0.1", - "is-regexp": "^1.0.0" + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" } }, "strip-ansi": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", - "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.0.1.tgz", + "integrity": "sha512-cXNxvT8dFNRVfhVME3JAe98mkXDYN2O1l7jmcwMnOslDeESg1rF/OZMtK0nRAhiari1unG5cD4jG3rapUAkLbw==", "dev": true, "requires": { - "ansi-regex": "^5.0.0" + "ansi-regex": "^6.0.1" } }, "strip-final-newline": { @@ -715,13 +610,10 @@ "dev": true }, "supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "requires": { - "has-flag": "^4.0.0" - } + "version": "9.2.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-9.2.1.tgz", + "integrity": "sha512-Obv7ycoCTG51N7y175StI9BlAXrmgZrFhZOb0/PyjHBher/NmsdBgbbQ1Inhq+gIhz6+7Gb+jWF2Vqi7Mf1xnQ==", + "dev": true }, "through": { "version": "2.3.8", @@ -739,9 +631,9 @@ } }, "tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==", "dev": true }, "type-fest": { @@ -768,6 +660,55 @@ "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true + }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + } + }, + "strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.1" + } + } } }, "yaml": { diff --git a/package.json b/package.json index 37ba0bf64..f731e5687 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,12 @@ { "private": true, "devDependencies": { - "husky": "^7.0.2", - "lint-staged": "^11.1.2", - "prettier": "^2.3.2" + "@prettier/plugin-xml": "1.2.0", + "husky": "7.0.4", + "lint-staged": "12.3.4", + "prettier": "2.5.1" + }, + "scripts": { + "prepare": "husky install" } } 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/SampleServer.csproj b/sample/SampleServer/SampleServer.csproj index ce86be19e..c53281cd5 100644 --- a/sample/SampleServer/SampleServer.csproj +++ b/sample/SampleServer/SampleServer.csproj @@ -10,18 +10,17 @@ - - - - - - - - - - - - + + + + + + + + + + + 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/sample/SampleServer/TextDocumentHandler.cs b/sample/SampleServer/TextDocumentHandler.cs index 701b67278..f3b6f9c2f 100644 --- a/sample/SampleServer/TextDocumentHandler.cs +++ b/sample/SampleServer/TextDocumentHandler.cs @@ -13,6 +13,8 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; +using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + #pragma warning disable CS0618 diff --git a/src/.editorconfig b/src/.editorconfig new file mode 100644 index 000000000..dc318009a --- /dev/null +++ b/src/.editorconfig @@ -0,0 +1,2 @@ +[*] +dotnet_diagnostic.CA1014.severity = none diff --git a/src/Client/Client.csproj b/src/Client/Client.csproj index 14bd92c9e..ebf3ae955 100644 --- a/src/Client/Client.csproj +++ b/src/Client/Client.csproj @@ -1,7 +1,7 @@  - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.LanguageClient OmniSharp.Extensions.LanguageServer.Client @@ -9,14 +9,15 @@ - - - - + + + + - <_Parameter1>OmniSharp.Extensions.LanguageProtocol.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageProtocol.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f 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/Dap.Client.csproj b/src/Dap.Client/Dap.Client.csproj index 1fe996a04..8997ffd64 100644 --- a/src/Dap.Client/Dap.Client.csproj +++ b/src/Dap.Client/Dap.Client.csproj @@ -1,7 +1,7 @@  - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.DebugAdapter.Client OmniSharp.Extensions.DebugAdapter.Client @@ -9,11 +9,12 @@ - + - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f 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.Proposals/Dap.Protocol.Proposals.csproj b/src/Dap.Protocol.Proposals/Dap.Protocol.Proposals.csproj index 77f12517f..e03805d19 100644 --- a/src/Dap.Protocol.Proposals/Dap.Protocol.Proposals.csproj +++ b/src/Dap.Protocol.Proposals/Dap.Protocol.Proposals.csproj @@ -1,18 +1,19 @@  - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.DebugAdapter.Proposals OmniSharp.Extensions.DebugAdapter.Protocol - Proposed Debug Adapter Protocol models, classes, interfaces and helper methods, that may or may not make it into the final spec + Proposed Debug Adapter Protocol models, classes, interfaces and helper methods, that may or may not make it into the final spec - + - + diff --git a/src/Dap.Protocol/Dap.Protocol.csproj b/src/Dap.Protocol/Dap.Protocol.csproj index 45920e504..4622960c4 100644 --- a/src/Dap.Protocol/Dap.Protocol.csproj +++ b/src/Dap.Protocol/Dap.Protocol.csproj @@ -1,7 +1,7 @@  - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.DebugAdapter OmniSharp.Extensions.DebugAdapter.Protocol @@ -9,29 +9,40 @@ - + - - + + - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Server, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Server, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Client, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Client, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Shared, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Shared, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Proposals, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Proposals, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f 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..9d5e6cb04 100644 --- a/src/Dap.Protocol/Feature/Requests/ThreadsFeature.cs +++ b/src/Dap.Protocol/Feature/Requests/ThreadsFeature.cs @@ -2,6 +2,7 @@ using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; +using Thread = OmniSharp.Extensions.DebugAdapter.Protocol.Models.Thread; // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.DebugAdapter.Protocol @@ -10,14 +11,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.Server/Dap.Server.csproj b/src/Dap.Server/Dap.Server.csproj index e6847acd4..c3d82e895 100644 --- a/src/Dap.Server/Dap.Server.csproj +++ b/src/Dap.Server/Dap.Server.csproj @@ -1,7 +1,7 @@ - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.DebugAdapter.Server OmniSharp.Extensions.DebugAdapter.Server @@ -9,11 +9,12 @@ - + - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f diff --git a/src/Dap.Shared/Dap.Shared.csproj b/src/Dap.Shared/Dap.Shared.csproj index 7b833c799..cabed9b52 100644 --- a/src/Dap.Shared/Dap.Shared.csproj +++ b/src/Dap.Shared/Dap.Shared.csproj @@ -1,25 +1,28 @@ - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.DebugAdapter.Shared OmniSharp.Extensions.DebugAdapter.Shared - - + + - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Server, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Server, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Client, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Client, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f 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/Dap.Testing/Dap.Testing.csproj b/src/Dap.Testing/Dap.Testing.csproj index fd64128ec..dec248cdd 100644 --- a/src/Dap.Testing/Dap.Testing.csproj +++ b/src/Dap.Testing/Dap.Testing.csproj @@ -1,7 +1,7 @@  - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.DebugAdapter.Testing OmniSharp.Extensions.DebugAdapter.Testing @@ -9,9 +9,9 @@ - - - - + + + + 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 55dd9ae7a..63f581d5a 100644 --- a/src/JsonRpc.Generators/AssemblyCapabilityKeyAttributeGenerator.cs +++ b/src/JsonRpc.Generators/AssemblyCapabilityKeyAttributeGenerator.cs @@ -1,113 +1,98 @@ using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace OmniSharp.Extensions.JsonRpc.Generators { [Generator] - public class AssemblyCapabilityKeyAttributeGenerator : CachedSourceGenerator + public class AssemblyCapabilityKeyAttributeGenerator : IIncrementalGenerator { - protected override void Execute( - GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource addCacheSource, - ReportCacheDiagnostic cacheDiagnostic - ) + public void Initialize(IncrementalGeneratorInitializationContext context) { - var namespaces = new HashSet() { "OmniSharp.Extensions.LanguageServer.Protocol" }; - var types = syntaxReceiver.FoundNodes - .Concat(syntaxReceiver.Handlers) - .Select( - options => { - var semanticModel = context.Compilation.GetSemanticModel(options.SyntaxTree); - foreach (var item in options.SyntaxTree.GetCompilationUnitRoot() - .Usings - .Where(z => z.Alias == null) - .Select(z => z.Name.ToFullString())) - { - namespaces.Add(item); - } + var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( + (syntaxNode, _) => + { + if (syntaxNode.Parent is TypeDeclarationSyntax) return false; + if (syntaxNode is TypeDeclarationSyntax { Arity: 0, BaseList: { } bl } typeDeclarationSyntax + and (ClassDeclarationSyntax or RecordDeclarationSyntax) + && !typeDeclarationSyntax.Modifiers.Any(SyntaxKind.AbstractKeyword) + && typeDeclarationSyntax.AttributeLists.ContainsAttribute("CapabilityKey") + && bl.Types.Any( + z => z.Type switch + { + SimpleNameSyntax + { + Identifier: { Text: "ICapability" or "DynamicCapability" or "IDynamicCapability" or "LinkSupportCapability" }, Arity: 0 + } => true, + _ => false + } + )) + { + return true; + } - var typeSymbol = semanticModel.GetDeclaredSymbol(options)!; + return false; + }, + (syntaxContext, _) => + { + var namespaces = new HashSet { "OmniSharp.Extensions.LanguageServer.Protocol" }; + var tds = (TypeDeclarationSyntax)syntaxContext.Node; - return SyntaxFactory.Attribute( - SyntaxFactory.IdentifierName("AssemblyCapabilityKey"), SyntaxFactory.AttributeArgumentList( - SyntaxFactory.SeparatedList( - new[] { - SyntaxFactory.AttributeArgument( - SyntaxFactory.TypeOfExpression(SyntaxFactory.ParseName(typeSymbol.ToDisplayString())) - ), - }.Concat(options.AttributeLists.GetAttribute("CapabilityKey")!.ArgumentList!.Arguments) - ) - ) - ); - } - ) - .ToArray(); - if (types.Any()) - { - var cu = SyntaxFactory.CompilationUnit() - .WithUsings(SyntaxFactory.List(namespaces.OrderBy(z => z).Select(z => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(z))))) - .AddAttributeLists( - SyntaxFactory.AttributeList( - target: SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)), SyntaxFactory.SeparatedList(types) - ) - ) - .WithLeadingTrivia(SyntaxFactory.Comment(Preamble.GeneratedByATool)) - .WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed); + foreach (var item in syntaxContext.Node.SyntaxTree.GetCompilationUnitRoot() + .Usings.Where(z => z.Alias == null) + .Select(z => z.Name.ToFullString())) + { + namespaces.Add(item); + } - context.AddSource("AssemblyCapabilityKeys.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8)); - } - } + var typeSymbol = syntaxContext.SemanticModel.GetDeclaredSymbol(syntaxContext.Node)!; - public AssemblyCapabilityKeyAttributeGenerator() : base(() => new SyntaxReceiver(Cache)) - { - } + return ( namespaces, + Attribute( + IdentifierName("AssemblyCapabilityKey"), + AttributeArgumentList( + SeparatedList( + new[] { AttributeArgument(TypeOfExpression(ParseName(typeSymbol.ToDisplayString()))), }.Concat( + tds.AttributeLists.GetAttribute("CapabilityKey")!.ArgumentList!.Arguments + ) + ) + ) + ) ); + } + ).Collect(); - public static CacheContainer Cache = new(); + context.RegisterSourceOutput(syntaxProvider, GenerateAssemblyCapabilityKeys); + } - public class SyntaxReceiver : SyntaxReceiverCache + private void GenerateAssemblyCapabilityKeys( + SourceProductionContext context, ImmutableArray<(HashSet namespaces, AttributeSyntax attribute)> types + ) { - public List Handlers { get; } = new(); - - public override string? GetKey(TypeDeclarationSyntax syntax) - { - var hasher = new CacheKeyHasher(); - hasher.Append(syntax.SyntaxTree.FilePath); - hasher.Append(syntax.Keyword.Text); - hasher.Append(syntax.Identifier.Text); - hasher.Append(syntax.TypeParameterList); - hasher.Append(syntax.AttributeLists); - hasher.Append(syntax.BaseList); - - return hasher; - } - - /// - /// Called for every syntax node in the compilation, we can inspect the nodes and save any information useful for generation - /// - public override void OnVisitNode(TypeDeclarationSyntax syntaxNode) - { - if (syntaxNode.Parent is TypeDeclarationSyntax) return; - if (syntaxNode is ClassDeclarationSyntax or RecordDeclarationSyntax - && syntaxNode.Arity == 0 - && !syntaxNode.Modifiers.Any(SyntaxKind.AbstractKeyword) - && syntaxNode.AttributeLists.ContainsAttribute("CapabilityKey") - && syntaxNode.BaseList is { } bl && bl.Types.Any( - z => z.Type switch { - SimpleNameSyntax { Identifier: { Text: "ICapability" or "DynamicCapability" or "IDynamicCapability" or "LinkSupportCapability" }, Arity: 0 } => true, - _ => false - } - )) + var namespaces = types.Aggregate( + new HashSet(), (set, tuple) => { - Handlers.Add(syntaxNode); - } - } + foreach (var name in tuple.namespaces) + { + set.Add(name); + } - public SyntaxReceiver(CacheContainer cache) : base(cache) + return set; + } + ); + if (types.Any()) { + var cu = CompilationUnit() + .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 81b6f97df..89f043221 100644 --- a/src/JsonRpc.Generators/AssemblyJsonRpcHandlersAttributeGenerator.cs +++ b/src/JsonRpc.Generators/AssemblyJsonRpcHandlersAttributeGenerator.cs @@ -1,122 +1,92 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Collections.Immutable; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; -using OmniSharp.Extensions.JsonRpc.Generators.Contexts; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace OmniSharp.Extensions.JsonRpc.Generators { [Generator] - public class AssemblyJsonRpcHandlersAttributeGenerator : CachedSourceGenerator + public class AssemblyJsonRpcHandlersAttributeGenerator : IIncrementalGenerator { - protected override void Execute( - GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource addCacheSource, - ReportCacheDiagnostic cacheDiagnostic - ) + public void Initialize(IncrementalGeneratorInitializationContext context) { - var namespaces = new HashSet() { "OmniSharp.Extensions.JsonRpc" }; - var types = syntaxReceiver.FoundNodes - .Concat(syntaxReceiver.Handlers) - .Select( - options => { - var semanticModel = context.Compilation.GetSemanticModel(options.SyntaxTree); - var typeSymbol = semanticModel.GetDeclaredSymbol(options)!; + var syntaxProvider = context + .SyntaxProvider + .CreateSyntaxProvider( + (syntaxNode, _) => + { + if (syntaxNode.Parent is TypeDeclarationSyntax) return false; + if (syntaxNode is TypeDeclarationSyntax { Arity: 0, BaseList: { } bl } typeDeclarationSyntax + and (ClassDeclarationSyntax or RecordDeclarationSyntax) + && !typeDeclarationSyntax.Modifiers.Any(SyntaxKind.AbstractKeyword) + && typeDeclarationSyntax.AttributeLists.ContainsAttribute("Method") + && bl.Types.Any( + z => z.Type switch + { + SimpleNameSyntax { Identifier: { Text: "IJsonRpcNotificationHandler" }, Arity: 0 or 1 } => true, + SimpleNameSyntax { Identifier: { Text: "ICanBeResolvedHandler" }, Arity: 1 } => true, + SimpleNameSyntax { Identifier: { Text: "IJsonRpcRequestHandler" }, Arity: 1 or 2 } => true, + SimpleNameSyntax { Identifier: { Text: "IJsonRpcHandler" }, Arity: 0 } => true, + _ => false + } + )) + { + return true; + } - return AttributeArgument(TypeOfExpression(ParseName(typeSymbol.ToDisplayString()))); - } - ) - .ToArray(); + if (syntaxNode is InterfaceDeclarationSyntax { Arity: 0, BaseList: { } bl2 } interfaceDeclarationSyntax + && interfaceDeclarationSyntax.AttributeLists.ContainsAttribute("Method") + && bl2.Types.Any( + z => z.Type switch + { + SimpleNameSyntax { Identifier: { Text: "IJsonRpcNotificationHandler" }, Arity: 0 or 1 } => true, + SimpleNameSyntax { Identifier: { Text: "ICanBeResolvedHandler" }, Arity: 1 } => true, + SimpleNameSyntax { Identifier: { Text: "IJsonRpcRequestHandler" }, Arity: 1 or 2 } => true, + SimpleNameSyntax { Identifier: { Text: "IJsonRpcHandler" }, Arity: 0 } => true, + _ => false + } + )) + { + return true; + } + + return false; + }, + (syntaxContext, _) => AttributeArgument( + TypeOfExpression( + ParseName(syntaxContext.SemanticModel.GetDeclaredSymbol(syntaxContext.Node)!.ToDisplayString()) + ) + ) + ) + .Collect(); + + context.RegisterSourceOutput(syntaxProvider, GenerateAssemblyJsonRpcHandlers); + } + + private void GenerateAssemblyJsonRpcHandlers(SourceProductionContext context, ImmutableArray types) + { + var namespaces = new HashSet { "OmniSharp.Extensions.JsonRpc" }; if (types.Any()) { var cu = CompilationUnit() - .WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z))))) - .WithLeadingTrivia(Comment(Preamble.GeneratedByATool)) - .WithTrailingTrivia(CarriageReturnLineFeed); + .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).ToArray(); + types = types.Skip(10).ToImmutableArray(); cu = cu.AddAttributeLists( AttributeList( - target: AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), + AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), SingletonSeparatedList(Attribute(IdentifierName("AssemblyJsonRpcHandlers"), AttributeArgumentList(SeparatedList(innerTypes)))) ) ); } - context.AddSource("AssemblyJsonRpcHandlers.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8)); - } - } - - public AssemblyJsonRpcHandlersAttributeGenerator() : base(() => new SyntaxReceiver(Cache)) - { - } - - public static CacheContainer Cache = new(); - - public class SyntaxReceiver : SyntaxReceiverCache - { - public List Handlers { get; } = new(); - public override string? GetKey(TypeDeclarationSyntax syntax) - { - var hasher = new CacheKeyHasher(); - hasher.Append(syntax.SyntaxTree.FilePath); - hasher.Append(syntax.Keyword.Text); - hasher.Append(syntax.Identifier.Text); - hasher.Append(syntax.TypeParameterList); - hasher.Append(syntax.AttributeLists); - hasher.Append(syntax.BaseList); - return hasher; - } - - /// - /// Called for every syntax node in the compilation, we can inspect the nodes and save any information useful for generation - /// - public override void OnVisitNode(TypeDeclarationSyntax syntaxNode) - { - if (syntaxNode.Parent is TypeDeclarationSyntax) return; - if (syntaxNode is ClassDeclarationSyntax or RecordDeclarationSyntax - && syntaxNode.Arity == 0 - && !syntaxNode.Modifiers.Any(SyntaxKind.AbstractKeyword) - && syntaxNode.AttributeLists.ContainsAttribute("Method") - && syntaxNode.BaseList is { } bl && bl.Types.Any( - z => z.Type switch { - SimpleNameSyntax { Identifier: { Text: "IJsonRpcNotificationHandler" }, Arity: 0 or 1 } => true, - SimpleNameSyntax { Identifier: { Text: "ICanBeResolvedHandler" }, Arity: 1 } => true, - SimpleNameSyntax { Identifier: { Text: "IJsonRpcRequestHandler" }, Arity: 1 or 2 } => true, - SimpleNameSyntax { Identifier: { Text: "IJsonRpcHandler" }, Arity: 0 } => true, - _ => false - } - )) - { - Handlers.Add(syntaxNode); - } - - if (syntaxNode is InterfaceDeclarationSyntax - && syntaxNode.Arity == 0 - && syntaxNode.AttributeLists.ContainsAttribute("Method") - && syntaxNode.BaseList is { } bl2 && bl2.Types.Any( - z => z.Type switch { - SimpleNameSyntax { Identifier: { Text: "IJsonRpcNotificationHandler" }, Arity: 0 or 1 } => true, - SimpleNameSyntax { Identifier: { Text: "ICanBeResolvedHandler" }, Arity: 1 } => true, - SimpleNameSyntax { Identifier: { Text: "IJsonRpcRequestHandler" }, Arity: 1 or 2 } => true, - SimpleNameSyntax { Identifier: { Text: "IJsonRpcHandler" }, Arity: 0 } => true, - _ => false - } - )) - { - Handlers.Add(syntaxNode); - } - } - - public SyntaxReceiver(CacheContainer cache) : base(cache) - { + context.AddSource("AssemblyJsonRpcHandlers.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8)); } } } diff --git a/src/JsonRpc.Generators/AutoImplementParamsGenerator.cs b/src/JsonRpc.Generators/AutoImplementParamsGenerator.cs index 541aa1c2b..c9eac05da 100644 --- a/src/JsonRpc.Generators/AutoImplementParamsGenerator.cs +++ b/src/JsonRpc.Generators/AutoImplementParamsGenerator.cs @@ -5,69 +5,93 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static OmniSharp.Extensions.JsonRpc.Generators.CommonElements; namespace OmniSharp.Extensions.JsonRpc.Generators { [Generator] - public class AutoImplementParamsGenerator : CachedSourceGenerator + public class AutoImplementParamsGenerator : IIncrementalGenerator { - protected override void Execute( - GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource addCacheSource, - ReportCacheDiagnostic cacheDiagnostic - ) + public void Initialize(IncrementalGeneratorInitializationContext context) { - foreach (var candidate in syntaxReceiver.Candidates) - { - var members = new List(); - var model = context.Compilation.GetSemanticModel(candidate.SyntaxTree); - var symbol = model.GetDeclaredSymbol(candidate); - if (symbol is null) continue; + var _attributes = "Method,RegistrationOptions"; + var _interfaces = "IPartialItemsRequest,IPartialItemRequest,IWorkDoneProgressParams,IHandlerIdentity"; - var autoImplementProperties = AutoImplementInterfaces(candidate, symbol).ToArray(); - if (autoImplementProperties is { Length: > 0 }) + var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( + (syntaxNode, _) => { - var extendedParams = candidate - .WithAttributeLists(List()) - .WithMembers(List(autoImplementProperties)) - .WithConstraintClauses(List()) - .WithBaseList(null); - members.Add(extendedParams); - } + if (syntaxNode is TypeDeclarationSyntax typeDeclarationSyntax and (ClassDeclarationSyntax or RecordDeclarationSyntax) + && ( typeDeclarationSyntax.AttributeLists.ContainsAttribute(_attributes) + || typeDeclarationSyntax.BaseList?.Types.Any(type => type.Type.GetSyntaxName() is { } n && _interfaces.Contains(n)) == true + ) + ) + { + return true; + } - if (members.Count == 0) continue; + return false; + }, (syntaxContext, _) => { return syntaxContext; } + ); - if (!candidate.Modifiers.Any(z => z.IsKind(SyntaxKind.PartialKeyword))) - { - cacheDiagnostic(candidate, static c => Diagnostic.Create(GeneratorDiagnostics.MustBePartial, c.Identifier.GetLocation(), c.Identifier.Text)); - } - var cu = CompilationUnit( - List(), - List(candidate.SyntaxTree.GetCompilationUnitRoot().Usings), - List(), - SingletonList( - NamespaceDeclaration(ParseName(symbol.ContainingNamespace.ToDisplayString())) - .WithMembers(List(members)) - ) - ) - .AddUsings(UsingDirective(ParseName("OmniSharp.Extensions.LanguageServer.Protocol.Serialization"))) - .WithLeadingTrivia() - .WithTrailingTrivia() - .WithLeadingTrivia(Comment(Preamble.GeneratedByATool), Trivia(NullableDirectiveTrivia(Token(SyntaxKind.EnableKeyword), true))) - .WithTrailingTrivia(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.RestoreKeyword), true)), CarriageReturnLineFeed); + context.RegisterSourceOutput(syntaxProvider, GenerateAutoImplementedInterfaces); + } + + private static void GenerateAutoImplementedInterfaces(SourceProductionContext context, GeneratorSyntaxContext syntaxContext) + { + var candidate = (TypeDeclarationSyntax)syntaxContext.Node; + var members = new List(); + var model = syntaxContext.SemanticModel; + var symbol = model.GetDeclaredSymbol(candidate); + if (symbol is null) return; + + var autoImplementProperties = AutoImplementInterfaces(candidate, symbol).ToArray(); + if (autoImplementProperties is { Length: > 0 }) + { + 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); + } - addCacheSource( - $"{Path.GetFileNameWithoutExtension(candidate.SyntaxTree.FilePath)}_{candidate.Identifier.Text}{( candidate.Arity > 0 ? candidate.Arity.ToString() : "" )}.cs", - candidate, - cu.NormalizeWhitespace().GetText(Encoding.UTF8) - ); + if (members.Count == 0) return; + + if (!candidate.Modifiers.Any(z => z.IsKind(SyntaxKind.PartialKeyword))) + { + context.ReportDiagnostic(Diagnostic.Create(GeneratorDiagnostics.MustBePartial, candidate.Identifier.GetLocation(), candidate.Identifier.Text)); } + + var cu = CompilationUnit( + 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)) + ) + ) + .AddUsings(UsingDirective(ParseName("OmniSharp.Extensions.LanguageServer.Protocol.Serialization"))) + .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) + ); } - private static IEnumerable AutoImplementInterfaces(TypeDeclarationSyntax syntax, INamedTypeSymbol symbol) + private static IEnumerable AutoImplementInterfaces(BaseTypeDeclarationSyntax syntax, INamedTypeSymbol symbol) { if (syntax.BaseList?.Types.Any(z => z.Type.GetSyntaxName() is "IWorkDoneProgressParams") == true && symbol.GetMembers("WorkDoneToken").IsEmpty) @@ -93,19 +117,27 @@ private static IEnumerable AutoImplementInterfaces(Type yield return PropertyDeclaration(PredefinedType(Token(SyntaxKind.StringKeyword)), Identifier("__identity")) .WithAttributeLists( List( - new[] { + new[] + { AttributeList( SeparatedList( - new[] { + new[] + { Attribute(IdentifierName("JsonProperty")) .WithArgumentList( AttributeArgumentList( SeparatedList( - new[] { - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal("$$__handler_id__$$"))), + new[] + { + AttributeArgument( + LiteralExpression( + SyntaxKind.StringLiteralExpression, Literal("$$__handler_id__$$") + ) + ), AttributeArgument( MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, IdentifierName("DefaultValueHandling"), + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("DefaultValueHandling"), IdentifierName("Ignore") ) ) @@ -120,7 +152,7 @@ private static IEnumerable AutoImplementInterfaces(Type SingletonSeparatedList( AttributeArgument( MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, IdentifierName("EditorBrowsableState"), + SyntaxKind.SimpleMemberAccessExpression, ParseName("EditorBrowsableState"), IdentifierName("Never") ) ) @@ -137,57 +169,5 @@ private static IEnumerable AutoImplementInterfaces(Type .WithAccessorList(GetInitAccessor); } } - - public AutoImplementParamsGenerator() : base(() => new SyntaxReceiver(Cache)) - { - } - - public static CacheContainer Cache = new(); - - public class SyntaxReceiver : SyntaxReceiverCache - { - private readonly string _attributes; - private readonly string _interfaces; - public List Candidates { get; } = new(); - - public SyntaxReceiver(CacheContainer cacheContainer) : base(cacheContainer) - { - _attributes = "Method,RegistrationOptions"; - _interfaces = "IPartialItemsRequest,IPartialItemRequest,IWorkDoneProgressParams,IHandlerIdentity"; - } - - public override string? GetKey(TypeDeclarationSyntax syntax) - { - var hasher = new CacheKeyHasher(); - hasher.Append(syntax.SyntaxTree.FilePath); - hasher.Append(syntax.Keyword.Text); - hasher.Append(syntax.Identifier.Text); - hasher.Append(syntax.TypeParameterList); - hasher.Append(syntax.AttributeLists); - hasher.Append(syntax.BaseList); - foreach (var item in syntax.Members.OfType().Select(z => z.Identifier.Text)) - { - hasher.Append(item); - } - - return hasher; - } - - /// - /// Called for every syntax node in the compilation, we can inspect the nodes and save any information useful for generation - /// - public override void OnVisitNode(TypeDeclarationSyntax syntaxNode) - { - // any field with at least one attribute is a candidate for property generation - if (syntaxNode is ClassDeclarationSyntax or RecordDeclarationSyntax - && ( syntaxNode.AttributeLists.ContainsAttribute(_attributes) - || syntaxNode.BaseList?.Types.Any(type => type.Type.GetSyntaxName() is { } n && _interfaces.Contains(n)) == true - ) - ) - { - Candidates.Add(syntaxNode); - } - } - } } } diff --git a/src/JsonRpc.Generators/Cache/AddCacheSource.cs b/src/JsonRpc.Generators/Cache/AddCacheSource.cs deleted file mode 100644 index e593a0c81..000000000 --- a/src/JsonRpc.Generators/Cache/AddCacheSource.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; - -namespace OmniSharp.Extensions.JsonRpc.Generators.Cache -{ - public delegate void AddCacheSource(string hintName, T syntaxNode, SourceText sourceText) where T : SyntaxNode; - - public delegate void ReportCacheDiagnostic(T syntaxNode, CacheDiagnosticFactory diagnostic) where T : SyntaxNode; - - public delegate Diagnostic CacheDiagnosticFactory(T syntaxNode) where T : SyntaxNode; - - public delegate Location LocationFactory(T syntaxNode) where T : SyntaxNode; -} diff --git a/src/JsonRpc.Generators/Cache/CacheContainer.cs b/src/JsonRpc.Generators/Cache/CacheContainer.cs deleted file mode 100644 index 7b8084630..000000000 --- a/src/JsonRpc.Generators/Cache/CacheContainer.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Collections.Immutable; -using System.Threading; -using Microsoft.CodeAnalysis; - -namespace OmniSharp.Extensions.JsonRpc.Generators.Cache -{ - public class CacheContainer where T : SyntaxNode - { - private ImmutableDictionary> _sourceTexts; - private ImmutableDictionary>> _cacheDiagnostics; - - public CacheContainer() - { - _sourceTexts = ImmutableDictionary>.Empty; - _cacheDiagnostics = ImmutableDictionary>>.Empty; - } - - public ImmutableDictionary> SourceTexts => _sourceTexts; - public ImmutableDictionary>> Diagnostics => _cacheDiagnostics; - - public void Swap( - ImmutableDictionary.Builder sources)>.Builder foundCache, - ImmutableDictionary>.Builder>.Builder diagnosticFactories - ) - { - Interlocked.Exchange( - ref _sourceTexts, - foundCache.ToImmutableDictionary(z => z.Key, z => z.Value.sources.ToImmutable()) - ); - Interlocked.Exchange( - ref _cacheDiagnostics, - diagnosticFactories.ToImmutableDictionary(z => z.Key, z => z.Value.ToImmutable()) - ); - } - } -} diff --git a/src/JsonRpc.Generators/Cache/CacheKeyHasher.cs b/src/JsonRpc.Generators/Cache/CacheKeyHasher.cs deleted file mode 100644 index 2061cbbee..000000000 --- a/src/JsonRpc.Generators/Cache/CacheKeyHasher.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace OmniSharp.Extensions.JsonRpc.Generators.Cache -{ - class CacheKeyHasher : IDisposable - { - public static bool Cache = true; - private readonly SHA1 _hasher; - - public CacheKeyHasher() - { - _hasher = SHA1.Create(); - } - - public void Append(string textToHash) - { - var inputBuffer = Encoding.UTF8.GetBytes(textToHash); - _hasher.TransformBlock(inputBuffer, 0, inputBuffer.Length, inputBuffer, 0); - } - - public void Append(TypeSyntax? typeSyntax) - { - if (typeSyntax?.GetSyntaxName() is { } a) - { - Append(a); - } - - if (typeSyntax is GenericNameSyntax gns) - { - foreach (var item in gns.TypeArgumentList.Arguments) - { - Append(item); - } - } - } - - public void Append(TypeParameterListSyntax? typeParameterListSyntax) - { - if (typeParameterListSyntax is null or { Parameters: { Count: 0 } }) return; - foreach (var item in typeParameterListSyntax.Parameters) - { - Append(item.Identifier.Text); - Append(item.AttributeLists); - } - } - - public void Append(BaseListSyntax? baseListSyntax) - { - if (baseListSyntax is null) return; - foreach (var item in baseListSyntax.Types) - { - Append(item.Type); - } - } - - public void Append(SyntaxList attributeList) - { - foreach (var item in attributeList) - { - Append(item); - } - } - - public void Append(SyntaxList items) - where T : MemberDeclarationSyntax - { - if (items is { Count: 0 }) return; - foreach (var item in items.OfType()) - { - Append(item.AttributeLists); - if (item is PropertyDeclarationSyntax p) - { - Append(p.Identifier.Text); - Append(p.Type); - } - } - } - - public void Append(AttributeListSyntax attributeList) - { - if (attributeList is { Attributes: { Count: 0 } }) return; - foreach (var item in attributeList.Attributes) - { - Append(item); - } - } - - public void Append(AttributeSyntax attribute) - { - Append(attribute.Name.GetSyntaxName() ?? string.Empty); - if (attribute.ArgumentList?.Arguments is { Count: > 0 } arguments) - { - foreach (var item in arguments) - { - if (item.NameEquals is { }) - { - Append(item.NameEquals.Name.GetSyntaxName() ?? string.Empty); - } - - Append( - item switch { - { Expression: TypeOfExpressionSyntax tyof } => tyof.Type.GetSyntaxName() is { Length: > 0 } name ? name : string.Empty, - { Expression: LiteralExpressionSyntax { } literal } => literal.Token.Text, - _ => string.Empty - } - ); - } - } - } - - private string ConvertByteArrayToString() - { - _hasher.TransformFinalBlock(Array.Empty(), 0, 0); - var sb = new StringBuilder(); - foreach (var b in _hasher.Hash) - { - sb.Append(b.ToString("X2")); - } - - return sb.ToString(); - } - - public override string ToString() => ConvertByteArrayToString(); - - public static implicit operator string(CacheKeyHasher value) => value.ToString(); - - public void Dispose() => _hasher.Dispose(); - } -} diff --git a/src/JsonRpc.Generators/Cache/CachedSourceGenerator.cs b/src/JsonRpc.Generators/Cache/CachedSourceGenerator.cs deleted file mode 100644 index 1f1cd0c42..000000000 --- a/src/JsonRpc.Generators/Cache/CachedSourceGenerator.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using Microsoft.CodeAnalysis; - -namespace OmniSharp.Extensions.JsonRpc.Generators.Cache -{ - /// - /// We're not supposed to do this... but in realistic. - /// - public abstract class CachedSourceGenerator : ISourceGenerator - where T : ISyntaxReceiver, IReceiverCache - where TSyntax : SyntaxNode - { - private readonly Func _syntaxReceiverFactory; - - public CachedSourceGenerator(Func syntaxReceiverFactory) - { - _syntaxReceiverFactory = syntaxReceiverFactory; - } - - public void Initialize(GeneratorInitializationContext context) - { - context.RegisterForSyntaxNotifications(() => _syntaxReceiverFactory()); - } - - public void Execute(GeneratorExecutionContext context) - { - if (!( context.SyntaxReceiver is T syntaxReceiver )) return; - - syntaxReceiver.Start(context); - Execute( - context, syntaxReceiver, - (name, node, text) => { - context.AddSource(name, text); - - if (CacheKeyHasher.Cache) - { - syntaxReceiver.AddCacheSource(name, node, text); - } - }, - (node, diagnostic) => { - context.ReportDiagnostic(diagnostic(node)); - - if (CacheKeyHasher.Cache) - { - syntaxReceiver.ReportCacheDiagnostic(node, diagnostic); - } - } - ); - foreach (var item in syntaxReceiver.CachedSources) - { - context.AddSource(item.Name, item.SourceText); - } - - foreach (var item in syntaxReceiver.CachedDiagnostics) - { - context.ReportDiagnostic(item); - } - - syntaxReceiver.Finish(context); - } - - protected abstract void Execute( - GeneratorExecutionContext context, T syntaxReceiver, AddCacheSource addCacheSource, ReportCacheDiagnostic cacheDiagnostic - ); - } -} diff --git a/src/JsonRpc.Generators/Cache/IReceiverCache.cs b/src/JsonRpc.Generators/Cache/IReceiverCache.cs deleted file mode 100644 index d1e72827e..000000000 --- a/src/JsonRpc.Generators/Cache/IReceiverCache.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Collections.Generic; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; - -namespace OmniSharp.Extensions.JsonRpc.Generators.Cache -{ - public interface IReceiverCache - where T : SyntaxNode - { - string? GetKey(T syntax); - void Start(GeneratorExecutionContext context); - void Finish(GeneratorExecutionContext context); - IEnumerable CachedSources { get; } - IEnumerable CachedDiagnostics { get; } - void AddCacheSource(string hintName, T syntaxNode, SourceText sourceText); - void ReportCacheDiagnostic(T syntaxNode, CacheDiagnosticFactory diagnostic); - } -} diff --git a/src/JsonRpc.Generators/Cache/SourceTextCache.cs b/src/JsonRpc.Generators/Cache/SourceTextCache.cs deleted file mode 100644 index 6abdd658f..000000000 --- a/src/JsonRpc.Generators/Cache/SourceTextCache.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; - -namespace OmniSharp.Extensions.JsonRpc.Generators.Cache -{ - public record SourceTextCache(string Name, SourceText SourceText); - public record DiagnosticCache(ImmutableArray> Diagnostics) where T : SyntaxNode; -} diff --git a/src/JsonRpc.Generators/Cache/SyntaxReceiverCache.cs b/src/JsonRpc.Generators/Cache/SyntaxReceiverCache.cs deleted file mode 100644 index 5620f5b6b..000000000 --- a/src/JsonRpc.Generators/Cache/SyntaxReceiverCache.cs +++ /dev/null @@ -1,125 +0,0 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; - -namespace OmniSharp.Extensions.JsonRpc.Generators.Cache -{ - public abstract class SyntaxReceiverCache : IReceiverCache, ISyntaxReceiver - where T : SyntaxNode - { - private readonly CacheContainer _cache; - private readonly ImmutableDictionary.Builder sources)>.Builder _foundSourceTexts; - private readonly ImmutableDictionary>.Builder>.Builder _foundDiagnosticFactories; - private readonly List _cachedSources = new(); - private readonly List _cachedDiagnostics = new(); - private readonly List _foundNodes = new(); - - protected SyntaxReceiverCache(CacheContainer cache) - { - _cache = cache; - _foundSourceTexts = ImmutableDictionary.Builder sources)>.Empty.ToBuilder(); - _foundDiagnosticFactories = ImmutableDictionary>.Builder>.Empty.ToBuilder(); - } - - public abstract string? GetKey(T syntax); - - public void Start(GeneratorExecutionContext context) - { - // TODO: Check if options disable cache - try - { - // check stuff - _cache.Swap(_foundSourceTexts, _foundDiagnosticFactories); - } - catch - { - _cachedSources.Clear(); - _cachedDiagnostics.Clear(); - foreach (var found in _foundSourceTexts.Values) - { - OnVisitNode(found.Item1); - } - } - } - - public void Finish(GeneratorExecutionContext context) - { - // TODO: Check if options disable cache - try - { - // check stuff - _cache.Swap(_foundSourceTexts, _foundDiagnosticFactories); - } - catch - { - _cache.Swap( - ImmutableDictionary.Builder sources)>.Empty.ToBuilder(), - ImmutableDictionary>.Builder>.Empty.ToBuilder() - ); - } - } - - public IEnumerable CachedSources => _cachedSources; - public IEnumerable CachedDiagnostics => _cachedDiagnostics; - public IEnumerable FoundNodes => _foundNodes; - - public void OnVisitSyntaxNode(SyntaxNode syntaxNode) - { - if (syntaxNode is not T v) return; - if (GetKey(v) is { } key) - { - if (_cache.SourceTexts.TryGetValue(key, out var cacheValue)) - { - _foundSourceTexts.Add(key, ( v, cacheValue.ToBuilder() )); - _cachedSources.AddRange(cacheValue); - } - - if (_cache.Diagnostics.TryGetValue(key, out var diagnostics)) - { - _foundDiagnosticFactories.Add(key, diagnostics.ToBuilder()); - _cachedDiagnostics.AddRange(diagnostics.Select(f => f(v))); - } - - if (_foundSourceTexts.ContainsKey(key) || _foundDiagnosticFactories.ContainsKey(key)) - { - _foundNodes.Add(v); - return; - } - } - - OnVisitNode(v); - } - - public void AddCacheSource(string hintName, T syntaxNode, SourceText sourceText) - { - if (GetKey(syntaxNode) is not { } key) return; - if (!_foundSourceTexts.TryGetValue(key, out var data)) - { - var array = ImmutableArray.Create(new SourceTextCache(hintName, sourceText)).ToBuilder(); - _foundSourceTexts.Add(key, ( syntaxNode, array )); - } - else - { - data.sources.Add(new SourceTextCache(hintName, sourceText)); - } - } - - public void ReportCacheDiagnostic(T syntaxNode, CacheDiagnosticFactory diagnostic) - { - if (GetKey(syntaxNode) is not { } key) return; - if (!_foundDiagnosticFactories.TryGetValue(key, out var array)) - { - array = ImmutableArray.Create(diagnostic).ToBuilder(); - _foundDiagnosticFactories.Add(key, array); - } - else - { - array.Add(diagnostic); - } - } - - public abstract void OnVisitNode(T syntaxNode); - } -} diff --git a/src/JsonRpc.Generators/Contexts/DapAttributes.cs b/src/JsonRpc.Generators/Contexts/DapAttributes.cs index 1f55ce153..d081deade 100644 --- a/src/JsonRpc.Generators/Contexts/DapAttributes.cs +++ b/src/JsonRpc.Generators/Contexts/DapAttributes.cs @@ -1,16 +1,14 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; namespace OmniSharp.Extensions.JsonRpc.Generators.Contexts { record DapAttributes { public static DapAttributes? Parse( - GeneratorExecutionContext context, - AddCacheSource addCacheSource, - ReportCacheDiagnostic cacheDiagnostic, - TypeDeclarationSyntax syntax, + Compilation compilation, + TypeDeclarationSyntax candidateClass, + SemanticModel model, INamedTypeSymbol symbol ) { diff --git a/src/JsonRpc.Generators/Contexts/ExtensionMethodContext.cs b/src/JsonRpc.Generators/Contexts/ExtensionMethodContext.cs index 3dc33a5df..49e08ae49 100644 --- a/src/JsonRpc.Generators/Contexts/ExtensionMethodContext.cs +++ b/src/JsonRpc.Generators/Contexts/ExtensionMethodContext.cs @@ -9,8 +9,7 @@ record ExtensionMethodContext( TypeDeclarationSyntax TypeDeclaration, INamedTypeSymbol TypeSymbol, TypeSyntax Item, - ImmutableArray RelatedItems, - GeneratorExecutionContext Context + ImmutableArray RelatedItems ) { public bool IsProxy { get; init; } diff --git a/src/JsonRpc.Generators/Contexts/GeneratorData.cs b/src/JsonRpc.Generators/Contexts/GeneratorData.cs index a5cd7f311..33cffce86 100644 --- a/src/JsonRpc.Generators/Contexts/GeneratorData.cs +++ b/src/JsonRpc.Generators/Contexts/GeneratorData.cs @@ -3,13 +3,11 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; using static OmniSharp.Extensions.JsonRpc.Generators.Helpers; namespace OmniSharp.Extensions.JsonRpc.Generators.Contexts { - abstract record GeneratorData( + internal abstract record GeneratorData( TypeDeclarationSyntax TypeDeclaration, INamedTypeSymbol TypeSymbol, JsonRpcAttributes JsonRpcAttributes, @@ -21,38 +19,23 @@ abstract record GeneratorData( HashSet AdditionalUsings, List AssemblyJsonRpcHandlersAttributeArguments, SemanticModel Model, - GeneratorExecutionContext Context + Compilation Compilation ) { - private AddCacheSource AddCacheSourceDelegate { get; init; } - private ReportCacheDiagnostic CacheDiagnosticDelegate { get; init; } - - public void AddSource(string hintName, SourceText sourceText) - { - AddCacheSourceDelegate(hintName, TypeDeclaration, sourceText); - } - - public void ReportDiagnostic(CacheDiagnosticFactory diagnostic) - { - CacheDiagnosticDelegate(TypeDeclaration, diagnostic); - } - public static GeneratorData? Create( - GeneratorExecutionContext context, + Compilation compilation, TypeDeclarationSyntax candidateClass, - AddCacheSource addCacheSource, - ReportCacheDiagnostic cacheDiagnostic, + SemanticModel model, HashSet additionalUsings ) { - var model = context.Compilation.GetSemanticModel(candidateClass.SyntaxTree); - var symbol = model.GetDeclaredSymbol(candidateClass); + var symbol = model.GetDeclaredSymbol(candidateClass) is { } nts ? nts : null; if (symbol == null) return null; var requestType = GetRequestType(candidateClass, symbol); if (requestType == null) return null; - var jsonRpcAttributes = JsonRpcAttributes.Parse(context, addCacheSource, cacheDiagnostic, candidateClass, symbol, additionalUsings); - var lspAttributes = LspAttributes.Parse(context, addCacheSource, cacheDiagnostic, candidateClass, symbol); - var dapAttributes = DapAttributes.Parse(context, addCacheSource, cacheDiagnostic, candidateClass, symbol); + var jsonRpcAttributes = JsonRpcAttributes.Parse(compilation, candidateClass, model, symbol, additionalUsings); + var lspAttributes = LspAttributes.Parse(compilation, candidateClass, model, symbol); + var dapAttributes = DapAttributes.Parse(compilation, candidateClass, model, symbol); additionalUsings.Add(jsonRpcAttributes.HandlerNamespace); additionalUsings.Add(jsonRpcAttributes.ModelNamespace); @@ -75,9 +58,8 @@ HashSet additionalUsings GetPartialItems(candidateClass, symbol, requestType), additionalUsings, new List(), - model, - context - ) { CacheDiagnosticDelegate = cacheDiagnostic, AddCacheSourceDelegate = addCacheSource }; + model, compilation + ); } if (IsNotification(candidateClass)) @@ -93,9 +75,8 @@ HashSet additionalUsings GetRegistrationOptions(candidateClass, symbol, lspAttributes), additionalUsings, new List(), - model, - context - ) { CacheDiagnosticDelegate = cacheDiagnostic, AddCacheSourceDelegate = addCacheSource }; + model, compilation + ); } return null; @@ -109,7 +90,9 @@ HashSet additionalUsings && tds.AttributeLists.ContainsAttribute("GenerateHandler") )?.GetSyntax() is TypeDeclarationSyntax declarationSyntax) { - return Create(parent.Context, declarationSyntax, parent.AddCacheSourceDelegate, parent.CacheDiagnosticDelegate, 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/JsonRpcAttributes.cs b/src/JsonRpc.Generators/Contexts/JsonRpcAttributes.cs index f72061692..17b5c6adb 100644 --- a/src/JsonRpc.Generators/Contexts/JsonRpcAttributes.cs +++ b/src/JsonRpc.Generators/Contexts/JsonRpcAttributes.cs @@ -5,18 +5,19 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; namespace OmniSharp.Extensions.JsonRpc.Generators.Contexts { record JsonRpcAttributes( SyntaxAttributeData? GenerateHandlerMethods, ImmutableArray HandlerRegistries, + ImmutableArray HandlerRegistryDiagnostics, string HandlerMethodName, string PartialHandlerMethodName, bool AllowDerivedRequests, SyntaxAttributeData? GenerateRequestMethods, ImmutableArray RequestProxies, + ImmutableArray RequestProxyDiagnostics, string RequestMethodName, SyntaxAttributeData? GenerateHandler, string HandlerNamespace, @@ -25,27 +26,30 @@ string ModelNamespace ) { public static JsonRpcAttributes Parse( - GeneratorExecutionContext context, - AddCacheSource addCacheSource, - ReportCacheDiagnostic cacheDiagnostic, + Compilation compilation, TypeDeclarationSyntax syntax, + SemanticModel model, INamedTypeSymbol symbol, HashSet additionalUsings ) { - var generateHandlerMethodsAttributeSymbol = context.Compilation.GetTypeByMetadataName("OmniSharp.Extensions.JsonRpc.Generation.GenerateHandlerMethodsAttribute"); - var generateRequestMethodsAttributeSymbol = context.Compilation.GetTypeByMetadataName("OmniSharp.Extensions.JsonRpc.Generation.GenerateRequestMethodsAttribute"); - var generateHandlerAttributeSymbol = context.Compilation.GetTypeByMetadataName("OmniSharp.Extensions.JsonRpc.Generation.GenerateHandlerAttribute"); + var generateHandlerMethodsAttributeSymbol = + compilation.GetTypeByMetadataName("OmniSharp.Extensions.JsonRpc.Generation.GenerateHandlerMethodsAttribute"); + var generateRequestMethodsAttributeSymbol = + compilation.GetTypeByMetadataName("OmniSharp.Extensions.JsonRpc.Generation.GenerateRequestMethodsAttribute"); + var generateHandlerAttributeSymbol = compilation.GetTypeByMetadataName("OmniSharp.Extensions.JsonRpc.Generation.GenerateHandlerAttribute"); var handlerName = Helpers.SpecialCasedHandlerName(symbol).Split('.').Last(); var attributes = new JsonRpcAttributes( null, ImmutableArray.Empty, + ImmutableArray.Empty, GetHandlerMethodName(symbol, handlerName), GetPartialHandlerMethodName(symbol, handlerName), false, null, ImmutableArray.Empty, + ImmutableArray.Empty, GetRequestMethodName(syntax, symbol, handlerName), null, symbol.ContainingNamespace.ToDisplayString(), @@ -55,70 +59,92 @@ HashSet additionalUsings if (symbol.GetAttribute(generateHandlerAttributeSymbol) is { } generateHandlerData) { - attributes = attributes with { + attributes = attributes with + { GenerateHandler = SyntaxAttributeData.Parse(generateHandlerData), AllowDerivedRequests = generateHandlerData .NamedArguments .Select(z => z is { Key: "AllowDerivedRequests", Value: { Value: true } }) .Count(z => z) is > 0, - HandlerNamespace = generateHandlerData is { ConstructorArguments: { Length: >=1 } arguments } + HandlerNamespace = generateHandlerData is { ConstructorArguments: { Length: >= 1 } arguments } ? arguments[0].Value as string ?? attributes.HandlerNamespace : attributes.HandlerNamespace, HandlerName = generateHandlerData is { NamedArguments: { Length: >= 1 } namedArguments } ? namedArguments .Select(z => z is { Key: "Name", Value: { Value: string str } } ? str : null) - .FirstOrDefault(z => z is { Length: >0 }) ?? attributes.HandlerName + .FirstOrDefault(z => z is { Length: > 0 }) ?? attributes.HandlerName : attributes.HandlerName - }; + }; - attributes = attributes with { + attributes = attributes with + { HandlerMethodName = GetHandlerMethodName(symbol, attributes.HandlerName), PartialHandlerMethodName = GetPartialHandlerMethodName(symbol, attributes.HandlerName), RequestMethodName = GetRequestMethodName(syntax, symbol, attributes.HandlerName) - }; + }; } if (symbol.GetAttribute(generateHandlerMethodsAttributeSymbol) is { } generateHandlerMethodsData) { var data = SyntaxAttributeData.Parse(generateHandlerMethodsData); - attributes = attributes with { + var diagnostics = new List(); + var syntaxes = new List(); + foreach (var registry in GetHandlerRegistries( + syntax, + generateHandlerMethodsData, + symbol, + additionalUsings + )) + { + if (registry.diagnostic is { }) diagnostics.Add(registry.diagnostic); + if (registry.typeSyntax is { }) syntaxes.Add(registry.typeSyntax); + } + + attributes = attributes with + { GenerateHandlerMethods = data, HandlerMethodName = generateHandlerMethodsData .NamedArguments .Select(z => z is { Key: "MethodName", Value: { Value: string value } } ? value : null) .FirstOrDefault(z => z is not null) ?? attributes.HandlerMethodName, - HandlerRegistries = GetHandlerRegistries( - a => cacheDiagnostic(syntax, a), - generateHandlerMethodsData, - symbol, - additionalUsings - ).ToImmutableArray() - }; + HandlerRegistries = syntaxes.ToImmutableArray(), + HandlerRegistryDiagnostics = diagnostics.ToImmutableArray() + }; } if (symbol.GetAttribute(generateRequestMethodsAttributeSymbol) is { } generateRequestMethodsData) { var data = SyntaxAttributeData.Parse(generateRequestMethodsData); - attributes = attributes with { + var diagnostics = new List(); + var syntaxes = new List(); + foreach (var registry in GetRequestProxies( + syntax, + generateRequestMethodsData, + symbol, + additionalUsings + )) + { + if (registry.diagnostic is { }) diagnostics.Add(registry.diagnostic); + if (registry.typeSyntax is { }) syntaxes.Add(registry.typeSyntax); + } + + attributes = attributes with + { GenerateRequestMethods = data, RequestMethodName = generateRequestMethodsData .NamedArguments .Select(z => z is { Key: "MethodName", Value: { Value: string value } } ? value : null) .FirstOrDefault(z => z is not null) ?? attributes.RequestMethodName, - RequestProxies = GetRequestProxies( - (a) => cacheDiagnostic(syntax, a), - generateRequestMethodsData, - symbol, - additionalUsings - ).ToImmutableArray() - }; + RequestProxies = syntaxes.ToImmutableArray(), + RequestProxyDiagnostics = diagnostics.ToImmutableArray() + }; } return attributes; } - private static IEnumerable GetHandlerRegistries( - Action> cacheDiagnostic, + private static IEnumerable<(TypeSyntax? typeSyntax, Diagnostic? diagnostic)> GetHandlerRegistries( + TypeDeclarationSyntax typeDeclarationSyntax, AttributeData attributeData, INamedTypeSymbol interfaceType, HashSet additionalUsings @@ -130,7 +156,7 @@ HashSet additionalUsings { if (item.Expression is TypeOfExpressionSyntax typeOfExpressionSyntax) { - yield return typeOfExpressionSyntax.Type; + yield return ( typeOfExpressionSyntax.Type, null ); foundValue = true; } } @@ -142,11 +168,15 @@ HashSet additionalUsings var attribute = interfaceType.GetAttributes().First(z => z.AttributeClass?.Name == "MethodAttribute"); if (attribute.ConstructorArguments.Length < 2) { - cacheDiagnostic(static c => Diagnostic.Create(GeneratorDiagnostics.MissingDirection, c.AttributeLists.GetAttribute("GenerateHandlerMethods")?.GetLocation())); + yield return ( null, Diagnostic.Create( + GeneratorDiagnostics.MissingDirection, + typeDeclarationSyntax.AttributeLists.GetAttribute("GenerateHandlerMethods")?.GetLocation() + ) + ); yield break; } - var direction = (int) interfaceType.GetAttributes().First(z => z.AttributeClass?.Name == "MethodAttribute").ConstructorArguments[1].Value!; + var direction = (int)interfaceType.GetAttributes().First(z => z.AttributeClass?.Name == "MethodAttribute").ConstructorArguments[1].Value!; /* Unspecified = 0b0000, @@ -160,12 +190,12 @@ HashSet additionalUsings additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Server"); if (( direction & 0b0001 ) == 0b0001) { - yield return LanguageProtocolServerToClientRegistry; + yield return ( LanguageProtocolServerToClientRegistry, null ); } if (( direction & 0b0010 ) == 0b0010) { - yield return LanguageProtocolClientToServerRegistry; + yield return ( LanguageProtocolClientToServerRegistry, null ); } yield break; @@ -176,11 +206,16 @@ HashSet additionalUsings var attribute = interfaceType.GetAttributes().First(z => z.AttributeClass?.Name == "MethodAttribute"); if (attribute.ConstructorArguments.Length < 2) { - cacheDiagnostic(static c => Diagnostic.Create(GeneratorDiagnostics.MissingDirection, c.AttributeLists.GetAttribute("GenerateHandlerMethods")?.GetLocation())); + yield return ( + null, + Diagnostic.Create( + GeneratorDiagnostics.MissingDirection, typeDeclarationSyntax.AttributeLists.GetAttribute("GenerateHandlerMethods")?.GetLocation() + ) + ); yield break; } - var direction = (int) interfaceType.GetAttributes().First(z => z.AttributeClass?.Name == "MethodAttribute").ConstructorArguments[1].Value!; + var direction = (int)interfaceType.GetAttributes().First(z => z.AttributeClass?.Name == "MethodAttribute").ConstructorArguments[1].Value!; /* Unspecified = 0b0000, @@ -194,18 +229,23 @@ HashSet additionalUsings additionalUsings.Add("OmniSharp.Extensions.DebugAdapter.Protocol.Server"); if (( direction & 0b0001 ) == 0b0001) { - yield return DebugProtocolServerToClientRegistry; + yield return ( DebugProtocolServerToClientRegistry, null ); } if (( direction & 0b0010 ) == 0b0010) { - yield return DebugProtocolClientToServerRegistry; + yield return ( DebugProtocolClientToServerRegistry, null ); } yield break; } - cacheDiagnostic(static c => Diagnostic.Create(GeneratorDiagnostics.CouldNotInferRequestRouter, c.AttributeLists.GetAttribute("GenerateHandlerMethods")?.GetLocation())); + yield return ( + null, + Diagnostic.Create( + GeneratorDiagnostics.CouldNotInferRequestRouter, typeDeclarationSyntax.AttributeLists.GetAttribute("GenerateHandlerMethods")?.GetLocation() + ) + ); } private static NameSyntax LanguageProtocolServerToClientRegistry { get; } = @@ -221,8 +261,8 @@ HashSet additionalUsings SyntaxFactory.IdentifierName("IDebugAdapterServerRegistry"); - private static IEnumerable GetRequestProxies( - Action> cacheDiagnostic, + private static IEnumerable<(TypeSyntax? typeSyntax, Diagnostic? diagnostic)> GetRequestProxies( + TypeDeclarationSyntax typeDeclarationSyntax, AttributeData attributeData, INamedTypeSymbol interfaceType, HashSet additionalUsings @@ -234,7 +274,7 @@ HashSet additionalUsings { if (item.Expression is TypeOfExpressionSyntax typeOfExpressionSyntax) { - yield return typeOfExpressionSyntax.Type; + yield return ( typeOfExpressionSyntax.Type, null ); foundValue = true; } } @@ -246,11 +286,16 @@ HashSet additionalUsings var attribute = interfaceType.GetAttributes().First(z => z.AttributeClass?.Name == "MethodAttribute"); if (attribute.ConstructorArguments.Length < 2) { - cacheDiagnostic(static c => Diagnostic.Create(GeneratorDiagnostics.MissingDirection, c.AttributeLists.GetAttribute("GenerateRequestMethods")?.GetLocation())); + yield return ( null, + Diagnostic.Create( + GeneratorDiagnostics.MissingDirection, + typeDeclarationSyntax.AttributeLists.GetAttribute("GenerateRequestMethods")?.GetLocation() + ) + ); yield break; } - var direction = (int) interfaceType.GetAttributes().First(z => z.AttributeClass?.Name == "MethodAttribute")!.ConstructorArguments[1].Value!; + var direction = (int)interfaceType.GetAttributes().First(z => z.AttributeClass?.Name == "MethodAttribute")!.ConstructorArguments[1].Value!; /* Unspecified = 0b0000, @@ -265,12 +310,12 @@ HashSet additionalUsings additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Client"); if (( direction & 0b0001 ) == 0b0001) { - yield return LanguageProtocolServerToClient; + yield return ( LanguageProtocolServerToClient, null ); } if (( direction & 0b0010 ) == 0b0010) { - yield return LanguageProtocolClientToServer; + yield return ( LanguageProtocolClientToServer, null ); } yield break; @@ -281,11 +326,16 @@ HashSet additionalUsings var attribute = interfaceType.GetAttributes().First(z => z.AttributeClass?.Name == "MethodAttribute"); if (attribute.ConstructorArguments.Length < 2) { - cacheDiagnostic(static c => Diagnostic.Create(GeneratorDiagnostics.MissingDirection, c.AttributeLists.GetAttribute("GenerateRequestMethods")?.GetLocation())); + yield return ( null, + Diagnostic.Create( + GeneratorDiagnostics.MissingDirection, + typeDeclarationSyntax.AttributeLists.GetAttribute("GenerateRequestMethods")?.GetLocation() + ) + ); yield break; } - var direction = (int) interfaceType.GetAttributes().First(z => z.AttributeClass?.Name == "MethodAttribute").ConstructorArguments[1].Value!; + var direction = (int)interfaceType.GetAttributes().First(z => z.AttributeClass?.Name == "MethodAttribute").ConstructorArguments[1].Value!; /* Unspecified = 0b0000, @@ -298,18 +348,23 @@ HashSet additionalUsings if (( direction & 0b0001 ) == 0b0001) { - yield return DebugProtocolServerToClient; + yield return ( DebugProtocolServerToClient, null ); } if (( direction & 0b0010 ) == 0b0010) { - yield return DebugProtocolClientToServer; + yield return ( DebugProtocolClientToServer, null ); } yield break; } - cacheDiagnostic(static c => Diagnostic.Create(GeneratorDiagnostics.CouldNotInferRequestRouter, c.AttributeLists.GetAttribute("GenerateRequestMethods")?.GetLocation())); + yield return ( null, + Diagnostic.Create( + GeneratorDiagnostics.CouldNotInferRequestRouter, + typeDeclarationSyntax.AttributeLists.GetAttribute("GenerateRequestMethods")?.GetLocation() + ) + ); } private static NameSyntax LanguageProtocolServerToClient { get; } = diff --git a/src/JsonRpc.Generators/Contexts/LspAttributes.cs b/src/JsonRpc.Generators/Contexts/LspAttributes.cs index 4c55f36e2..3dda28f14 100644 --- a/src/JsonRpc.Generators/Contexts/LspAttributes.cs +++ b/src/JsonRpc.Generators/Contexts/LspAttributes.cs @@ -1,7 +1,6 @@ using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; namespace OmniSharp.Extensions.JsonRpc.Generators.Contexts { @@ -23,10 +22,9 @@ bool CanHaveData ) { public static LspAttributes? Parse( - GeneratorExecutionContext context, - AddCacheSource addCacheSource, - ReportCacheDiagnostic cacheDiagnostic, + Compilation compilation, TypeDeclarationSyntax syntax, + SemanticModel model, INamedTypeSymbol symbol) { var prefix = "OmniSharp.Extensions.LanguageServer.Protocol.Generation"; @@ -40,7 +38,7 @@ bool CanHaveData }; { - var attributeSymbol = context.Compilation.GetTypeByMetadataName($"{prefix}.GenerateTypedDataAttribute"); + var attributeSymbol = compilation.GetTypeByMetadataName($"{prefix}.GenerateTypedDataAttribute"); if (symbol.GetAttribute(attributeSymbol) is { } data && data.ApplicationSyntaxReference?.GetSyntax() is AttributeSyntax attributeSyntax) { attributes = attributes with { @@ -50,7 +48,7 @@ bool CanHaveData } } { - var attributeSymbol = context.Compilation.GetTypeByMetadataName($"{prefix}.GenerateContainerAttribute"); + var attributeSymbol = compilation.GetTypeByMetadataName($"{prefix}.GenerateContainerAttribute"); if (symbol.GetAttribute(attributeSymbol) is { } data && data.ApplicationSyntaxReference?.GetSyntax() is AttributeSyntax attributeSyntax) { attributes = attributes with { @@ -60,7 +58,7 @@ bool CanHaveData } } { - var attributeSymbol = context.Compilation.GetTypeByMetadataName($"{prefix}.RegistrationOptionsKeyAttribute"); + var attributeSymbol = compilation.GetTypeByMetadataName($"{prefix}.RegistrationOptionsKeyAttribute"); if (symbol.GetAttribute(attributeSymbol) is { ConstructorArguments: { Length: >=1 } arguments } data && arguments[0].Kind is TypedConstantKind.Primitive && arguments[0].Value is string value && data.ApplicationSyntaxReference?.GetSyntax() is AttributeSyntax attributeSyntax) @@ -72,21 +70,21 @@ bool CanHaveData } } { - var (syntaxAttributeData, syntaxSymbol) = ExtractAttributeTypeData(symbol, context.Compilation.GetTypeByMetadataName($"{prefix}.CapabilityAttribute")); + var (syntaxAttributeData, syntaxSymbol) = ExtractAttributeTypeData(symbol, compilation.GetTypeByMetadataName($"{prefix}.CapabilityAttribute")); attributes = attributes with { CapabilityAttribute = syntaxAttributeData, Capability = syntaxSymbol }; } { - var (syntaxAttributeData, syntaxSymbol) = ExtractAttributeTypeData(symbol, context.Compilation.GetTypeByMetadataName($"{prefix}.ResolverAttribute")); + var (syntaxAttributeData, syntaxSymbol) = ExtractAttributeTypeData(symbol, compilation.GetTypeByMetadataName($"{prefix}.ResolverAttribute")); attributes = attributes with { ResolverAttribute = syntaxAttributeData, Resolver = syntaxSymbol }; } { - var (syntaxAttributeData, syntaxSymbol) = ExtractAttributeTypeData(symbol, context.Compilation.GetTypeByMetadataName($"{prefix}.RegistrationOptionsAttribute")); + var (syntaxAttributeData, syntaxSymbol) = ExtractAttributeTypeData(symbol, compilation.GetTypeByMetadataName($"{prefix}.RegistrationOptionsAttribute")); attributes = attributes with { RegistrationOptionsAttribute = syntaxAttributeData, RegistrationOptions = syntaxSymbol diff --git a/src/JsonRpc.Generators/Contexts/NotificationItem.cs b/src/JsonRpc.Generators/Contexts/NotificationItem.cs index 6d9d7a111..24b2eab64 100644 --- a/src/JsonRpc.Generators/Contexts/NotificationItem.cs +++ b/src/JsonRpc.Generators/Contexts/NotificationItem.cs @@ -16,10 +16,10 @@ record NotificationItem( HashSet AdditionalUsings, List AssemblyJsonRpcHandlersAttributeArguments, SemanticModel Model, - GeneratorExecutionContext Context + Compilation Compilation ) : GeneratorData( TypeDeclaration, TypeSymbol, JsonRpcAttributes, LspAttributes, DapAttributes, Request, Capability, RegistrationOptions, - AdditionalUsings, AssemblyJsonRpcHandlersAttributeArguments, Model, Context + AdditionalUsings, AssemblyJsonRpcHandlersAttributeArguments, Model, Compilation ); } diff --git a/src/JsonRpc.Generators/Contexts/RegistrationOptionAttributes.cs b/src/JsonRpc.Generators/Contexts/RegistrationOptionAttributes.cs index f94a2844d..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, @@ -20,18 +19,19 @@ record RegistrationOptionAttributes( bool ImplementsStaticRegistrationOptions ) { - public static RegistrationOptionAttributes? Parse(GeneratorExecutionContext context, TypeDeclarationSyntax syntax, INamedTypeSymbol symbol) + public static RegistrationOptionAttributes? Parse(Compilation compilation, TypeDeclarationSyntax syntax, INamedTypeSymbol symbol) { var registrationOptionsAttributeSymbol = - context.Compilation.GetTypeByMetadataName($"OmniSharp.Extensions.LanguageServer.Protocol.Generation.GenerateRegistrationOptionsAttribute"); + compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Generation.GenerateRegistrationOptionsAttribute"); var registrationOptionsConverterAttributeSymbol = - context.Compilation.GetTypeByMetadataName($"OmniSharp.Extensions.LanguageServer.Protocol.RegistrationOptionsConverterAttribute"); -// var registrationOptionsInterfaceSymbol = context.Compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.IRegistrationOptions"); + compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.RegistrationOptionsConverterAttribute"); +// var registrationOptionsInterfaceSymbol = compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.IRegistrationOptions"); var textDocumentRegistrationOptionsInterfaceSymbol = - context.Compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.ITextDocumentRegistrationOptions"); - var workDoneProgressOptionsInterfaceSymbol = context.Compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.IWorkDoneProgressOptions"); + compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.ITextDocumentRegistrationOptions"); + var workDoneProgressOptionsInterfaceSymbol = + compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.IWorkDoneProgressOptions"); var staticRegistrationOptionsInterfaceSymbol = - context.Compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.IStaticRegistrationOptions"); + compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.IStaticRegistrationOptions"); if (!( symbol.GetAttribute(registrationOptionsAttributeSymbol) is { } data )) return null; if (!( data.ApplicationSyntaxReference?.GetSyntax() is AttributeSyntax attributeSyntax )) return null; @@ -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/Contexts/RequestItem.cs b/src/JsonRpc.Generators/Contexts/RequestItem.cs index 109d2ab88..3b5103243 100644 --- a/src/JsonRpc.Generators/Contexts/RequestItem.cs +++ b/src/JsonRpc.Generators/Contexts/RequestItem.cs @@ -20,11 +20,11 @@ record RequestItem( HashSet AdditionalUsings, List AssemblyJsonRpcHandlersAttributeArguments, SemanticModel Model, - GeneratorExecutionContext Context + Compilation Compilation ) : GeneratorData( TypeDeclaration, TypeSymbol, JsonRpcAttributes, LspAttributes, DapAttributes, Request, Capability, RegistrationOptions, - AdditionalUsings, AssemblyJsonRpcHandlersAttributeArguments, Model, Context + AdditionalUsings, AssemblyJsonRpcHandlersAttributeArguments, Model, Compilation ); // record PartialItem(TypeSyntax Syntax, INamedTypeSymbol Symbol, SyntaxSymbol Item) : SyntaxSymbol(Syntax, Symbol); diff --git a/src/JsonRpc.Generators/EnumLikeStringGenerator.cs b/src/JsonRpc.Generators/EnumLikeStringGenerator.cs index bef33165e..7d395976e 100644 --- a/src/JsonRpc.Generators/EnumLikeStringGenerator.cs +++ b/src/JsonRpc.Generators/EnumLikeStringGenerator.cs @@ -1,83 +1,93 @@ -using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace OmniSharp.Extensions.JsonRpc.Generators { [Generator] - public class EnumLikeStringGenerator : CachedSourceGenerator + public class EnumLikeStringGenerator : IIncrementalGenerator { - protected override void Execute( - GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource addCacheSource, - ReportCacheDiagnostic cacheDiagnostic - ) + public void Initialize(IncrementalGeneratorInitializationContext context) { - foreach (var candidate in syntaxReceiver.Candidates) - { - var model = context.Compilation.GetSemanticModel(candidate.SyntaxTree); - var symbol = model.GetDeclaredSymbol(candidate); - if (symbol is null) continue; + var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( + (node, _) => node is StructDeclarationSyntax tds && tds.AttributeLists.ContainsAttribute("StringEnum"), + (syntaxContext, _) => syntaxContext + ); - if (!candidate.Modifiers.Any(z => z.IsKind(SyntaxKind.PartialKeyword))) - { - cacheDiagnostic(candidate, static c => Diagnostic.Create(GeneratorDiagnostics.MustBePartial, c.Identifier.GetLocation(), c.Identifier.Text)); - continue; - } + context.RegisterSourceOutput(syntaxProvider, GenerateEnum); + } - if (!candidate.Modifiers.Any(z => z.IsKind(SyntaxKind.ReadOnlyKeyword))) - { - cacheDiagnostic(candidate, static c => Diagnostic.Create(GeneratorDiagnostics.MustBeReadOnly, c.Identifier.GetLocation(), c.Identifier.Text)); - continue; - } + private void GenerateEnum(SourceProductionContext context, GeneratorSyntaxContext syntaxContext) + { + var candidate = (StructDeclarationSyntax)syntaxContext.Node; + var model = syntaxContext.SemanticModel; + var symbol = model.GetDeclaredSymbol(syntaxContext.Node); + if (symbol is null) return; - var cu = CompilationUnit( - List(), - List(), - List(), - SingletonList( - NamespaceDeclaration(ParseName(symbol.ContainingNamespace.ToDisplayString())) - .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")) - ) - .WithLeadingTrivia() - .WithTrailingTrivia() - .WithLeadingTrivia(Comment(Preamble.GeneratedByATool), Trivia(NullableDirectiveTrivia(Token(SyntaxKind.EnableKeyword), true))) - .WithTrailingTrivia(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.RestoreKeyword), true)), CarriageReturnLineFeed); + if (!candidate.Modifiers.Any(z => z.IsKind(SyntaxKind.PartialKeyword))) + { + context.ReportDiagnostic(Diagnostic.Create(GeneratorDiagnostics.MustBePartial, candidate.Identifier.GetLocation(), candidate.Identifier.Text)); + return; + } - addCacheSource( - $"{Path.GetFileNameWithoutExtension(candidate.SyntaxTree.FilePath)}_{candidate.Identifier.Text}{( candidate.Arity > 0 ? candidate.Arity.ToString() : "" )}.cs", - candidate, - cu.NormalizeWhitespace().GetText(Encoding.UTF8) - ); + if (!candidate.Modifiers.Any(z => z.IsKind(SyntaxKind.ReadOnlyKeyword))) + { + context.ReportDiagnostic(Diagnostic.Create(GeneratorDiagnostics.MustBeReadOnly, candidate.Identifier.GetLocation(), candidate.Identifier.Text)); + return; } + + var cu = CompilationUnit( + List(), List(), List(), SingletonList( + NamespaceDeclaration(ParseName(symbol.ContainingNamespace.ToDisplayString())) + .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")) + ) + .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) + ); } 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")) @@ -90,7 +100,8 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithAttributeLists( List( - new[] { + new[] + { AttributeList( SingletonSeparatedList( Attribute(IdentifierName("JsonConverter")) @@ -124,7 +135,8 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithMembers( List( - new MemberDeclarationSyntax[] { + new MemberDeclarationSyntax[] + { FieldDeclaration( VariableDeclaration( GenericName(Identifier("Lazy")) @@ -133,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)) + ) ) ) ) @@ -152,7 +166,9 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax GenericName(Identifier("IReadOnlyList")) .WithTypeArgumentList( TypeArgumentList( - SingletonSeparatedList(IdentifierName(syntax.Identifier.Text)) + SingletonSeparatedList( + IdentifierName(syntax.Identifier.Text) + ) ) ) ) @@ -168,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) + ) + ) ) ) ) @@ -346,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( @@ -368,10 +236,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword) ) ) .WithExpressionBody( @@ -402,10 +267,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PrivateKeyword), - Token(SyntaxKind.ReadOnlyKeyword) - } + Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword) ) ), ConstructorDeclaration( @@ -448,10 +310,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword) ) ) .WithParameterList( @@ -495,10 +354,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword) ) ) .WithParameterList( @@ -533,10 +389,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.OverrideKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword) ) ) .WithExpressionBody( @@ -631,10 +484,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.OverrideKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword) ) ) .WithParameterList( @@ -718,10 +568,7 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax ) .WithModifiers( TokenList( - new[] { - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.OverrideKeyword) - } + Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword) ) ) .WithExpressionBody( @@ -746,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") ) @@ -804,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") ) @@ -860,47 +703,8 @@ private static StructDeclarationSyntax GetImplementation(StructDeclarationSyntax } ) ) + .NormalizeWhitespace() ; } - - public EnumLikeStringGenerator() : base(() => new SyntaxReceiver(Cache)) - { - } - - public static CacheContainer Cache = new(); - - public class SyntaxReceiver : SyntaxReceiverCache - { - public List Candidates { get; } = new(); - - public SyntaxReceiver(CacheContainer cacheContainer) : base(cacheContainer) - { - } - - public override string? GetKey(StructDeclarationSyntax syntax) - { - var hasher = new CacheKeyHasher(); - hasher.Append(syntax.SyntaxTree.FilePath); - hasher.Append(syntax.Keyword.Text); - hasher.Append(syntax.Identifier.Text); - hasher.Append(syntax.TypeParameterList); - hasher.Append(syntax.AttributeLists); - hasher.Append(syntax.BaseList); - - return hasher; - } - - /// - /// Called for every syntax node in the compilation, we can inspect the nodes and save any information useful for generation - /// - public override void OnVisitNode(StructDeclarationSyntax syntaxNode) - { - // any field with at least one attribute is a candidate for property generation - if (syntaxNode.AttributeLists.ContainsAttribute("StringEnum")) - { - Candidates.Add(syntaxNode); - } - } - } } } diff --git a/src/JsonRpc.Generators/GenerateHandlerMethodsGenerator.cs b/src/JsonRpc.Generators/GenerateHandlerMethodsGenerator.cs index a07d42697..51e875466 100644 --- a/src/JsonRpc.Generators/GenerateHandlerMethodsGenerator.cs +++ b/src/JsonRpc.Generators/GenerateHandlerMethodsGenerator.cs @@ -7,7 +7,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; using OmniSharp.Extensions.JsonRpc.Generators.Contexts; using OmniSharp.Extensions.JsonRpc.Generators.Strategies; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -15,155 +14,172 @@ namespace OmniSharp.Extensions.JsonRpc.Generators { [Generator] - public class GenerateHandlerMethodsGenerator : CachedSourceGenerator + public class GenerateHandlerMethodsGenerator : IIncrementalGenerator { - protected override void Execute( - GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource addCacheSource, - ReportCacheDiagnostic cacheDiagnostic + public void Initialize(IncrementalGeneratorInitializationContext context) + { + var _attributes = "GenerateHandler,GenerateRequestMethods,GenerateHandlerMethods"; + var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( + (syntaxNode, _) => + syntaxNode is TypeDeclarationSyntax tds + and (ClassDeclarationSyntax or RecordDeclarationSyntax or InterfaceDeclarationSyntax) + && tds.AttributeLists.ContainsAttribute(_attributes), (syntaxContext, _) => syntaxContext + ) + .Combine(context.CompilationProvider) + .Select( + (tuple, _) => + { + var (syntaxContext, compilaiton) = tuple; + var additionalUsings = new HashSet + { + "System", + "System.Collections.Generic", + "System.Threading", + "System.Threading.Tasks", + "MediatR", + "Microsoft.Extensions.DependencyInjection" + }; + + GeneratorData? actionItem = null; + Diagnostic? diagnostic = null; + + try + { + actionItem = GeneratorData.Create( + compilaiton, (TypeDeclarationSyntax)syntaxContext.Node, syntaxContext.SemanticModel, additionalUsings + ); + } + catch (Exception e) + { + diagnostic = Diagnostic.Create( + GeneratorDiagnostics.Exception, syntaxContext.Node.GetLocation(), e.Message, + e.StackTrace ?? string.Empty + ); + Debug.WriteLine(e); + Debug.WriteLine(e.StackTrace); + } + + return ( actionItem, diagnostic, additionalUsings ); + } + ); + + context.RegisterSourceOutput(syntaxProvider, GenerateHandlerMethods); + 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 ) { - var handlers = new List(); - foreach (var candidateClass in syntaxReceiver.Candidates) + var (actionItem, diagnostic, additionalUsings) = valueTuple; + // context.ReportDiagnostic(Diagnostic.Create(GeneratorDiagnostics.Message, null, $"candidate: {candidateClass.Identifier.ToFullString()}")); + // can this be async??? + context.CancellationToken.ThrowIfCancellationRequested(); + + if (actionItem is null) { -// context.ReportDiagnostic(Diagnostic.Create(GeneratorDiagnostics.Message, null, $"candidate: {candidateClass.Identifier.ToFullString()}")); - // can this be async??? - context.CancellationToken.ThrowIfCancellationRequested(); - - var additionalUsings = new HashSet { - "System", - "System.Collections.Generic", - "System.Threading", - "System.Threading.Tasks", - "MediatR", - "Microsoft.Extensions.DependencyInjection" - }; - - GeneratorData? actionItem = null; - - try - { - actionItem = GeneratorData.Create(context, candidateClass, addCacheSource, cacheDiagnostic, additionalUsings); - } - catch (Exception e) - { - context.ReportDiagnostic(Diagnostic.Create(GeneratorDiagnostics.Exception, candidateClass.GetLocation(), e.Message, e.StackTrace ?? string.Empty)); - Debug.WriteLine(e); - Debug.WriteLine(e.StackTrace); - } + context.ReportDiagnostic(diagnostic!); + return; + } - if (actionItem is null) continue; - - var members = CompilationUnitGeneratorStrategies.Aggregate( - new List(), (m, strategy) => { - try - { - m.AddRange(strategy.Apply(actionItem)); - } - catch (Exception e) - { - context.ReportDiagnostic( - Diagnostic.Create( - GeneratorDiagnostics.Exception, candidateClass.GetLocation(), $"Strategy {strategy.GetType().FullName} failed!" + " - " + e.Message, - e.StackTrace ?? string.Empty - ) - ); - Debug.WriteLine($"Strategy {strategy.GetType().FullName} failed!"); - Debug.WriteLine(e); - Debug.WriteLine(e.StackTrace); - } - - return m; - } - ); - - if (!members.Any()) continue; - - var namespacesMapping = new Dictionary() { - ["OmniSharp.Extensions.DebugAdapter"] = new[] { - "OmniSharp.Extensions.DebugAdapter.Protocol", - "OmniSharp.Extensions.DebugAdapter.Protocol.Models", - "OmniSharp.Extensions.DebugAdapter.Protocol.Events", - "OmniSharp.Extensions.DebugAdapter.Protocol.Requests" - }, - ["OmniSharp.Extensions.LanguageProtocol"] = new[] { - "OmniSharp.Extensions.LanguageServer.Protocol", - "OmniSharp.Extensions.LanguageServer.Protocol.Models" - }, - }; - - foreach (var assembly in actionItem.Context.Compilation.References - .Select(actionItem.Context.Compilation.GetAssemblyOrModuleSymbol) - .OfType() - .Concat(new[] { actionItem.Context.Compilation.Assembly })) + var candidateClass = actionItem.TypeDeclaration; + + var members = CompilationUnitGeneratorStrategies.Aggregate( + new List(), (m, strategy) => { - if (namespacesMapping.TryGetValue(assembly.Name, out var additionalNamespaceUsings)) + try { - foreach (var item in additionalNamespaceUsings) - { - additionalUsings.Add(item); - } + m.AddRange(strategy.Apply(context, actionItem)); } + catch (Exception e) + { + context.ReportDiagnostic( + Diagnostic.Create( + GeneratorDiagnostics.Exception, candidateClass.GetLocation(), + $"Strategy {strategy.GetType().FullName} failed!" + " - " + e.Message, e.StackTrace ?? string.Empty + ) + ); + Debug.WriteLine($"Strategy {strategy.GetType().FullName} failed!"); + Debug.WriteLine(e); + Debug.WriteLine(e.StackTrace); + } + + return m; } + ); - var existingUsings = candidateClass.SyntaxTree.GetCompilationUnitRoot() - .Usings - .Select(x => x.WithoutTrivia()) - .Union( - additionalUsings - .Except( - candidateClass.SyntaxTree.GetCompilationUnitRoot() - .Usings - .Where(z => z.Alias == null) - .Select(z => z.Name.ToFullString()) - ) - .Except(new [] { "" }) // I think there is a better way... but for now.. - .Distinct() - .Select(z => UsingDirective(IdentifierName(z))) - ) - .OrderBy(x => x.Name.ToFullString()) - .ToImmutableArray(); - - var cu = CompilationUnit( - List(), - List(existingUsings), - List(), - List(members) - ) - .WithLeadingTrivia(Comment(Preamble.GeneratedByATool)) - .WithTrailingTrivia(CarriageReturnLineFeed); - - addCacheSource( - $"{candidateClass.Identifier.Text}{( candidateClass.Arity > 0 ? candidateClass.Arity.ToString() : "" )}.cs", - candidateClass, - cu.NormalizeWhitespace().GetText(Encoding.UTF8) - ); - - handlers.AddRange(actionItem.AssemblyJsonRpcHandlersAttributeArguments); - } + if (!members.Any()) return; + var namespacesMapping = new Dictionary { - var namespaces = new HashSet() { "OmniSharp.Extensions.JsonRpc" }; - if (handlers.Any()) + ["OmniSharp.Extensions.DebugAdapter"] = new[] { - var types = handlers.ToArray(); - var cu = CompilationUnit() - .WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z))))) - .WithLeadingTrivia(Comment(Preamble.GeneratedByATool)) - .WithTrailingTrivia(CarriageReturnLineFeed); - while (types.Length > 0) + "OmniSharp.Extensions.DebugAdapter.Protocol", "OmniSharp.Extensions.DebugAdapter.Protocol.Models", + "OmniSharp.Extensions.DebugAdapter.Protocol.Events", "OmniSharp.Extensions.DebugAdapter.Protocol.Requests" + }, + ["OmniSharp.Extensions.LanguageProtocol"] = new[] + { "OmniSharp.Extensions.LanguageServer.Protocol", "OmniSharp.Extensions.LanguageServer.Protocol.Models" }, + }; + + foreach (var assembly in actionItem.Compilation.References.Select(actionItem.Compilation.GetAssemblyOrModuleSymbol) + .OfType() + .Concat(new[] { actionItem.Compilation.Assembly })) + { + if (namespacesMapping.TryGetValue(assembly.Name, out var additionalNamespaceUsings)) + { + foreach (var item in additionalNamespaceUsings) { - var innerTypes = types.Take(10).ToArray(); - types = types.Skip(10).ToArray(); - cu = cu.AddAttributeLists( - AttributeList( - target: AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), - SingletonSeparatedList(Attribute(IdentifierName("AssemblyJsonRpcHandlers"), AttributeArgumentList(SeparatedList(innerTypes)))) - ) - ); + additionalUsings.Add(item); } + } + } - context.AddSource("GeneratedAssemblyJsonRpcHandlers.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8)); + var existingUsings = candidateClass.SyntaxTree.GetCompilationUnitRoot() + .Usings.Select(x => x.WithoutTrivia()) + .Union( + additionalUsings.Except( + candidateClass.SyntaxTree.GetCompilationUnitRoot() + .Usings.Where(z => z.Alias == null) + .Select(z => z.Name.ToFullString()) + ) + .Except(new[] { "" }) // I think there is a better way... but for now.. + .Distinct() + .Select(z => UsingDirective(IdentifierName(z))) + ) + .OrderBy(x => x.Name.ToFullString()) + .ToImmutableArray(); + + var cu = CompilationUnit(List(), List(existingUsings), List(), List(members)); + + context.AddSource( + $"{candidateClass.Identifier.Text}{( candidateClass.Arity > 0 ? candidateClass.Arity.ToString() : "" )}.cs", + cu.NormalizeWhitespace().GetText(Encoding.UTF8) + ); + } + + private void GenerateAssemblyJsonRpcHandlers(SourceProductionContext context, ImmutableArray handlers) + { + var namespaces = new HashSet { "OmniSharp.Extensions.JsonRpc" }; + if (handlers.Any()) + { + var cu = CompilationUnit() + .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( + AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), + SingletonSeparatedList(Attribute(IdentifierName("AssemblyJsonRpcHandlers"), AttributeArgumentList(SeparatedList(innerTypes)))) + ) + ); } + + context.AddSource("GeneratedAssemblyJsonRpcHandlers.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8)); } } @@ -196,46 +212,5 @@ private static ImmutableArray GetCompilationU ); return compilationUnitStrategies; } - - public GenerateHandlerMethodsGenerator() : base(() => new SyntaxReceiver(Cache)) - { - } - - public static CacheContainer Cache = new(); - - public class SyntaxReceiver : SyntaxReceiverCache - { - private string _attributes; - public List Candidates { get; } = new(); - - public SyntaxReceiver(CacheContainer cache) : base(cache) - { - _attributes = "GenerateHandler,GenerateRequestMethods,GenerateHandlerMethods"; - } - - public override string? GetKey(TypeDeclarationSyntax syntax) - { - var hasher = new CacheKeyHasher(); - hasher.Append(syntax.SyntaxTree.FilePath); - hasher.Append(syntax.Keyword.Text); - hasher.Append(syntax.Identifier.Text); - hasher.Append(syntax.TypeParameterList); - hasher.Append(syntax.AttributeLists); - hasher.Append(syntax.BaseList); - return hasher; - } - - /// - /// Called for every syntax node in the compilation, we can inspect the nodes and save any information useful for generation - /// - public override void OnVisitNode(TypeDeclarationSyntax syntaxNode) - { - // any field with at least one attribute is a candidate for property generation - if (syntaxNode is ClassDeclarationSyntax or RecordDeclarationSyntax or InterfaceDeclarationSyntax && syntaxNode.AttributeLists.ContainsAttribute(_attributes)) - { - Candidates.Add(syntaxNode); - } - } - } } } diff --git a/src/JsonRpc.Generators/ICompilationUnitGeneratorStrategy.cs b/src/JsonRpc.Generators/ICompilationUnitGeneratorStrategy.cs index c3a147903..d7cc10336 100644 --- a/src/JsonRpc.Generators/ICompilationUnitGeneratorStrategy.cs +++ b/src/JsonRpc.Generators/ICompilationUnitGeneratorStrategy.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using OmniSharp.Extensions.JsonRpc.Generators.Contexts; @@ -6,6 +7,6 @@ namespace OmniSharp.Extensions.JsonRpc.Generators { internal interface ICompilationUnitGeneratorStrategy { - IEnumerable Apply(GeneratorData item); + IEnumerable Apply(SourceProductionContext context, GeneratorData item); } } diff --git a/src/JsonRpc.Generators/IExtensionMethodContextGeneratorStrategy.cs b/src/JsonRpc.Generators/IExtensionMethodContextGeneratorStrategy.cs index 7160e8285..8d3e5bff8 100644 --- a/src/JsonRpc.Generators/IExtensionMethodContextGeneratorStrategy.cs +++ b/src/JsonRpc.Generators/IExtensionMethodContextGeneratorStrategy.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using OmniSharp.Extensions.JsonRpc.Generators.Contexts; @@ -6,6 +7,6 @@ namespace OmniSharp.Extensions.JsonRpc.Generators { internal interface IExtensionMethodContextGeneratorStrategy { - IEnumerable Apply(ExtensionMethodContext extensionMethodContext, GeneratorData item); + IEnumerable Apply(SourceProductionContext context, ExtensionMethodContext extensionMethodContext, GeneratorData item); } } diff --git a/src/JsonRpc.Generators/IExtensionMethodGeneratorStrategy.cs b/src/JsonRpc.Generators/IExtensionMethodGeneratorStrategy.cs index c1bf09b8b..537177649 100644 --- a/src/JsonRpc.Generators/IExtensionMethodGeneratorStrategy.cs +++ b/src/JsonRpc.Generators/IExtensionMethodGeneratorStrategy.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using OmniSharp.Extensions.JsonRpc.Generators.Contexts; @@ -6,6 +7,6 @@ namespace OmniSharp.Extensions.JsonRpc.Generators { internal interface IExtensionMethodGeneratorStrategy { - IEnumerable Apply(GeneratorData item); + IEnumerable Apply(SourceProductionContext context, GeneratorData item); } } diff --git a/src/JsonRpc.Generators/JsonRpc.Generators.csproj b/src/JsonRpc.Generators/JsonRpc.Generators.csproj index 8f0a15cc0..7854d8f6f 100644 --- a/src/JsonRpc.Generators/JsonRpc.Generators.csproj +++ b/src/JsonRpc.Generators/JsonRpc.Generators.csproj @@ -11,15 +11,15 @@ - - + + <_Parameter1>Generation.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - + diff --git a/src/JsonRpc.Generators/RegistrationOptionsGenerator.cs b/src/JsonRpc.Generators/RegistrationOptionsGenerator.cs index 00884886a..2c36fcf4f 100644 --- a/src/JsonRpc.Generators/RegistrationOptionsGenerator.cs +++ b/src/JsonRpc.Generators/RegistrationOptionsGenerator.cs @@ -1,284 +1,359 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; using OmniSharp.Extensions.JsonRpc.Generators.Contexts; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace OmniSharp.Extensions.JsonRpc.Generators { [Generator] - public class RegistrationOptionsGenerator : CachedSourceGenerator + public class RegistrationOptionsGenerator : IIncrementalGenerator { - private static string[] RequiredUsings = { + private static readonly string[] RequiredUsings = + { "OmniSharp.Extensions.LanguageServer.Protocol", "OmniSharp.Extensions.LanguageServer.Protocol.Serialization", "OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities", }; - protected override void Execute( - GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource addCacheSource, - ReportCacheDiagnostic cacheDiagnostic - ) - { - var compilation = context.Compilation; + private record AttributeData( + INamedTypeSymbol RegistrationOptionsInterfaceSymbol, INamedTypeSymbol TextDocumentRegistrationOptionsInterfaceSymbol, + INamedTypeSymbol WorkDoneProgressOptionsInterfaceSymbol, INamedTypeSymbol StaticRegistrationOptionsInterfaceSymbol + ); - 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 staticRegistrationOptionsInterfaceSymbol = compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.IStaticRegistrationOptions")!; + public void Initialize(IncrementalGeneratorInitializationContext context) + { + var attributes = context.CompilationProvider + .Select( + (compilation, _) => + { + 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 staticRegistrationOptionsInterfaceSymbol = + compilation.GetTypeByMetadataName( + "OmniSharp.Extensions.LanguageServer.Protocol.Models.IStaticRegistrationOptions" + )!; + return new AttributeData( + registrationOptionsInterfaceSymbol, textDocumentRegistrationOptionsInterfaceSymbol, + workDoneProgressOptionsInterfaceSymbol, staticRegistrationOptionsInterfaceSymbol + ); + } + ); + var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( + (syntaxNode, _) => + syntaxNode is TypeDeclarationSyntax tds and (ClassDeclarationSyntax or RecordDeclarationSyntax) + && tds.AttributeLists + .SelectMany(z => z.Attributes) + .Any(z => z.Name.ToFullString().Contains("GenerateRegistrationOptions")), + (syntaxContext, _) => syntaxContext + ) + .Combine(context.CompilationProvider) + .Select( + (tuple, _) => + { + var (syntaxContext, compilation) = tuple; + var typeSymbol = syntaxContext.SemanticModel.GetDeclaredSymbol((TypeDeclarationSyntax)syntaxContext.Node); + if (typeSymbol is not { }) return default!; + var data = RegistrationOptionAttributes.Parse( + compilation, + (TypeDeclarationSyntax)syntaxContext.Node, + typeSymbol + ); + return data is not { } + ? default! + : ( registrationOptions: (TypeDeclarationSyntax)syntaxContext.Node, + semanticModel: syntaxContext.SemanticModel, typeSymbol, data: data! ); + } + ) + .Where(z => z is { data: { } }) + .Combine(attributes) + .Select( + (tuple, _) => ( + tuple.Left.registrationOptions, tuple.Left.data, tuple.Left.semanticModel, tuple.Left.typeSymbol, + attributes: tuple.Right ) + ) + ; + + context.RegisterSourceOutput(syntaxProvider, GenerateRegistrationOptions); + context.RegisterSourceOutput( + syntaxProvider + .Select( + (tuple, _) => ( namespaces: tuple.typeSymbol.ContainingNamespace.ToDisplayString(), + AttributeArgument(TypeOfExpression(IdentifierName(tuple.typeSymbol.Name))) ) + ) + .Collect(), GenerateAssemblyRegistrationOptions + ); + } - foreach (var registrationOptions in syntaxReceiver.RegistrationOptions) + private void GenerateRegistrationOptions( + SourceProductionContext context, + (TypeDeclarationSyntax registrationOptions, RegistrationOptionAttributes data, SemanticModel semanticModel, INamedTypeSymbol typeSymbol, + AttributeData attributes) valueTuple + ) + { + var (registrationOptions, data, semanticModel, typeSymbol, attributes) = valueTuple; + try { - try + if (!registrationOptions.Modifiers.Any(z => z.IsKind(SyntaxKind.PartialKeyword))) { - var semanticModel = context.Compilation.GetSemanticModel(registrationOptions.SyntaxTree); - var typeSymbol = semanticModel.GetDeclaredSymbol(registrationOptions); + context.ReportDiagnostic( + Diagnostic.Create(GeneratorDiagnostics.MustBePartial, registrationOptions.Identifier.GetLocation(), registrationOptions.Identifier.Text) + ); + return; + } - if (typeSymbol is not { }) continue; - var data = RegistrationOptionAttributes.Parse(context, registrationOptions, typeSymbol); - if (data is not { }) continue; + var extendedRegistrationOptions = registrationOptions.WithAttributeLists(List()) + .WithBaseList( + BaseList( + SingletonSeparatedList( + SimpleBaseType( + ParseName(attributes.RegistrationOptionsInterfaceSymbol.ToDisplayString()) + ) + ) + ) + ) + .WithMembers(List()); - if (!registrationOptions.Modifiers.Any(z => z.IsKind(SyntaxKind.PartialKeyword))) - { - cacheDiagnostic(registrationOptions, static r => Diagnostic.Create(GeneratorDiagnostics.MustBePartial, r.Identifier.GetLocation(), r.Identifier.Text)); - continue; - } - var extendedRegistrationOptions = registrationOptions - .WithAttributeLists(List()) - .WithBaseList( - BaseList( - SingletonSeparatedList( - SimpleBaseType(ParseName(registrationOptionsInterfaceSymbol.ToDisplayString())) - ) - ) - ) - .WithMembers(List()); - - - var staticRegistrationOptions = registrationOptions - .WithIdentifier(Identifier($"StaticOptions")) - .WithMembers(List(registrationOptions.Members.OfType())) - .WithAttributeLists(List()); - - var staticBaseList = - registrationOptions.BaseList?.Types.Where(z => z.Type.GetSyntaxName() != textDocumentRegistrationOptionsInterfaceSymbol.Name).ToArray() - ?? Array.Empty(); - if (staticBaseList.Length > 0) - { - staticRegistrationOptions = staticRegistrationOptions.WithBaseList(BaseList(SeparatedList(staticBaseList))); - } - else + var staticRegistrationOptions = registrationOptions.WithIdentifier(Identifier("StaticOptions")) + .WithMembers( + List( + registrationOptions.Members.OfType() + ) + ) + .WithAttributeLists(List()); + + var staticBaseList = + registrationOptions.BaseList?.Types.Where(z => z.Type.GetSyntaxName() != attributes.TextDocumentRegistrationOptionsInterfaceSymbol.Name) + .ToArray() ?? Array.Empty(); + if (staticBaseList.Length > 0) + { + staticRegistrationOptions = staticRegistrationOptions.WithBaseList(BaseList(SeparatedList(staticBaseList))); + } + else + { + staticRegistrationOptions = staticRegistrationOptions.WithBaseList(null); + } + + if (data.KeyExpression is { }) + { + var attributeList = AttributeList( + SingletonSeparatedList( + Attribute( + IdentifierName("RegistrationOptionsKey"), AttributeArgumentList(SeparatedList(data.KeyExpression.Select(AttributeArgument))) + ) + ) + ); + extendedRegistrationOptions = extendedRegistrationOptions.AddAttributeLists(attributeList); + staticRegistrationOptions = staticRegistrationOptions.AddAttributeLists(attributeList); + } + + if (data.SupportsDocumentSelector && !data.ImplementsDocumentSelector) + { + if (registrationOptions.BaseList?.Types.Any( + z => z.Type.ToFullString().Contains(attributes.TextDocumentRegistrationOptionsInterfaceSymbol.Name) + ) != true) { - staticRegistrationOptions = staticRegistrationOptions.WithBaseList(null); + extendedRegistrationOptions = ExtendAndImplementInterface( + extendedRegistrationOptions, attributes.TextDocumentRegistrationOptionsInterfaceSymbol + ); } - if (data.KeyExpression is { }) - { - var attributeList = - AttributeList( - SingletonSeparatedList( - Attribute( - IdentifierName("RegistrationOptionsKey"), - AttributeArgumentList( - SeparatedList(data.KeyExpression.Select(AttributeArgument)) - ) + extendedRegistrationOptions = extendedRegistrationOptions.AddMembers( + PropertyDeclaration(NullableType(IdentifierName("DocumentSelector")), Identifier("DocumentSelector")) + .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))) + .WithAccessorList( + AccessorList( + List( + new[] + { + AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)), + AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + } ) ) - ); - extendedRegistrationOptions = extendedRegistrationOptions.AddAttributeLists(attributeList); - staticRegistrationOptions = staticRegistrationOptions.AddAttributeLists(attributeList); - } + ) + ); + } - if (data.SupportsDocumentSelector && !data.ImplementsDocumentSelector) + if (data.SupportsWorkDoneProgress && !data.ImplementsWorkDoneProgress) + { + if (registrationOptions.BaseList?.Types.Any(z => z.Type.GetSyntaxName() == attributes.WorkDoneProgressOptionsInterfaceSymbol.Name) != true) { - if (registrationOptions.BaseList?.Types.Any(z => z.Type.ToFullString().Contains(textDocumentRegistrationOptionsInterfaceSymbol.Name)) != true) - { - extendedRegistrationOptions = ExtendAndImplementInterface(extendedRegistrationOptions, textDocumentRegistrationOptionsInterfaceSymbol); - } - - extendedRegistrationOptions = extendedRegistrationOptions - .AddMembers( - PropertyDeclaration(NullableType(IdentifierName("DocumentSelector")), Identifier("DocumentSelector")) - .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))) - .WithAccessorList( - AccessorList( - List( - new[] { - AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)), - AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - } - ) - ) - ) - ); + extendedRegistrationOptions = ExtendAndImplementInterface( + extendedRegistrationOptions, attributes.WorkDoneProgressOptionsInterfaceSymbol + ); + staticRegistrationOptions = ExtendAndImplementInterface(staticRegistrationOptions, attributes.WorkDoneProgressOptionsInterfaceSymbol); } - if (data.SupportsWorkDoneProgress && !data.ImplementsWorkDoneProgress) - { - if (registrationOptions.BaseList?.Types.Any(z => z.Type.GetSyntaxName() == workDoneProgressOptionsInterfaceSymbol.Name) != true) - { - extendedRegistrationOptions = ExtendAndImplementInterface(extendedRegistrationOptions, workDoneProgressOptionsInterfaceSymbol); - staticRegistrationOptions = ExtendAndImplementInterface(staticRegistrationOptions, workDoneProgressOptionsInterfaceSymbol); - } - - staticRegistrationOptions = staticRegistrationOptions.AddMembers(GetWorkDoneProperty()); - extendedRegistrationOptions = extendedRegistrationOptions.AddMembers(GetWorkDoneProperty()); - } + staticRegistrationOptions = staticRegistrationOptions.AddMembers(GetWorkDoneProperty()); + extendedRegistrationOptions = extendedRegistrationOptions.AddMembers(GetWorkDoneProperty()); + } - if (data.SupportsStaticRegistrationOptions && !data.ImplementsStaticRegistrationOptions) + if (data.SupportsStaticRegistrationOptions && !data.ImplementsStaticRegistrationOptions) + { + if (registrationOptions.BaseList?.Types.Any(z => z.Type.GetSyntaxName() == attributes.StaticRegistrationOptionsInterfaceSymbol.Name) + != true) { - if (registrationOptions.BaseList?.Types.Any(z => z.Type.GetSyntaxName() == staticRegistrationOptionsInterfaceSymbol.Name) != true) - { - extendedRegistrationOptions = ExtendAndImplementInterface(extendedRegistrationOptions, staticRegistrationOptionsInterfaceSymbol); - staticRegistrationOptions = ExtendAndImplementInterface(staticRegistrationOptions, staticRegistrationOptionsInterfaceSymbol); - } - - staticRegistrationOptions = staticRegistrationOptions.AddMembers(GetIdProperty()); - extendedRegistrationOptions = extendedRegistrationOptions.AddMembers(GetIdProperty()); + extendedRegistrationOptions = ExtendAndImplementInterface( + extendedRegistrationOptions, attributes.StaticRegistrationOptionsInterfaceSymbol + ); + staticRegistrationOptions = ExtendAndImplementInterface(staticRegistrationOptions, attributes.StaticRegistrationOptionsInterfaceSymbol); } - if (data.RegistrationOptionsConverter is null - && CreateConverter(registrationOptions, staticRegistrationOptions.Members.OfType()) is { } converter) - { - extendedRegistrationOptions = extendedRegistrationOptions - .AddAttributeLists( - AttributeList( - SingletonSeparatedList( - Attribute( - IdentifierName("RegistrationOptionsConverterAttribute"), - AttributeArgumentList( - SingletonSeparatedList( - AttributeArgument( - TypeOfExpression(IdentifierName(converter.Identifier.Text)) + staticRegistrationOptions = staticRegistrationOptions.AddMembers(GetIdProperty()); + extendedRegistrationOptions = extendedRegistrationOptions.AddMembers(GetIdProperty()); + } + + if (data.RegistrationOptionsConverter is null && CreateConverter( + registrationOptions, staticRegistrationOptions.Members.OfType() + ) is { } converter) + { + extendedRegistrationOptions = extendedRegistrationOptions.AddAttributeLists( + AttributeList( + SingletonSeparatedList( + Attribute( + IdentifierName("RegistrationOptionsConverterAttribute"), + AttributeArgumentList( + SingletonSeparatedList( + AttributeArgument( + TypeOfExpression( + IdentifierName(converter.Identifier.Text) + ) + ) + ) + ) + ) + ) + ) ) - ) - ) - ) - ) - ) - ) - .AddMembers(converter); - } + .AddMembers(converter); + } - extendedRegistrationOptions = extendedRegistrationOptions.AddMembers(staticRegistrationOptions); + extendedRegistrationOptions = extendedRegistrationOptions.AddMembers(staticRegistrationOptions); - var members = new List() { extendedRegistrationOptions }; + var members = new List { extendedRegistrationOptions }; - var cu = CompilationUnit() - .WithUsings(registrationOptions.SyntaxTree.GetCompilationUnitRoot().Usings) - .AddMembers( - NamespaceDeclaration(ParseName(typeSymbol.ContainingNamespace.ToDisplayString())) - .WithMembers(List(members)) - .WithLeadingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.EnableKeyword), true)))) - .WithTrailingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.RestoreKeyword), true)))) - ) - .WithLeadingTrivia(Comment(Preamble.GeneratedByATool)) - .WithTrailingTrivia(CarriageReturnLineFeed); + var cu = CompilationUnit() + .WithUsings(registrationOptions.SyntaxTree.GetCompilationUnitRoot().Usings) + .AddMembers( + NamespaceDeclaration(ParseName(typeSymbol.ContainingNamespace.ToDisplayString())) + .WithMembers(List(members)) + .WithLeadingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.EnableKeyword), true)))) + .WithTrailingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.RestoreKeyword), true)))) + ); - foreach (var ns in RequiredUsings) + foreach (var ns in RequiredUsings) + { + if (cu.Usings.All(z => z.Name.ToFullString() != ns)) { - if (cu.Usings.All(z => z.Name.ToFullString() != ns)) - { - cu = cu.AddUsings(UsingDirective(ParseName(ns))); - } + cu = cu.AddUsings(UsingDirective(ParseName(ns))); } - - addCacheSource( - $"{registrationOptions.Identifier.Text}.cs", - registrationOptions, - cu.NormalizeWhitespace().GetText(Encoding.UTF8) - ); - } - catch (Exception e) - { - context.ReportDiagnostic(Diagnostic.Create(GeneratorDiagnostics.Exception, registrationOptions.GetLocation(), e.Message, e.StackTrace ?? string.Empty)); - Debug.WriteLine(e); - Debug.WriteLine(e.StackTrace); } + + context.AddSource($"{registrationOptions.Identifier.Text}.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8)); + } + catch (Exception e) + { + context.ReportDiagnostic( + Diagnostic.Create(GeneratorDiagnostics.Exception, registrationOptions.GetLocation(), e.Message, e.StackTrace ?? string.Empty) + ); + Debug.WriteLine(e); + Debug.WriteLine(e.StackTrace); } + } + private void GenerateAssemblyRegistrationOptions( + SourceProductionContext context, ImmutableArray<(string @namespace, AttributeArgumentSyntax argumentSyntax)> types + ) + { + var namespaces = new HashSet { "OmniSharp.Extensions.LanguageServer.Protocol" }; + if (types.Any()) { - var namespaces = new HashSet() { "OmniSharp.Extensions.LanguageServer.Protocol" }; - var types = syntaxReceiver.FoundNodes - .Concat(syntaxReceiver.RegistrationOptions) - .Select( - options => { - var semanticModel = context.Compilation.GetSemanticModel(options.SyntaxTree); - var typeSymbol = semanticModel.GetDeclaredSymbol(options)!; - namespaces.Add(typeSymbol.ContainingNamespace.ToDisplayString()); - return AttributeArgument(TypeOfExpression(IdentifierName(typeSymbol.Name))); - } - ) - .ToArray(); - if (types.Any()) + foreach (var item in types) { - var cu = CompilationUnit() - .WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z))))) - .AddAttributeLists( - AttributeList( - target: AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), - SingletonSeparatedList(Attribute(IdentifierName("AssemblyRegistrationOptions"), AttributeArgumentList(SeparatedList(types)))) + namespaces.Add(item.@namespace); + } + + var cu = CompilationUnit() + .WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z))))) + .AddAttributeLists( + AttributeList( + AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), + SingletonSeparatedList( + Attribute( + IdentifierName("AssemblyRegistrationOptions"), + AttributeArgumentList(SeparatedList(types.Select(z => z.argumentSyntax))) + ) ) ) - .WithLeadingTrivia(Comment(Preamble.GeneratedByATool)) - .WithTrailingTrivia(CarriageReturnLineFeed); + ); - context.AddSource("AssemblyRegistrationOptions.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8)); - } + context.AddSource("AssemblyRegistrationOptions.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8)); } + } - static TypeDeclarationSyntax ExtendAndImplementInterface(TypeDeclarationSyntax syntax, ITypeSymbol symbolToExtendFrom) - { - return syntax switch { - ClassDeclarationSyntax cd => cd.AddBaseListTypes(SimpleBaseType(ParseName(symbolToExtendFrom.ToDisplayString()))), - RecordDeclarationSyntax rd => rd.AddBaseListTypes(SimpleBaseType(ParseName(symbolToExtendFrom.ToDisplayString()))), - _ => throw new NotSupportedException() - }; - } - static PropertyDeclarationSyntax GetWorkDoneProperty() + private static TypeDeclarationSyntax ExtendAndImplementInterface(TypeDeclarationSyntax syntax, ITypeSymbol symbolToExtendFrom) + { + return syntax switch { - return PropertyDeclaration(PredefinedType(Token(SyntaxKind.BoolKeyword)), Identifier("WorkDoneProgress")) - .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))) - .WithAttributeLists( - SingletonList( - AttributeList( - SingletonSeparatedList(Attribute(IdentifierName("Optional"))) - ) + ClassDeclarationSyntax cd => cd.AddBaseListTypes(SimpleBaseType(ParseName(symbolToExtendFrom.ToDisplayString()))), + RecordDeclarationSyntax rd => rd.AddBaseListTypes(SimpleBaseType(ParseName(symbolToExtendFrom.ToDisplayString()))), + _ => throw new NotSupportedException() + }; + } + + private static PropertyDeclarationSyntax GetWorkDoneProperty() + { + return PropertyDeclaration(PredefinedType(Token(SyntaxKind.BoolKeyword)), Identifier("WorkDoneProgress")) + .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))) + .WithAttributeLists( + SingletonList( + AttributeList( + SingletonSeparatedList(Attribute(IdentifierName("Optional"))) ) ) - .WithAccessorList(CommonElements.GetSetAccessor); - } + ) + .WithAccessorList(CommonElements.GetSetAccessor); + } - static PropertyDeclarationSyntax GetIdProperty() - { - return PropertyDeclaration(NullableType(PredefinedType(Token(SyntaxKind.StringKeyword))), Identifier("Id")) - .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))) - .WithAttributeLists( - SingletonList( - AttributeList( - SingletonSeparatedList(Attribute(IdentifierName("Optional"))) - ) + private static PropertyDeclarationSyntax GetIdProperty() + { + return PropertyDeclaration(NullableType(PredefinedType(Token(SyntaxKind.StringKeyword))), Identifier("Id")) + .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))) + .WithAttributeLists( + SingletonList( + AttributeList( + SingletonSeparatedList(Attribute(IdentifierName("Optional"))) ) ) - .WithAccessorList(CommonElements.GetSetAccessor); - } + ) + .WithAccessorList(CommonElements.GetSetAccessor); } private static IEnumerable GetMapping(IEnumerable properties, IdentifierNameSyntax paramName) { return properties - .Where(z => z.AccessorList?.Accessors.Any(a => a.Keyword.Kind() == SyntaxKind.SetKeyword || a.Keyword.Kind() == SyntaxKind.InitKeyword) == true) + .Where( + z => z.AccessorList?.Accessors.Any(a => a.Keyword.Kind() == SyntaxKind.SetKeyword || a.Keyword.Kind() == SyntaxKind.InitKeyword) == true + ) .Select( property => AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, @@ -310,7 +385,8 @@ private static IEnumerable GetMapping(IEnumerable GetMapping(IEnumerable GetMapping(IEnumerable new SyntaxReceiver(Cache)) - { - } - - public static CacheContainer Cache = new(); - - public class SyntaxReceiver : SyntaxReceiverCache - { - public List RegistrationOptions { get; } = new(); - - public override string? GetKey(TypeDeclarationSyntax syntax) - { - var hasher = new CacheKeyHasher(); - hasher.Append(syntax.SyntaxTree.FilePath); - hasher.Append(syntax.Keyword.Text); - hasher.Append(syntax.Identifier.Text); - hasher.Append(syntax.TypeParameterList); - hasher.Append(syntax.AttributeLists); - hasher.Append(syntax.BaseList); - foreach (var item in syntax.Members.OfType().Select(z => z.Identifier.Text)) - { - hasher.Append(item); - } - - return hasher; - } - - /// - /// Called for every syntax node in the compilation, we can inspect the nodes and save any information useful for generation - /// - public override void OnVisitNode(TypeDeclarationSyntax syntaxNode) - { - if (syntaxNode is ClassDeclarationSyntax or RecordDeclarationSyntax - && syntaxNode.AttributeLists - .SelectMany(z => z.Attributes) - .Any(z => z.Name.ToFullString().Contains("GenerateRegistrationOptions")) - ) - { - RegistrationOptions.Add(syntaxNode); - } - } - - public SyntaxReceiver(CacheContainer cache) : base(cache) - { - } - } } } diff --git a/src/JsonRpc.Generators/Strategies/EnsureNamespaceStrategy.cs b/src/JsonRpc.Generators/Strategies/EnsureNamespaceStrategy.cs index 7f4482cde..76e48e5b7 100644 --- a/src/JsonRpc.Generators/Strategies/EnsureNamespaceStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/EnsureNamespaceStrategy.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using OmniSharp.Extensions.JsonRpc.Generators.Contexts; @@ -6,7 +7,7 @@ namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies { internal class EnsureNamespaceStrategy : IExtensionMethodGeneratorStrategy { - public IEnumerable Apply(GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, GeneratorData item) { if (item.Capability != null) item.AdditionalUsings.Add(item.Capability.Symbol.ContainingNamespace.ToDisplayString()); if (item.RegistrationOptions != null) item.AdditionalUsings.Add(item.RegistrationOptions.Symbol.ContainingNamespace.ToDisplayString()); diff --git a/src/JsonRpc.Generators/Strategies/ExtensionMethodGeneratorStrategy.cs b/src/JsonRpc.Generators/Strategies/ExtensionMethodGeneratorStrategy.cs index 0b8116e80..182210655 100644 --- a/src/JsonRpc.Generators/Strategies/ExtensionMethodGeneratorStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/ExtensionMethodGeneratorStrategy.cs @@ -19,13 +19,13 @@ public ExtensionMethodGeneratorStrategy(ImmutableArray Apply(GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, GeneratorData item) { var methods = _extensionMethodGeneratorStrategies.Aggregate( new List(), (m, strategy) => { try { - m.AddRange(strategy.Apply(item)); + m.AddRange(strategy.Apply(context, item)); } catch (Exception e) { diff --git a/src/JsonRpc.Generators/Strategies/HandlerGeneratorStrategy.cs b/src/JsonRpc.Generators/Strategies/HandlerGeneratorStrategy.cs index 65881c524..08a0b1368 100644 --- a/src/JsonRpc.Generators/Strategies/HandlerGeneratorStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/HandlerGeneratorStrategy.cs @@ -11,7 +11,7 @@ namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies { internal class HandlerGeneratorStrategy : ICompilationUnitGeneratorStrategy { - public IEnumerable Apply(GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, GeneratorData item) { if (item.JsonRpcAttributes.GenerateHandler is not { }) yield break; var members = new List(); diff --git a/src/JsonRpc.Generators/Strategies/HandlerRegistryActionContextRunnerStrategy.cs b/src/JsonRpc.Generators/Strategies/HandlerRegistryActionContextRunnerStrategy.cs index ffda7747c..ab5ddf6df 100644 --- a/src/JsonRpc.Generators/Strategies/HandlerRegistryActionContextRunnerStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/HandlerRegistryActionContextRunnerStrategy.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using OmniSharp.Extensions.JsonRpc.Generators.Contexts; @@ -14,17 +15,20 @@ public HandlerRegistryActionContextRunnerStrategy(ImmutableArray Apply(GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, GeneratorData item) { + foreach (var diagnostic in item.JsonRpcAttributes.HandlerRegistryDiagnostics) + { + context.ReportDiagnostic(diagnostic); + } return item.JsonRpcAttributes.HandlerRegistries .Select( registry => new ExtensionMethodContext( - item.JsonRpcAttributes.GenerateHandlerMethods!.Data, item.TypeDeclaration, item.TypeSymbol, registry, item.JsonRpcAttributes.HandlerRegistries, - item.Context + item.JsonRpcAttributes.GenerateHandlerMethods!.Data, item.TypeDeclaration, item.TypeSymbol, registry, item.JsonRpcAttributes.HandlerRegistries ) { IsRegistry = true } ) .SelectMany(_ => _strategies, (actionContext, strategy) => new { actionContext, strategy }) - .SelectMany(@t => @t.strategy.Apply(@t.actionContext, item)); + .SelectMany(@t => @t.strategy.Apply(context, @t.actionContext, item)); } } } diff --git a/src/JsonRpc.Generators/Strategies/OnNotificationMethodGeneratorWithRegistrationOptionsStrategy.cs b/src/JsonRpc.Generators/Strategies/OnNotificationMethodGeneratorWithRegistrationOptionsStrategy.cs index 660226913..b4f0324bc 100644 --- a/src/JsonRpc.Generators/Strategies/OnNotificationMethodGeneratorWithRegistrationOptionsStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/OnNotificationMethodGeneratorWithRegistrationOptionsStrategy.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Collections.Generic; using System.Collections.Immutable; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using OmniSharp.Extensions.JsonRpc.Generators.Contexts; @@ -13,7 +14,7 @@ namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies { internal class OnNotificationMethodGeneratorWithRegistrationOptionsStrategy : IExtensionMethodContextGeneratorStrategy { - public IEnumerable Apply(ExtensionMethodContext extensionMethodContext, GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, ExtensionMethodContext extensionMethodContext, GeneratorData item) { if (item is not { RegistrationOptions: { } registrationOptions }) yield break; if (item is not NotificationItem notification) yield break; diff --git a/src/JsonRpc.Generators/Strategies/OnNotificationMethodGeneratorWithoutRegistrationOptionsStrategy.cs b/src/JsonRpc.Generators/Strategies/OnNotificationMethodGeneratorWithoutRegistrationOptionsStrategy.cs index 984cf5f4b..d0e158e53 100644 --- a/src/JsonRpc.Generators/Strategies/OnNotificationMethodGeneratorWithoutRegistrationOptionsStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/OnNotificationMethodGeneratorWithoutRegistrationOptionsStrategy.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using OmniSharp.Extensions.JsonRpc.Generators.Contexts; @@ -10,7 +11,7 @@ namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies { internal class OnNotificationMethodGeneratorWithoutRegistrationOptionsStrategy : IExtensionMethodContextGeneratorStrategy { - public IEnumerable Apply(ExtensionMethodContext extensionMethodContext, GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, ExtensionMethodContext extensionMethodContext, GeneratorData item) { if (item is { RegistrationOptions: { } }) yield break; if (item is not NotificationItem notification) yield break; diff --git a/src/JsonRpc.Generators/Strategies/OnRequestMethodGeneratorWithRegistrationOptionsStrategy.cs b/src/JsonRpc.Generators/Strategies/OnRequestMethodGeneratorWithRegistrationOptionsStrategy.cs index 7db3b435e..7ad741a03 100644 --- a/src/JsonRpc.Generators/Strategies/OnRequestMethodGeneratorWithRegistrationOptionsStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/OnRequestMethodGeneratorWithRegistrationOptionsStrategy.cs @@ -21,7 +21,7 @@ public OnRequestMethodGeneratorWithRegistrationOptionsStrategy(bool doResolve) _doResolve = doResolve; } - public IEnumerable Apply(ExtensionMethodContext extensionMethodContext, GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, ExtensionMethodContext extensionMethodContext, GeneratorData item) { if (item is not { RegistrationOptions: { } registrationOptions }) yield break; if (item is not RequestItem request) yield break; diff --git a/src/JsonRpc.Generators/Strategies/OnRequestMethodGeneratorWithoutRegistrationOptionsStrategy.cs b/src/JsonRpc.Generators/Strategies/OnRequestMethodGeneratorWithoutRegistrationOptionsStrategy.cs index 2eecbffe3..0bdcdccaa 100644 --- a/src/JsonRpc.Generators/Strategies/OnRequestMethodGeneratorWithoutRegistrationOptionsStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/OnRequestMethodGeneratorWithoutRegistrationOptionsStrategy.cs @@ -19,7 +19,7 @@ public OnRequestMethodGeneratorWithoutRegistrationOptionsStrategy(bool doResolve _doResolve = doResolve; } - public IEnumerable Apply(ExtensionMethodContext extensionMethodContext, GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, ExtensionMethodContext extensionMethodContext, GeneratorData item) { if (item is { RegistrationOptions: { } }) yield break; if (item is not RequestItem request) yield break; diff --git a/src/JsonRpc.Generators/Strategies/OnRequestTypedResolveMethodGeneratorWithRegistrationOptionsStrategy.cs b/src/JsonRpc.Generators/Strategies/OnRequestTypedResolveMethodGeneratorWithRegistrationOptionsStrategy.cs index b13c22046..303f9908d 100644 --- a/src/JsonRpc.Generators/Strategies/OnRequestTypedResolveMethodGeneratorWithRegistrationOptionsStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/OnRequestTypedResolveMethodGeneratorWithRegistrationOptionsStrategy.cs @@ -14,7 +14,7 @@ namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies { internal class OnRequestTypedResolveMethodGeneratorWithRegistrationOptionsStrategy : IExtensionMethodContextGeneratorStrategy { - public IEnumerable Apply(ExtensionMethodContext extensionMethodContext, GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, ExtensionMethodContext extensionMethodContext, GeneratorData item) { if (item is not { RegistrationOptions: { } registrationOptions }) yield break; if (item is not RequestItem request) yield break; diff --git a/src/JsonRpc.Generators/Strategies/OnRequestTypedResolveMethodGeneratorWithoutRegistrationOptionsStrategy.cs b/src/JsonRpc.Generators/Strategies/OnRequestTypedResolveMethodGeneratorWithoutRegistrationOptionsStrategy.cs index 027144aa6..a7f88defc 100644 --- a/src/JsonRpc.Generators/Strategies/OnRequestTypedResolveMethodGeneratorWithoutRegistrationOptionsStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/OnRequestTypedResolveMethodGeneratorWithoutRegistrationOptionsStrategy.cs @@ -13,7 +13,7 @@ namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies internal class OnRequestTypedResolveMethodGeneratorWithoutRegistrationOptionsStrategy : IExtensionMethodContextGeneratorStrategy { - public IEnumerable Apply(ExtensionMethodContext extensionMethodContext, GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, ExtensionMethodContext extensionMethodContext, GeneratorData item) { if (item is { RegistrationOptions: { } }) yield break; if (item is not RequestItem request) yield break; diff --git a/src/JsonRpc.Generators/Strategies/RequestProxyActionContextRunnerStrategy.cs b/src/JsonRpc.Generators/Strategies/RequestProxyActionContextRunnerStrategy.cs index 17ee67b1f..791c51ddc 100644 --- a/src/JsonRpc.Generators/Strategies/RequestProxyActionContextRunnerStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/RequestProxyActionContextRunnerStrategy.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using OmniSharp.Extensions.JsonRpc.Generators.Contexts; @@ -14,17 +15,20 @@ public RequestProxyActionContextRunnerStrategy(ImmutableArray Apply(GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, GeneratorData item) { + foreach (var diagnostic in item.JsonRpcAttributes.RequestProxyDiagnostics) + { + context.ReportDiagnostic(diagnostic); + } return item.JsonRpcAttributes.RequestProxies .Select( registry => new ExtensionMethodContext( - item.JsonRpcAttributes.GenerateRequestMethods!.Data, item.TypeDeclaration, item.TypeSymbol, registry, item.JsonRpcAttributes.RequestProxies, - item.Context + item.JsonRpcAttributes.GenerateRequestMethods!.Data, item.TypeDeclaration, item.TypeSymbol, registry, item.JsonRpcAttributes.RequestProxies ) { IsProxy = true } ) .SelectMany(_ => _strategies, (actionContext, strategy) => new { actionContext, strategy }) - .SelectMany(t => t.strategy.Apply(t.actionContext, item)); + .SelectMany(t => t.strategy.Apply(context, t.actionContext, item)); } } } diff --git a/src/JsonRpc.Generators/Strategies/SendMethodNotificationStrategy.cs b/src/JsonRpc.Generators/Strategies/SendMethodNotificationStrategy.cs index bad6be5c1..265473f86 100644 --- a/src/JsonRpc.Generators/Strategies/SendMethodNotificationStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/SendMethodNotificationStrategy.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using OmniSharp.Extensions.JsonRpc.Generators.Contexts; @@ -8,7 +9,7 @@ namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies { internal class SendMethodNotificationStrategy : IExtensionMethodContextGeneratorStrategy { - public IEnumerable Apply(ExtensionMethodContext extensionMethodContext, GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, ExtensionMethodContext extensionMethodContext, GeneratorData item) { if (item is not NotificationItem notification) yield break; if (extensionMethodContext is not { IsProxy: true }) yield break; diff --git a/src/JsonRpc.Generators/Strategies/SendMethodRequestStrategy.cs b/src/JsonRpc.Generators/Strategies/SendMethodRequestStrategy.cs index fdcf99139..7bbc19ce3 100644 --- a/src/JsonRpc.Generators/Strategies/SendMethodRequestStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/SendMethodRequestStrategy.cs @@ -9,7 +9,7 @@ namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies { internal class SendMethodRequestStrategy : IExtensionMethodContextGeneratorStrategy { - public IEnumerable Apply(ExtensionMethodContext extensionMethodContext, GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, ExtensionMethodContext extensionMethodContext, GeneratorData item) { if (item is not RequestItem request) yield break; if (extensionMethodContext is not { IsProxy: true }) yield break; diff --git a/src/JsonRpc.Generators/Strategies/TypedDelegatingHandlerStrategy.cs b/src/JsonRpc.Generators/Strategies/TypedDelegatingHandlerStrategy.cs index f1fbaef01..21d7b9905 100644 --- a/src/JsonRpc.Generators/Strategies/TypedDelegatingHandlerStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/TypedDelegatingHandlerStrategy.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -8,7 +9,7 @@ namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies { internal class TypedDelegatingHandlerStrategy : IExtensionMethodGeneratorStrategy { - public IEnumerable Apply(GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, GeneratorData item) { if (item is not RequestItem requestItem) yield break; if (requestItem is not { LspAttributes: { Resolver: { } } }) yield break; diff --git a/src/JsonRpc.Generators/Strategies/WarnIfResponseRouterIsNotProvidedStrategy.cs b/src/JsonRpc.Generators/Strategies/WarnIfResponseRouterIsNotProvidedStrategy.cs index 82c16622d..6432f37d7 100644 --- a/src/JsonRpc.Generators/Strategies/WarnIfResponseRouterIsNotProvidedStrategy.cs +++ b/src/JsonRpc.Generators/Strategies/WarnIfResponseRouterIsNotProvidedStrategy.cs @@ -7,20 +7,24 @@ namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies { internal class WarnIfResponseRouterIsNotProvidedStrategy : IExtensionMethodContextGeneratorStrategy { - public IEnumerable Apply(ExtensionMethodContext extensionMethodContext, GeneratorData item) + public IEnumerable Apply(SourceProductionContext context, ExtensionMethodContext extensionMethodContext, GeneratorData item) { if (extensionMethodContext is not { IsProxy: true }) yield break; 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")) { - item.ReportDiagnostic(static type => Diagnostic.Create(GeneratorDiagnostics.NoResponseRouterProvided, type.Identifier.GetLocation(), type.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 dd83fafdc..299cd4f25 100644 --- a/src/JsonRpc.Generators/StronglyTypedGenerator.cs +++ b/src/JsonRpc.Generators/StronglyTypedGenerator.cs @@ -5,252 +5,303 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static OmniSharp.Extensions.JsonRpc.Generators.Helpers; namespace OmniSharp.Extensions.JsonRpc.Generators { [Generator] - public class StronglyTypedGenerator : CachedSourceGenerator + public class StronglyTypedGenerator : IIncrementalGenerator { - private static string[] RequiredUsings = new[] { + private static readonly string[] RequiredUsings = + { "System.Collections.Generic", "System.Collections.ObjectModel", "System.Collections.Immutable", "System.Linq", }; - protected override void Execute( - GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource addCacheSource, - ReportCacheDiagnostic cacheDiagnostic - ) - { - var generateTypedDataAttributeSymbol = context.Compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Generation.GenerateTypedDataAttribute"); - var generateContainerAttributeSymbol = context.Compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Generation.GenerateContainerAttribute"); + private record AttributeData(INamedTypeSymbol GenerateTypedDataAttributeSymbol, INamedTypeSymbol GenerateContainerAttributeSymbol); - foreach (var classToContain in syntaxReceiver.CreateContainers) - { - var semanticModel = context.Compilation.GetSemanticModel(classToContain.SyntaxTree); - var typeSymbol = semanticModel.GetDeclaredSymbol(classToContain); - var attribute = typeSymbol?.GetAttributes().FirstOrDefault(z => SymbolEqualityComparer.Default.Equals(z.AttributeClass, generateContainerAttributeSymbol)); - if (typeSymbol == null || attribute is null) continue; - - var containerName = attribute is { ConstructorArguments: { Length: > 0 } arguments } ? arguments[0].Value as string : null; - - var container = CreateContainerClass(classToContain, containerName) - .AddAttributeLists( - AttributeList( - SeparatedList( - new[] { - Attribute(ParseName("System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute")), - Attribute(ParseName("System.Runtime.CompilerServices.CompilerGeneratedAttribute")) - } - ) - ) - ); + public void Initialize(IncrementalGeneratorInitializationContext context) + { + var attributes = context.CompilationProvider + .Select( + (compilation, _) => new AttributeData( + compilation.GetTypeByMetadataName( + "OmniSharp.Extensions.LanguageServer.Protocol.Generation.GenerateTypedDataAttribute" + )!, + compilation.GetTypeByMetadataName( + "OmniSharp.Extensions.LanguageServer.Protocol.Generation.GenerateContainerAttribute" + )! + ) + ); - var cu = CompilationUnit() - .WithUsings(classToContain.SyntaxTree.GetCompilationUnitRoot().Usings) - .AddMembers( - NamespaceDeclaration(ParseName(typeSymbol.ContainingNamespace.ToDisplayString())) - .AddMembers(container) - .WithLeadingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.EnableKeyword), true)))) - .WithTrailingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.RestoreKeyword), true)))) - ) - .WithLeadingTrivia(Comment(Preamble.GeneratedByATool)) - .WithTrailingTrivia(CarriageReturnLineFeed); - - foreach (var ns in RequiredUsings) + var createContainersSyntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( + (syntaxNode, _) => syntaxNode switch { - if (cu.Usings.All(z => z.Name.ToFullString() != ns)) - { - cu = cu.AddUsings(UsingDirective(ParseName(ns))); - } - } + StructDeclarationSyntax structDeclarationSyntax when structDeclarationSyntax.AttributeLists.ContainsAttribute("GenerateContainer") => true, + TypeDeclarationSyntax typeDeclarationSyntax and (ClassDeclarationSyntax or RecordDeclarationSyntax) when typeDeclarationSyntax + .AttributeLists.ContainsAttribute("GenerateContainer") => true, + _ => false + }, (syntaxContext, _) => syntaxContext + ); - addCacheSource( - $"{containerName ?? classToContain.Identifier.Text + "Container"}.cs", - classToContain, - cu.NormalizeWhitespace().GetText(Encoding.UTF8) - ); - } + var canBeResolvedSyntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( + (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"), + (syntaxContext, _) => syntaxContext + ); - foreach (var canBeResolved in syntaxReceiver.CanBeResolved) - { - var dataInterfaceName = IdentifierName("ICanBeResolved"); - CreateTypedClass( - context, canBeResolved, dataInterfaceName, generateTypedDataAttributeSymbol, generateContainerAttributeSymbol, true, addCacheSource, cacheDiagnostic - ); - } + var canHaveDataSyntaxProvider = context.SyntaxProvider.CreateSyntaxProvider( + (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"), (syntaxContext, _) => syntaxContext + ); - foreach (var canBeResolved in syntaxReceiver.CanHaveData) - { - var dataInterfaceName = IdentifierName("ICanHaveData"); - CreateTypedClass( - context, canBeResolved, dataInterfaceName, generateTypedDataAttributeSymbol, generateContainerAttributeSymbol, false, addCacheSource, cacheDiagnostic + context.RegisterSourceOutput(createContainersSyntaxProvider.Combine(attributes), GenerateContainerClass); + context.RegisterSourceOutput(canBeResolvedSyntaxProvider.Combine(attributes), GenerateCanBeResolvedClass); + context.RegisterSourceOutput(canHaveDataSyntaxProvider.Combine(attributes), GenerateCanHaveDataClass); + } + + private void GenerateContainerClass(SourceProductionContext context, (GeneratorSyntaxContext syntaxContext, AttributeData attributeData) valueTuple) + { + var (syntaxContext, attributeData) = valueTuple; + var classToContain = (TypeDeclarationSyntax)syntaxContext.Node; + var typeSymbol = syntaxContext.SemanticModel.GetDeclaredSymbol(classToContain); + var attribute = typeSymbol?.GetAttributes() + .FirstOrDefault( + z => SymbolEqualityComparer.Default.Equals(z.AttributeClass, attributeData.GenerateContainerAttributeSymbol) + ); + if (typeSymbol == null || attribute is null) return; + + var containerName = attribute is { ConstructorArguments: { Length: > 0 } arguments } ? arguments[0].Value as string : null; + + var container = CreateContainerClass(classToContain, containerName) + .AddAttributeLists( + AttributeList( + SeparatedList( + new[] + { + Attribute(ParseName("System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute")), + Attribute(ParseName("System.Runtime.CompilerServices.CompilerGeneratedAttribute")) + } + ) + ) ); - } - static void CreateTypedClass( - GeneratorExecutionContext context, - TypeDeclarationSyntax candidate, - IdentifierNameSyntax dataInterfaceName, - INamedTypeSymbol? generateTypedDataAttributeSymbol, - INamedTypeSymbol? generateContainerAttributeSymbol, - bool includeHandlerIdentity, - AddCacheSource cacheItem, - ReportCacheDiagnostic cacheDiagnostic - ) - { - var semanticModel = context.Compilation.GetSemanticModel(candidate.SyntaxTree); - var typeSymbol = semanticModel.GetDeclaredSymbol(candidate); - var attribute = typeSymbol?.GetAttributes().FirstOrDefault(z => SymbolEqualityComparer.Default.Equals(z.AttributeClass, generateTypedDataAttributeSymbol)); - if (typeSymbol == null || attribute is null) return; - var container = typeSymbol.GetAttributes().FirstOrDefault(z => SymbolEqualityComparer.Default.Equals(z.AttributeClass, generateContainerAttributeSymbol)); + var cu = CompilationUnit() + .WithUsings(classToContain.SyntaxTree.GetCompilationUnitRoot().Usings) + .AddMembers( + NamespaceDeclaration(ParseName(typeSymbol.ContainingNamespace.ToDisplayString())) + .AddMembers(container) + .WithLeadingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.EnableKeyword), true)))) + .WithTrailingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.RestoreKeyword), true)))) + ); - if (!candidate.Modifiers.Any(SyntaxKind.PartialKeyword)) + foreach (var ns in RequiredUsings) + { + if (cu.Usings.All(z => z.Name.ToFullString() != ns)) { - cacheDiagnostic(candidate, static c => Diagnostic.Create(GeneratorDiagnostics.MustBePartial, c.Identifier.GetLocation(), c.Identifier.Text)); - return; + cu = cu.AddUsings(UsingDirective(ParseName(ns))); } + } - var property = candidate.Members.OfType().Single(z => z.Identifier.Text == "Data"); - var partialClass = candidate - .WithAttributeLists(List()) - .WithBaseList(null) - .WithMembers(List()) - .AddMembers( - GetWithDataMethod(candidate, HandlerIdentityConstraintClause(includeHandlerIdentity, IdentifierName("TData"))), - GetFromMethod(candidate, includeHandlerIdentity) - ); - - var compilationMembers = new List(); - - - var convertFromOperator = GetConvertFromOperator(candidate); - var convertToOperator = GetConvertToOperator(candidate); - // remove the data property - var typedClass = candidate - .WithHandlerIdentityConstraint(includeHandlerIdentity) - .WithMembers(candidate.Members.Replace(property, GetPropertyImpl(property).WithType(IdentifierName("T")))) - .AddMembers( - GetWithDataMethod(candidate, HandlerIdentityConstraintClause(includeHandlerIdentity, IdentifierName("TData"))), - GetExplicitProperty(property, dataInterfaceName), - GetJDataProperty(), - convertFromOperator, - convertToOperator, - GetGenericFromMethod(candidate) - ) - .WithAttributeLists( - List( - candidate.AttributeLists - .Where(z => !z.ContainsAttribute("Method") && !z.ContainsAttribute("GenerateTypedData")) - ) + context.AddSource( + $"{containerName ?? classToContain.Identifier.Text + "Container"}.cs", + cu.NormalizeWhitespace().GetText(Encoding.UTF8) + ); + } + + private void GenerateCanBeResolvedClass(SourceProductionContext context, (GeneratorSyntaxContext syntaxContext, AttributeData attributeData) valueTuple) + { + 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 + ); + } + + private void GenerateCanHaveDataClass(SourceProductionContext context, (GeneratorSyntaxContext syntaxContext, AttributeData attributeData) valueTuple) + { + 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 + ); + } + + private static void CreateTypedClass( + SourceProductionContext context, + TypeDeclarationSyntax candidate, + INamedTypeSymbol typeSymbol, + IdentifierNameSyntax dataInterfaceName, + INamedTypeSymbol? generateTypedDataAttributeSymbol, + INamedTypeSymbol? generateContainerAttributeSymbol, + bool includeHandlerIdentity + ) + { + var attribute = typeSymbol?.GetAttributes() + .FirstOrDefault(z => SymbolEqualityComparer.Default.Equals(z.AttributeClass, generateTypedDataAttributeSymbol)); + if (typeSymbol == null || attribute is null) return; + var container = typeSymbol.GetAttributes() + .FirstOrDefault(z => SymbolEqualityComparer.Default.Equals(z.AttributeClass, generateContainerAttributeSymbol)); + + if (!candidate.Modifiers.Any(SyntaxKind.PartialKeyword)) + { + context.ReportDiagnostic(Diagnostic.Create(GeneratorDiagnostics.MustBePartial, candidate.Identifier.GetLocation(), candidate.Identifier.Text)); + return; + } + + var property = candidate.Members.OfType().Single(z => z.Identifier.Text == "Data"); + var partialClass = candidate + .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) + ); + + var compilationMembers = new List(); + + + var convertFromOperator = GetConvertFromOperator(candidate); + var convertToOperator = GetConvertToOperator(candidate); + // remove the data property + var typedClass = candidate + .WithHandlerIdentityConstraint(includeHandlerIdentity) + .WithMembers(candidate.Members.Replace(property, GetPropertyImpl(property).WithType(IdentifierName("T")))) + .AddMembers( + GetWithDataMethod(candidate, HandlerIdentityConstraintClause(includeHandlerIdentity, IdentifierName("TData"))), + GetExplicitProperty(property, dataInterfaceName), + GetJDataProperty(), + convertFromOperator, + convertToOperator, + GetGenericFromMethod(candidate) + ) + .WithAttributeLists( + List( + candidate.AttributeLists + .Where(z => !z.ContainsAttribute("Method") && !z.ContainsAttribute("GenerateTypedData")) ) - .WithBaseList(BaseList(SingletonSeparatedList(SimpleBaseType(dataInterfaceName)))) - .AddAttributeLists( - AttributeList( - SeparatedList( - new[] { - Attribute(ParseName("System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute")), - Attribute(ParseName("System.Runtime.CompilerServices.CompilerGeneratedAttribute")) - } - ) + ) + .WithBaseList(BaseList(SingletonSeparatedList(SimpleBaseType(dataInterfaceName)))) + .AddAttributeLists( + AttributeList( + SeparatedList( + new[] + { + Attribute(ParseName("System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute")), + Attribute(ParseName("System.Runtime.CompilerServices.CompilerGeneratedAttribute")) + } ) ) + ) // .WithLeadingTrivia(candidate.GetLeadingTrivia().Where(z => !z.ToString().Contains("#nullable"))) // .WithTrailingTrivia(candidate.GetTrailingTrivia().Where(z => !z.ToString().Contains("#nullable"))) - ; + ; - if (container is { }) - { - var containerName = container is { ConstructorArguments: { Length: > 0 } arguments } ? arguments[0].Value as string : null; - var typedContainer = CreateContainerClass(typedClass, containerName) - .WithHandlerIdentityConstraint(includeHandlerIdentity); - - var typedArgumentList = TypeArgumentList(SingletonSeparatedList(IdentifierName("T"))); - typedContainer = typedContainer - .AddMembers( - ConversionOperatorDeclaration(Token(SyntaxKind.ImplicitKeyword), IdentifierName(typedContainer.Identifier)) - .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword))) - .WithParameterList( - ParameterList( - SingletonSeparatedList( - Parameter(Identifier("container")) - .WithType(GenericName(typedContainer.Identifier).WithTypeArgumentList(typedArgumentList)) - ) + if (container is { }) + { + var containerName = container is { ConstructorArguments: { Length: > 0 } arguments } ? arguments[0].Value as string : null; + var typedContainer = CreateContainerClass(typedClass, containerName) + .WithHandlerIdentityConstraint(includeHandlerIdentity); + + var typedArgumentList = TypeArgumentList(SingletonSeparatedList(IdentifierName("T"))); + typedContainer = typedContainer + .AddMembers( + ConversionOperatorDeclaration(Token(SyntaxKind.ImplicitKeyword), IdentifierName(typedContainer.Identifier)) + .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword))) + .WithParameterList( + ParameterList( + SingletonSeparatedList( + Parameter(Identifier("container")) + .WithType(GenericName(typedContainer.Identifier).WithTypeArgumentList(typedArgumentList)) ) ) - .WithExpressionBody( - ArrowExpressionClause( - ObjectCreationExpression(IdentifierName(typedContainer.Identifier)) - .WithArgumentList( - ArgumentList( - SingletonSeparatedList( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("container"), - IdentifierName("Select") - ) + ) + .WithExpressionBody( + ArrowExpressionClause( + ObjectCreationExpression(IdentifierName(typedContainer.Identifier)) + .WithArgumentList( + ArgumentList( + SingletonSeparatedList( + Argument( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("container"), + IdentifierName("Select") ) - .WithArgumentList( - ArgumentList( - SingletonSeparatedList( - Argument( - SimpleLambdaExpression(Parameter(Identifier("value"))) - .WithExpressionBody( - CastExpression( - IdentifierName(candidate.Identifier), - IdentifierName("value") - ) + ) + .WithArgumentList( + ArgumentList( + SingletonSeparatedList( + Argument( + SimpleLambdaExpression(Parameter(Identifier("value"))) + .WithExpressionBody( + CastExpression( + IdentifierName(candidate.Identifier), + IdentifierName("value") ) - ) + ) ) ) ) - ) + ) ) ) ) - ) - ) - .MakeMethodNullable(IdentifierName("container")) - .WithSemicolonToken( - Token(SyntaxKind.SemicolonToken) + ) ) - ); + ) + .MakeMethodNullable(IdentifierName("container")) + .WithSemicolonToken( + Token(SyntaxKind.SemicolonToken) + ) + ); - compilationMembers.Add(typedContainer); - } + compilationMembers.Add(typedContainer); + } - var cu = CompilationUnit() - .WithUsings(candidate.SyntaxTree.GetCompilationUnitRoot().Usings) - .AddMembers( - NamespaceDeclaration(ParseName(typeSymbol.ContainingNamespace.ToDisplayString())) - .AddMembers(partialClass, typedClass) - .AddMembers(compilationMembers.ToArray()) - .WithLeadingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.EnableKeyword), true)))) - .WithTrailingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.RestoreKeyword), true)))) - ) - .WithLeadingTrivia(Comment(Preamble.GeneratedByATool)) - .WithTrailingTrivia(CarriageReturnLineFeed); - foreach (var ns in RequiredUsings) + var cu = CompilationUnit() + .WithUsings(candidate.SyntaxTree.GetCompilationUnitRoot().Usings) + .AddMembers( + NamespaceDeclaration(ParseName(typeSymbol.ContainingNamespace.ToDisplayString())) + .AddMembers(partialClass, typedClass) + .AddMembers(compilationMembers.ToArray()) + .WithLeadingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.EnableKeyword), true)))) + .WithTrailingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.RestoreKeyword), true)))) + ); + foreach (var ns in RequiredUsings) + { + if (cu.Usings.All(z => z.Name.ToFullString() != ns)) { - if (cu.Usings.All(z => z.Name.ToFullString() != ns)) - { - cu = cu.AddUsings(UsingDirective(ParseName(ns))); - } + cu = cu.AddUsings(UsingDirective(ParseName(ns))); } - - cacheItem( - $"{Path.GetFileNameWithoutExtension(candidate.SyntaxTree.FilePath)}_{candidate.Identifier.Text}Typed.cs", - candidate, - cu.NormalizeWhitespace().GetText(Encoding.UTF8) - ); } + + context.AddSource( + $"{Path.GetFileNameWithoutExtension(candidate.SyntaxTree.FilePath)}_{candidate.Identifier.Text}Typed.cs", + cu.NormalizeWhitespace().GetText(Encoding.UTF8) + ); } private static MethodDeclarationSyntax GetWithDataMethod(TypeDeclarationSyntax syntax, SyntaxList constraintSyntax) @@ -277,7 +328,8 @@ private static MethodDeclarationSyntax GetWithDataMethod(TypeDeclarationSyntax s SyntaxKind.ObjectInitializerExpression, SeparatedList( GetMapping(syntax, null).Concat( - new ExpressionSyntax[] { + new ExpressionSyntax[] + { AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName("Data"), @@ -337,7 +389,13 @@ private static MethodDeclarationSyntax GetFromMethod(TypeDeclarationSyntax synta private static IEnumerable GetMapping(TypeDeclarationSyntax syntax, IdentifierNameSyntax? paramName) { return syntax.Members.OfType() - .Where(z => z.AccessorList?.Accessors.Any(a => a.Keyword.Kind() == SyntaxKind.SetKeyword || a.Keyword.Kind() == SyntaxKind.InitKeyword) == true) + .Where( + z => z.AccessorList?.Accessors.Any( + a => + a.Keyword.IsKind(SyntaxKind.SetKeyword) + || a.Keyword.IsKind(SyntaxKind.InitKeyword) + ) == true + ) .Where(z => z.Identifier.Text != "Data") .Select( property => AssignmentExpression( @@ -383,7 +441,8 @@ private static ConversionOperatorDeclarationSyntax GetConvertToOperator(TypeDecl SeparatedList( GetMapping(syntax, paramName) .Concat( - new[] { + new[] + { AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName("Data"), @@ -414,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)) @@ -438,7 +497,8 @@ private static ConversionOperatorDeclarationSyntax GetConvertFromOperator(TypeDe SeparatedList( GetMapping(syntax, paramName) .Concat( - new[] { + new[] + { AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName("JData"), @@ -474,18 +534,27 @@ private static PropertyDeclarationSyntax GetJDataProperty() .WithAccessorList( AccessorList( List( - new[] { + new[] + { AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithExpressionBody( ArrowExpressionClause( - InvocationExpression(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, ThisExpression(), IdentifierName("GetRawData"))) + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, ThisExpression(), IdentifierName("GetRawData") + ) + ) ) ) .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)), AccessorDeclaration(SyntaxKind.InitAccessorDeclaration) .WithExpressionBody( ArrowExpressionClause( - InvocationExpression(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, ThisExpression(), IdentifierName("SetRawData"))) + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, ThisExpression(), IdentifierName("SetRawData") + ) + ) .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("value"))))) ) ) @@ -496,12 +565,13 @@ private static PropertyDeclarationSyntax GetJDataProperty() ); } - static PropertyDeclarationSyntax GetPropertyImpl(PropertyDeclarationSyntax syntax) + private static PropertyDeclarationSyntax GetPropertyImpl(PropertyDeclarationSyntax syntax) { return syntax.WithAccessorList( AccessorList( List( - new[] { + new[] + { AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithExpressionBody( ArrowExpressionClause( @@ -573,7 +643,8 @@ private static TypeDeclarationSyntax CreateContainerClass(TypeDeclarationSyntax ) .WithMembers( List( - new MemberDeclarationSyntax[] { + new MemberDeclarationSyntax[] + { ConstructorDeclaration(classIdentifier) .WithModifiers( TokenList( @@ -611,19 +682,27 @@ private static TypeDeclarationSyntax CreateContainerClass(TypeDeclarationSyntax .WithParameterList( ParameterList( SingletonSeparatedList( - Parameter(Identifier("items")).WithType(GenericName(Identifier("IEnumerable")).WithTypeArgumentList(typeArgumentList)) + Parameter(Identifier("items")).WithType( + GenericName(Identifier("IEnumerable")).WithTypeArgumentList(typeArgumentList) + ) ) ) ) .WithInitializer( - ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, ArgumentList(SingletonSeparatedList(Argument(IdentifierName("items"))))) + ConstructorInitializer( + SyntaxKind.BaseConstructorInitializer, ArgumentList(SingletonSeparatedList(Argument(IdentifierName("items")))) + ) ) .WithBody(Block()), ConstructorDeclaration(classIdentifier) .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))) - .WithParameterList(ParameterList(SingletonSeparatedList(ArrayParameter(typeName).WithModifiers(TokenList(Token(SyntaxKind.ParamsKeyword)))))) + .WithParameterList( + ParameterList(SingletonSeparatedList(ArrayParameter(typeName).WithModifiers(TokenList(Token(SyntaxKind.ParamsKeyword))))) + ) .WithInitializer( - ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, ArgumentList(SingletonSeparatedList(Argument(IdentifierName("items"))))) + ConstructorInitializer( + SyntaxKind.BaseConstructorInitializer, ArgumentList(SingletonSeparatedList(Argument(IdentifierName("items")))) + ) ) .WithBody(Block()), AddConversionBody( @@ -649,7 +728,9 @@ private static TypeDeclarationSyntax CreateContainerClass(TypeDeclarationSyntax Identifier("List"), MethodDeclaration(className, Identifier("From")) ) - .WithParameterList(ParameterList(SingletonSeparatedList(ArrayParameter(typeName).WithModifiers(TokenList(Token(SyntaxKind.ParamsKeyword)))))), + .WithParameterList( + ParameterList(SingletonSeparatedList(ArrayParameter(typeName).WithModifiers(TokenList(Token(SyntaxKind.ParamsKeyword))))) + ), AddConversionBody( typeName, Identifier("Collection"), @@ -774,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))) @@ -817,74 +898,5 @@ static BaseMethodDeclarationSyntax AddConversionBody(TypeSyntax typeName, Syntax ); } } - - public StronglyTypedGenerator() : base(() => new SyntaxReceiver(Cache)) - { - } - - public static CacheContainer Cache = new(); - - public class SyntaxReceiver : SyntaxReceiverCache - { - public List CanBeResolved { get; } = new(); - public List CanHaveData { get; } = new(); - public List CreateContainers { get; } = new(); - - public override string? GetKey(TypeDeclarationSyntax syntax) - { - var hasher = new CacheKeyHasher(); - hasher.Append(syntax.SyntaxTree.FilePath); - hasher.Append(syntax.Keyword.Text); - hasher.Append(syntax.Identifier.Text); - hasher.Append(syntax.TypeParameterList); - hasher.Append(syntax.AttributeLists); - hasher.Append(syntax.BaseList); - return hasher; - } - - /// - /// Called for every syntax node in the compilation, we can inspect the nodes and save any information useful for generation - /// - public override void OnVisitNode(TypeDeclarationSyntax syntaxNode) - { - // any field with at least one attribute is a candidate for property generation - - if (syntaxNode is StructDeclarationSyntax structDeclarationSyntax) - { - if (structDeclarationSyntax.AttributeLists.ContainsAttribute("GenerateContainer")) - { - CreateContainers.Add(structDeclarationSyntax); - } - } - - if (syntaxNode is ClassDeclarationSyntax or RecordDeclarationSyntax) - { - if (syntaxNode.AttributeLists.ContainsAttribute("GenerateContainer")) - { - CreateContainers.Add(syntaxNode); - } - - if ( - syntaxNode.BaseList != null && - syntaxNode.SyntaxTree.HasCompilationUnitRoot && - syntaxNode.Members.OfType().Any(z => z.Identifier.Text == "Data") - ) - { - if (syntaxNode.BaseList.Types.Any(z => z.Type.GetSyntaxName() == "ICanBeResolved")) - { - CanBeResolved.Add(syntaxNode); - } - else if (syntaxNode.BaseList.Types.Any(z => z.Type.GetSyntaxName() == "ICanHaveData")) - { - CanHaveData.Add(syntaxNode); - } - } - } - } - - public SyntaxReceiver(CacheContainer cache) : base(cache) - { - } - } } } diff --git a/src/JsonRpc.Testing/JsonRpc.Testing.csproj b/src/JsonRpc.Testing/JsonRpc.Testing.csproj index 5c6ce8413..d02e92518 100644 --- a/src/JsonRpc.Testing/JsonRpc.Testing.csproj +++ b/src/JsonRpc.Testing/JsonRpc.Testing.csproj @@ -1,7 +1,7 @@  - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.JsonRpc.Testing OmniSharp.Extensions.JsonRpc.Testing @@ -13,10 +13,12 @@ - <_Parameter1>OmniSharp.Extensions.LanguageProtocol.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageProtocol.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f 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/DryIoc/DryIocAdapter.cs b/src/JsonRpc/DryIoc/DryIocAdapter.cs index 2b30999fd..ca0e269b9 100644 --- a/src/JsonRpc/DryIoc/DryIocAdapter.cs +++ b/src/JsonRpc/DryIoc/DryIocAdapter.cs @@ -1,184 +1,188 @@ -using System; -using System.Collections.Generic; +using System.Runtime.CompilerServices; using Microsoft.Extensions.DependencyInjection; using OmniSharp.Extensions.JsonRpc; -// ReSharper disable once CheckNamespace -namespace DryIoc -{ +namespace DryIoc; - /// Adapts DryIoc container to be used as MS.DI service provider, plus provides the helpers - /// to simplify work with adapted container. - internal static class DryIocAdapter +/// Adapts DryIoc container to be used as MS.DI service provider, plus provides the helpers +/// to simplify work with adapted container. +internal static class DryIocAdapter +{ + /// Adapts passed to Microsoft.DependencyInjection conventions, + /// registers DryIoc implementations of and , + /// and returns NEW container. + /// + /// Source container to adapt. + /// (optional) Specify service descriptors or use later. + /// (optional) Custom registration action, should return true to skip normal registration. + /// (optional) Use DryIoc capability. + /// + /// (Reuse.Scoped) + /// + /// // applies the MS.DI rules and registers the infrastructure helpers and service collection to the container + /// var adaptedContainer = container.WithDependencyInjectionAdapter(services); + /// + /// // the container implements IServiceProvider + /// IServiceProvider serviceProvider = adaptedContainer; + /// + ///]]> + /// + /// You still need to Dispose adapted container at the end / application shutdown. + public static IContainer WithDependencyInjectionAdapter( + this IContainer container, + IEnumerable descriptors = null, + Func registerDescriptor = null, + RegistrySharing registrySharing = RegistrySharing.Share + ) { - /// Creates the container and the `IServiceProvider` because its implemented by `IContainer` - - /// you get simply the best of both worlds. - public static IContainer Create( - IEnumerable services, - Func? registerService = null) - { - var container = new Container(Rules.MicrosoftDependencyInjectionRules); - - container.Use(r => new DryIocServiceScopeFactory(r)); - container.Populate(services, registerService); - - return container; - } + if (container.Rules != Rules.MicrosoftDependencyInjectionRules) + container = container.With( + container.Rules.WithMicrosoftDependencyInjectionRules(), + container.ScopeContext, registrySharing, container.SingletonScope + ); + + var capabilities = new DryIocServiceProviderCapabilities(container); + var singletons = container.SingletonScope; +#if NET6_0_OR_GREATER + singletons.Use(capabilities); +#endif + singletons.Use(capabilities); + singletons.UseFactory(r => new DryIocServiceScopeFactory(r)); + + if (descriptors != null) + container.Populate(descriptors, registerDescriptor); + + return container; + } - /// Adapts passed to Microsoft.DependencyInjection conventions, - /// registers DryIoc implementations of and , - /// and returns NEW container. - /// - /// Source container to adapt. - /// (optional) Specify service descriptors or use later. - /// (optional) Custom registration action, should return true to skip normal registration. - /// - /// (Reuse.Scoped) - /// - /// var adaptedContainer = container.WithDependencyInjectionAdapter(services); - /// IServiceProvider serviceProvider = adaptedContainer; // the container implements IServiceProvider now - /// - ///]]> - /// - /// You still need to Dispose adapted container at the end / application shutdown. - public static IContainer WithDependencyInjectionAdapter(this IContainer container, - IEnumerable? descriptors = null, - Func? registerDescriptor = null) - { - if (container.Rules != Rules.MicrosoftDependencyInjectionRules) - container = container.With(rules => rules.WithMicrosoftDependencyInjectionRules()); + /// Sugar to create the DryIoc container and adapter populated with services + public static IServiceProvider CreateServiceProvider(this IServiceCollection services) => + new Container(DryIoc.Rules.MicrosoftDependencyInjectionRules).WithDependencyInjectionAdapter(services); - container.Use(r => new DryIocServiceScopeFactory(r)); + /// Adds services registered in to container + public static IContainer WithCompositionRoot(this IContainer container, Type compositionRootType) + { + container.Register(compositionRootType); + container.Resolve(compositionRootType); + return container; + } - // Registers service collection - if (descriptors != null) - container.Populate(descriptors, registerDescriptor); + /// Adds services registered in to container + public static IContainer WithCompositionRoot(this IContainer container) => + container.WithCompositionRoot(typeof(TCompositionRoot)); + + /// It does not really build anything, it just gets the `IServiceProvider` from the container. + public static IServiceProvider BuildServiceProvider(this IContainer container) => + container.GetServiceProvider(); + + /// Just gets the `IServiceProvider` from the container. + public static IServiceProvider GetServiceProvider(this IResolver container) => + container; + + /// Facade to consolidate DryIoc registrations in + /// The class will be created by container on Startup + /// to enable registrations with injected or full . + /// Adapted container Service provider + /// + /// (Reuse.Singleton); + /// r.Register(Reuse.Transient); + /// r.Register(Reuse.InCurrentScope); + /// } + /// } + /// ]]> + /// + public static IServiceProvider ConfigureServiceProvider(this IContainer container) => + container.WithCompositionRoot().GetServiceProvider(); + + /// Registers service descriptors into container. May be called multiple times with different service collections. + /// The container. + /// The service descriptors. + /// (optional) Custom registration action, should return true to skip normal registration. + /// + /// { + /// if (service.ServiceType == typeof(SomeService)) { + /// r.Register(Made.Of(() => CreateCustomService()), Reuse.Singleton); + /// return true; + /// }; + /// return false; // fallback to normal registrations for the rest of the descriptors. + /// }); + /// ]]> + /// + public static IContainer Populate( + this IContainer container, IEnumerable descriptors, + Func registerDescriptor = null + ) + { + if (registerDescriptor == null) + foreach (var descriptor in descriptors) + container.RegisterDescriptor(descriptor); + else + foreach (var descriptor in descriptors) + if (!registerDescriptor(container, descriptor)) + container.RegisterDescriptor(descriptor); + return container; + } - return container; - } + /// Converts the MS.DI ServiceLifetime into the corresponding `DryIoc.IReuse` + [MethodImpl((MethodImplOptions)256)] + public static IReuse ToReuse(this ServiceLifetime lifetime) => + lifetime == ServiceLifetime.Singleton ? Reuse.Singleton : + lifetime == ServiceLifetime.Scoped ? Reuse.ScopedOrSingleton : // see, that we have Reuse.ScopedOrSingleton here instead of Reuse.Scoped + Reuse.Transient; - /// Adds services registered in to container - public static IContainer WithCompositionRoot(this IContainer container, Type compositionRootType) + /// Unpacks the service descriptor to register the service in DryIoc container + public static void RegisterDescriptor(this IContainer container, ServiceDescriptor descriptor) + { + var serviceType = descriptor.ServiceType; + var implType = descriptor.ImplementationType; + if (implType != null) { - container.Register(compositionRootType); - container.Resolve(compositionRootType); - return container; + // ensure eventing handlers are pulled in automagically. + container.RegisterMany( + new [] {descriptor.ImplementationType}, + reuse: descriptor.Lifetime.ToReuse(), + serviceTypeCondition: type => type == descriptor.ImplementationType || type == descriptor.ServiceType || typeof(IEventingHandler).IsAssignableFrom(type) || typeof(IJsonRpcHandler).IsAssignableFrom(type), + nonPublicServiceTypes: true + ); } - - /// Adds services registered in to container - public static IContainer WithCompositionRoot(this IContainer container) => - container.WithCompositionRoot(typeof(TCompositionRoot)); - - /// It does not really build anything, it just gets the `IServiceProvider` from the container. - public static IServiceProvider BuildServiceProvider(this IContainer container) => - container.GetServiceProvider(); - - /// Just gets the `IServiceProvider` from the container. - public static IServiceProvider GetServiceProvider(this IResolver container) => - container; - - /// Facade to consolidate DryIoc registrations in - /// The class will be created by container on Startup - /// to enable registrations with injected or full . - /// Adapted container Service provider - /// - /// (Reuse.Singleton); - /// r.Register(Reuse.Transient); - /// r.Register(Reuse.InCurrentScope); - /// } - /// } - /// ]]> - /// - public static IServiceProvider ConfigureServiceProvider(this IContainer container) => - container.WithCompositionRoot().GetServiceProvider(); - - /// Registers service descriptors into container. May be called multiple times with different service collections. - /// The container. - /// The service descriptors. - /// (optional) Custom registration action, should return true to skip normal registration. - /// - /// { - /// if (service.ServiceType == typeof(SomeService)) { - /// r.Register(Made.Of(() => CreateCustomService()), Reuse.Singleton); - /// return true; - /// }; - /// return false; // fallback to normal registrations for the rest of the descriptors. - /// }); - /// ]]> - /// - public static IContainer Populate(this IContainer container, IEnumerable descriptors, - Func? registerDescriptor = null) + else if (descriptor.ImplementationFactory != null) { - if (registerDescriptor == null) - foreach (var descriptor in descriptors) - container.RegisterDescriptor(descriptor); - else - foreach (var descriptor in descriptors) - if (!registerDescriptor(container, descriptor)) - container.RegisterDescriptor(descriptor); - return container; + container.Register( + DelegateFactory.Of(descriptor.ImplementationFactory.ToFactoryDelegate, descriptor.Lifetime.ToReuse()), serviceType, + null, null, isStaticallyChecked: true + ); } - - /// Uses passed descriptor to register service in container: - /// maps DI Lifetime to DryIoc Reuse, - /// and DI registration type to corresponding DryIoc Register, RegisterDelegate or RegisterInstance. - /// The container. - /// Service descriptor. - public static void RegisterDescriptor(this IContainer container, ServiceDescriptor descriptor) + else { - if (descriptor.ImplementationType != null) + // ensure eventing handlers are pulled in automagically. + if (descriptor.ImplementationInstance is not IEnumerable + && descriptor.ImplementationInstance is IEventingHandler or IJsonRpcHandler) { - var reuse = descriptor.Lifetime == ServiceLifetime.Singleton ? Reuse.Singleton - : descriptor.Lifetime == ServiceLifetime.Scoped ? Reuse.Scoped - : Reuse.Transient; - - // ensure eventing handlers are pulled in automagically. - container.RegisterMany( - new [] {descriptor.ImplementationType}, - reuse: reuse, - serviceTypeCondition: type => type == descriptor.ImplementationType || type == descriptor.ServiceType || typeof(IEventingHandler).IsAssignableFrom(type) || typeof(IJsonRpcHandler).IsAssignableFrom(type), - nonPublicServiceTypes: true - ); - } - else if (descriptor.ImplementationFactory != null) - { - var reuse = descriptor.Lifetime == ServiceLifetime.Singleton ? Reuse.Singleton - : descriptor.Lifetime == ServiceLifetime.Scoped ? Reuse.Scoped - : Reuse.Transient; - - container.RegisterDelegate(true, descriptor.ServiceType, - descriptor.ImplementationFactory, - reuse - ); + var instance = descriptor.ImplementationInstance; + container.RegisterInstanceMany(instance, nonPublicServiceTypes: true); + container.TrackDisposable(instance); } else { - // ensure eventing handlers are pulled in automagically. - if (!(descriptor.ImplementationInstance is IEnumerable) && (descriptor.ImplementationInstance is IEventingHandler || descriptor.ImplementationInstance is IJsonRpcHandler)) - { - - container.RegisterInstanceMany( - descriptor.ImplementationInstance, - nonPublicServiceTypes: true - ); - } - else - { - container.RegisterInstance(true, descriptor.ServiceType, descriptor.ImplementationInstance); - } + var instance = descriptor.ImplementationInstance; + container.Register( + InstanceFactory.Of(instance), serviceType, + null, null, isStaticallyChecked: true + ); + container.TrackDisposable(instance); } } } diff --git a/src/JsonRpc/DryIoc/DryIocServiceProviderCapabilities.cs b/src/JsonRpc/DryIoc/DryIocServiceProviderCapabilities.cs new file mode 100644 index 000000000..c291ecc91 --- /dev/null +++ b/src/JsonRpc/DryIoc/DryIocServiceProviderCapabilities.cs @@ -0,0 +1,46 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace DryIoc; + +/// Wrapper of DryIoc `IsRegistered` and `Resolve` throwing the exception on unresolved type capabilities. +internal sealed class DryIocServiceProviderCapabilities : +#if NET6_0_OR_GREATER + IServiceProviderIsService, +#endif + ISupportRequiredService +{ + private readonly IContainer _container; + + /// Statefully wraps the passed + public DryIocServiceProviderCapabilities(IContainer container) => _container = container; + + /// + public bool IsService(Type serviceType) + { + // I am not fully comprehend but MS.DI considers asking for the open-generic type even if it is registered to return `false` + // Probably mixing here the fact that open type cannot be instantiated without providing the concrete type argument. + // But I think it is conflating two things and making the reasoning harder. + if (serviceType.IsGenericTypeDefinition) + return false; + + if ( +#if NET6_0_OR_GREATER + serviceType == typeof(IServiceProviderIsService) || +#endif + serviceType == typeof(ISupportRequiredService) || + serviceType == typeof(IServiceScopeFactory)) + return true; + + if (_container.IsRegistered(serviceType)) + return true; + + if (serviceType.IsGenericType && + _container.IsRegistered(serviceType.GetGenericTypeDefinition())) + return true; + + return _container.IsRegistered(serviceType, factoryType: FactoryType.Wrapper); + } + + /// + public object GetRequiredService(Type serviceType) => _container.Resolve(serviceType); +} \ No newline at end of file diff --git a/src/JsonRpc/DryIoc/DryIocServiceProviderFactory.cs b/src/JsonRpc/DryIoc/DryIocServiceProviderFactory.cs index 28b752b46..fde1de962 100644 --- a/src/JsonRpc/DryIoc/DryIocServiceProviderFactory.cs +++ b/src/JsonRpc/DryIoc/DryIocServiceProviderFactory.cs @@ -1,56 +1,77 @@ -using System; -using Microsoft.Extensions.DependencyInjection; -// ReSharper disable once CheckNamespace +using Microsoft.Extensions.DependencyInjection; -namespace DryIoc +namespace DryIoc; + +/// +/// This DryIoc is supposed to be used with generic `IHostBuilder` like this: +/// +/// +/// await CreateHostBuilder(args).Build().RunAsync(); +/// +/// Rules WithMyRules(Rules currentRules) => currentRules; +/// +/// public static IHostBuilder CreateHostBuilder(string[] args) => +/// Host.CreateDefaultBuilder(args) +/// .UseServiceProviderFactory(new DryIocServiceProviderFactory(new Container(rules => WithMyRules(rules)))) +/// .ConfigureWebHostDefaults(webBuilder => +/// { +/// webBuilder.UseStartup(); +/// }); +/// } +/// ]]> +/// +/// Then register your services in `Startup.ConfigureContainer`. +/// +/// DON'T try to change the container rules there - they will be lost, +/// instead pass the pre-configured container to `DryIocServiceProviderFactory` as in example above. +/// By default container will use +/// +/// DON'T forget to add `services.AddControllers().AddControllersAsServices()` in `Startup.ConfigureServices` +/// in order to access DryIoc diagnostics for controllers, property-injection, etc. +/// +/// +internal class DryIocServiceProviderFactory : IServiceProviderFactory { - /// This DryIoc is supposed to be used with `IHostBuilder` like this: - /// - /// await CreateHostBuilder(args).Build().RunAsync(); - /// - /// public static IHostBuilder CreateHostBuilder(string[] args) => - /// Host.CreateDefaultBuilder(args) - /// .UseServiceProviderFactory(new DryIocServiceProviderFactory(new Container(rules => WithMyRules(rules)))) - /// .ConfigureWebHostDefaults(webBuilder => - /// { - /// webBuilder.UseStartup(); - /// }); - /// } - /// ]]> - /// - /// Then register your services in `Startup.ConfigureContainer`. - /// - /// DON'T try to change the container rules there - they will be lost, - /// instead pass the pre-configured container to `DryIocServiceProviderFactory` as in example above. - /// - /// DON'T forget to add `services.AddControllers().AddControllersAsServices` in `Startup.ConfigureServices` - /// in order to access DryIoc diagnostics for controllers, property-injection, etc. - /// - /// That's probably ALL YOU NEED to do. + private readonly IContainer _container; + private readonly Func _registerDescriptor; + private readonly RegistrySharing _registrySharing; + + /// + /// We won't initialize the container here because it is logically expected to be done in `CreateBuilder`, + /// so the factory constructor is just saving some options to use later. /// - internal class DryIocServiceProviderFactory : IServiceProviderFactory + public DryIocServiceProviderFactory( + IContainer container = null, + Func registerDescriptor = null + ) : + this(container, RegistrySharing.CloneAndDropCache, registerDescriptor) { - private readonly IContainer? _container; - private readonly Func? _registerDescriptor; + } - /// Some options to push to `.WithDependencyInjectionAdapter(...)` - public DryIocServiceProviderFactory( - IContainer? container = null, - Func? registerDescriptor = null) - { - _container = container; // we won't initialize the container here because it is logically expected to be done in `CreateBuilder` - _registerDescriptor = registerDescriptor; - } + /// + /// `container` is the existing container which will be cloned with the MS.DI rules and its cache will be dropped, + /// unless the `registrySharing` is set to the `RegistrySharing.Share` or to `RegistrySharing.CloneButKeepCache`. + /// `registerDescriptor` is the custom service descriptor handler. + /// + public DryIocServiceProviderFactory( + IContainer container, RegistrySharing registrySharing, + Func registerDescriptor = null + ) + { + _container = container; + _registrySharing = registrySharing; + _registerDescriptor = registerDescriptor; + } - /// - public IContainer CreateBuilder(IServiceCollection services) => - (_container ?? new Container()).WithDependencyInjectionAdapter(services, _registerDescriptor); + /// + public IContainer CreateBuilder(IServiceCollection services) => + ( _container ?? new Container(Rules.MicrosoftDependencyInjectionRules) ) + .WithDependencyInjectionAdapter(services, _registerDescriptor, _registrySharing); - /// - public IServiceProvider CreateServiceProvider(IContainer container) => - container.BuildServiceProvider(); - } -} + /// + public IServiceProvider CreateServiceProvider(IContainer container) => + container.BuildServiceProvider(); +} \ No newline at end of file diff --git a/src/JsonRpc/DryIoc/DryIocServiceScope.cs b/src/JsonRpc/DryIoc/DryIocServiceScope.cs index d1951a5c5..b0688b136 100644 --- a/src/JsonRpc/DryIoc/DryIocServiceScope.cs +++ b/src/JsonRpc/DryIoc/DryIocServiceScope.cs @@ -1,24 +1,18 @@ -using System; -using Microsoft.Extensions.DependencyInjection; -// ReSharper disable once CheckNamespace +using Microsoft.Extensions.DependencyInjection; -namespace DryIoc +namespace DryIoc; + +/// Bare-bones IServiceScope implementations +internal sealed class DryIocServiceScope : IServiceScope { - /// Bare-bones IServiceScope implementations - internal sealed class DryIocServiceScope : IServiceScope - { - /// - public IServiceProvider ServiceProvider => _resolverContext; + /// + public IServiceProvider ServiceProvider => _resolverContext; - private readonly IResolverContext _resolverContext; + private readonly IResolverContext _resolverContext; - /// Creating from resolver context - public DryIocServiceScope(IResolverContext resolverContext) - { - _resolverContext = resolverContext; - } + /// Creating from resolver context + public DryIocServiceScope(IResolverContext resolverContext) => _resolverContext = resolverContext; - /// Disposes the underlying resolver context - public void Dispose() => _resolverContext.Dispose(); - } -} + /// Disposes the underlying resolver context + public void Dispose() => _resolverContext.Dispose(); +} \ No newline at end of file diff --git a/src/JsonRpc/DryIoc/DryIocServiceScopeFactory.cs b/src/JsonRpc/DryIoc/DryIocServiceScopeFactory.cs index f45a9e738..742855a28 100644 --- a/src/JsonRpc/DryIoc/DryIocServiceScopeFactory.cs +++ b/src/JsonRpc/DryIoc/DryIocServiceScopeFactory.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.DependencyInjection; + // ReSharper disable once CheckNamespace namespace DryIoc @@ -10,17 +11,16 @@ internal sealed class DryIocServiceScopeFactory : IServiceScopeFactory /// Stores passed scoped container to open nested scope. /// Scoped container to be used to create nested scope. - public DryIocServiceScopeFactory(IResolverContext scopedResolver) - { - _scopedResolver = scopedResolver; - } + public DryIocServiceScopeFactory(IResolverContext scopedResolver) => _scopedResolver = scopedResolver; /// Opens scope and wraps it into DI interface. /// DI wrapper of opened scope. public IServiceScope CreateScope() { var r = _scopedResolver; - var scope = r.ScopeContext == null ? new Scope(r.CurrentScope) : r.ScopeContext.SetCurrent(p => new Scope(p)); + var scope = r.ScopeContext == null + ? Scope.Of(r.OwnCurrentScope) + : r.ScopeContext.SetCurrent(p => Scope.Of(p)); return new DryIocServiceScope(r.WithCurrentScope(scope)); } } 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/JsonRpc.csproj b/src/JsonRpc/JsonRpc.csproj index f62bc92b6..29782f6dc 100644 --- a/src/JsonRpc/JsonRpc.csproj +++ b/src/JsonRpc/JsonRpc.csproj @@ -1,6 +1,6 @@ - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.JsonRpc OmniSharp.Extensions.JsonRpc @@ -14,52 +14,70 @@ - - + - <_Parameter1>OmniSharp.Extensions.LanguageProtocol.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageProtocol.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.JsonRpc.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.JsonRpc.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.LanguageServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.LanguageProtocol, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageProtocol, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.LanguageProtocol.Proposals, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageProtocol.Proposals, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.LanguageServer.Shared, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageServer.Shared, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.LanguageClient, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageClient, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Server, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Server, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Client, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Client, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Shared, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Shared, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.DebugAdapter, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.DebugAdapter.Proposals, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.DebugAdapter.Proposals, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f 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/JsonRpcServerContainer.cs b/src/JsonRpc/JsonRpcServerContainer.cs index b69a102cf..ccc645e85 100644 --- a/src/JsonRpc/JsonRpcServerContainer.cs +++ b/src/JsonRpc/JsonRpcServerContainer.cs @@ -37,7 +37,7 @@ public static IContainer Create(IServiceProvider? outerServiceProvider) rules => rules.WithUnknownServiceResolvers( request => { var value = outerServiceProvider.GetService(request.ServiceType); - return value == null ? null : (Factory) new RegisteredInstanceFactory(value, Reuse.Transient); + return value == null ? null : (Factory) InstanceFactory.Of(value, Reuse.Transient); } ) ); diff --git a/src/JsonRpc/JsonRpcServerServiceCollectionExtensions.cs b/src/JsonRpc/JsonRpcServerServiceCollectionExtensions.cs index e61f8059c..c24bb27d2 100644 --- a/src/JsonRpc/JsonRpcServerServiceCollectionExtensions.cs +++ b/src/JsonRpc/JsonRpcServerServiceCollectionExtensions.cs @@ -49,23 +49,23 @@ internal static IContainer AddJsonRpcServerCore(this IContainer container, Js ); container.Register( - made: new Made.TypedMade().Parameters - .Type(serviceKey: nameof(options.MaximumRequestTimeout)) - .Type(serviceKey: nameof(options.SupportsContentModified)) - .Name("concurrency", serviceKey: nameof(options.Concurrency)), + made: Made.Of().Parameters + .Type(serviceKey: nameof(options.MaximumRequestTimeout)) + .Type(serviceKey: nameof(options.SupportsContentModified)) + .Name("concurrency", serviceKey: nameof(options.Concurrency)), reuse: Reuse.Singleton); if (!container.IsRegistered()) { container.Register( - made: new Made.TypedMade().Parameters - .Type(serviceKey: nameof(options.InputScheduler)), + made: Made.Of().Parameters + .Type(serviceKey: nameof(options.InputScheduler)), reuse: Reuse.Singleton); } container.Register( - made: new Made.TypedMade().Parameters - .Type(serviceKey: nameof(options.Input)) + made: Made.Of().Parameters + .Type(serviceKey: nameof(options.Input)) , reuse: Reuse.Singleton ); 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/Protocol.Proposals.csproj b/src/Protocol.Proposals/Protocol.Proposals.csproj index b330ead61..2e61bfaed 100644 --- a/src/Protocol.Proposals/Protocol.Proposals.csproj +++ b/src/Protocol.Proposals/Protocol.Proposals.csproj @@ -1,19 +1,20 @@ - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.LanguageProtocol.Proposals OmniSharp.Extensions.LanguageServer.Protocol - Proposed Language Server Protocol models, classes, interfaces and helper methods, that may or may not make it into the final spec + Proposed Language Server Protocol models, classes, interfaces and helper methods, that may or may not make it into the final spec - - - + + + - + 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/SemanticTokensBuilder.cs b/src/Protocol/Features/Document/SemanticTokensBuilder.cs index 87c26a98b..bdd5b94a9 100644 --- a/src/Protocol/Features/Document/SemanticTokensBuilder.cs +++ b/src/Protocol/Features/Document/SemanticTokensBuilder.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.LanguageServer.Protocol.Document diff --git a/src/Protocol/Features/Document/SemanticTokensDocument.cs b/src/Protocol/Features/Document/SemanticTokensDocument.cs index a9d7e1155..562478f51 100644 --- a/src/Protocol/Features/Document/SemanticTokensDocument.cs +++ b/src/Protocol/Features/Document/SemanticTokensDocument.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Immutable; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.LanguageServer.Protocol.Document 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/Generation/GenerateContainerAttribute.cs b/src/Protocol/Generation/GenerateContainerAttribute.cs index 793f9bafa..582e7a175 100644 --- a/src/Protocol/Generation/GenerateContainerAttribute.cs +++ b/src/Protocol/Generation/GenerateContainerAttribute.cs @@ -1,11 +1,10 @@ using System; using System.Diagnostics; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace OmniSharp.Extensions.LanguageServer.Protocol.Generation { /// - /// Allows generating a typed container counterpart to any model that implements + /// Allows generating a typed container counterpart to any model that implements /// /// /// Efforts will be made to make this available for consumers once source generators land diff --git a/src/Protocol/Generation/GenerateTypedDataAttribute.cs b/src/Protocol/Generation/GenerateTypedDataAttribute.cs index c016fe25f..4b7d222f1 100644 --- a/src/Protocol/Generation/GenerateTypedDataAttribute.cs +++ b/src/Protocol/Generation/GenerateTypedDataAttribute.cs @@ -1,11 +1,10 @@ using System; using System.Diagnostics; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace OmniSharp.Extensions.LanguageServer.Protocol.Generation { /// - /// Allows generating a typed counterpart to any model that implements + /// Allows generating a typed counterpart to any model that implements /// /// /// Efforts will be made to make this available for consumers once source generators land 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/Protocol.csproj b/src/Protocol/Protocol.csproj index bedebe4d9..28fb52bfa 100644 --- a/src/Protocol/Protocol.csproj +++ b/src/Protocol/Protocol.csproj @@ -1,6 +1,6 @@ - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.LanguageProtocol OmniSharp.Extensions.LanguageServer.Protocol @@ -15,23 +15,34 @@ - + - <_Parameter1>OmniSharp.Extensions.LanguageProtocol.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageProtocol.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.LanguageServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.LanguageProtocol.Proposals, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageProtocol.Proposals, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.LanguageServer.Shared, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageServer.Shared, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.LanguageClient, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageClient, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f 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/Serialization/Converters/RangeOrPlaceholderRangeConverter.cs b/src/Protocol/Serialization/Converters/RangeOrPlaceholderRangeConverter.cs index 38887e41d..ff641aa77 100644 --- a/src/Protocol/Serialization/Converters/RangeOrPlaceholderRangeConverter.cs +++ b/src/Protocol/Serialization/Converters/RangeOrPlaceholderRangeConverter.cs @@ -2,7 +2,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { diff --git a/src/Protocol/Serialization/Converters/TextEditConverter.cs b/src/Protocol/Serialization/Converters/TextEditConverter.cs index 7777a111a..69929db95 100644 --- a/src/Protocol/Serialization/Converters/TextEditConverter.cs +++ b/src/Protocol/Serialization/Converters/TextEditConverter.cs @@ -2,7 +2,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { 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/Protocol/Usings.global.cs b/src/Protocol/Usings.global.cs new file mode 100644 index 000000000..1f6c6a094 --- /dev/null +++ b/src/Protocol/Usings.global.cs @@ -0,0 +1 @@ +global using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; 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 - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.LanguageServer OmniSharp.Extensions.LanguageServer.Server @@ -8,14 +8,15 @@ - - - - + + + + - <_Parameter1>OmniSharp.Extensions.LanguageProtocol.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageProtocol.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f diff --git a/src/Shared/LanguageProtocolServiceCollectionExtensions.cs b/src/Shared/LanguageProtocolServiceCollectionExtensions.cs index 8fa7dc453..0fc0d64d5 100644 --- a/src/Shared/LanguageProtocolServiceCollectionExtensions.cs +++ b/src/Shared/LanguageProtocolServiceCollectionExtensions.cs @@ -1,13 +1,11 @@ using System; using System.Linq; -using System.Reactive.Concurrency; using System.Reflection; using DryIoc; using Microsoft.Extensions.DependencyInjection; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Protocol.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; @@ -15,7 +13,8 @@ namespace OmniSharp.Extensions.LanguageServer.Shared { internal static class LanguageProtocolServiceCollectionExtensions { - internal static IContainer AddLanguageProtocolInternals(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/src/Shared/Shared.csproj b/src/Shared/Shared.csproj index b253a26d1..b42aa76a1 100644 --- a/src/Shared/Shared.csproj +++ b/src/Shared/Shared.csproj @@ -1,23 +1,26 @@ - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.LanguageServer.Shared OmniSharp.Extensions.LanguageServer.Shared Shared classes for language server protocol - + - <_Parameter1>OmniSharp.Extensions.LanguageProtocol.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageProtocol.Testing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.LanguageServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f - <_Parameter1>OmniSharp.Extensions.LanguageClient, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f + <_Parameter1 + >OmniSharp.Extensions.LanguageClient, PublicKey=0024000004800000940000000602000000240000525341310004000001000100391db875e68eb4bfef49ce14313b9e13f2cd3cc89eb273bbe6c11a55044c7d4f566cf092e1c77ef9e7c75b1496ae7f95d925938f5a01793dd8d9f99ae0a7595779b71b971287d7d7b5960d052078d14f5ce1a85ea5c9fb2f59ac735ff7bc215cab469b7c3486006860bad6f4c3b5204ea2f28dd4e1d05e2cca462cfd593b9f9f diff --git a/src/Testing/TestContent.cs b/src/Testing/TestContent.cs index a9c52d607..a8b0635e5 100644 --- a/src/Testing/TestContent.cs +++ b/src/Testing/TestContent.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Text; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace OmniSharp.Extensions.LanguageProtocol.Testing { diff --git a/src/Testing/TestSourceHelpers.cs b/src/Testing/TestSourceHelpers.cs index 5b3e588ec..8e06cbf47 100644 --- a/src/Testing/TestSourceHelpers.cs +++ b/src/Testing/TestSourceHelpers.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Linq; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace OmniSharp.Extensions.LanguageProtocol.Testing { diff --git a/src/Testing/Testing.csproj b/src/Testing/Testing.csproj index 279eb835f..4ce49a710 100644 --- a/src/Testing/Testing.csproj +++ b/src/Testing/Testing.csproj @@ -1,7 +1,7 @@  - netstandard2.1;netstandard2.0 + netstandard2.1;netstandard2.0;net6.0 AnyCPU OmniSharp.Extensions.LanguageProtocol.Testing OmniSharp.Extensions.LanguageProtocol.Testing @@ -9,9 +9,9 @@ - - - - + + + + diff --git a/src/Testing/Usings.global.cs b/src/Testing/Usings.global.cs new file mode 100644 index 000000000..1f6c6a094 --- /dev/null +++ b/src/Testing/Usings.global.cs @@ -0,0 +1 @@ +global using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; diff --git a/test/.editorconfig b/test/.editorconfig index f508dbdfa..f1d0802e3 100644 --- a/test/.editorconfig +++ b/test/.editorconfig @@ -1,10 +1,27 @@ -[*] -dotnet_diagnostic.CA2007.severity = none -dotnet_diagnostic.CS0618.severity = none -dotnet_diagnostic.CS4014.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.CS0436.severity = none +dotnet_diagnostic.CA1014.severity = none +dotnet_diagnostic.CA1034.severity = none +dotnet_diagnostic.CA1040.severity = none +dotnet_diagnostic.CA1062.severity = none +dotnet_diagnostic.CA1707.severity = none +dotnet_diagnostic.CA1711.severity = none +dotnet_diagnostic.CA1715.severity = none +dotnet_diagnostic.CA1720.severity = none +dotnet_diagnostic.CA1812.severity = none +dotnet_diagnostic.CA1822.severity = none +dotnet_diagnostic.CA1848.severity = none +dotnet_diagnostic.CA2000.severity = none +dotnet_diagnostic.CA2225.severity = none +dotnet_diagnostic.CA2227.severity = none +dotnet_diagnostic.CA2254.severity = none +dotnet_diagnostic.IDE0060.severity = none +dotnet_diagnostic.RCS1163.severity = none dotnet_diagnostic.VSTHRD200.severity = none +resharper_possible_multiple_enumeration_highlighting = none +resharper_template_is_not_compile_time_constant_problem_highlighting = none +resharper_inconsistent_naming_highlighting = none +resharper_variable_hides_outer_variable_highlighting = none +resharper_unused_parameter_local_highlighting = none +resharper_unused_variable_highlighting = none +resharper_suspicious_type_conversion_global_highlighting = none diff --git a/test/Client.Tests/Client.Tests.csproj b/test/Client.Tests/Client.Tests.csproj index c5d883459..07ae8a6c0 100644 --- a/test/Client.Tests/Client.Tests.csproj +++ b/test/Client.Tests/Client.Tests.csproj @@ -1,7 +1,7 @@ - netcoreapp3.1;net5.0;netcoreapp2.1 + netcoreapp3.1;net6.0 OmniSharp.Extensions.LanguageClient.Tests OmniSharp.Extensions.LanguageServer.Client.Tests diff --git a/test/Client.Tests/ClientTests.cs b/test/Client.Tests/ClientTests.cs index e435f3bb9..6c31d0426 100644 --- a/test/Client.Tests/ClientTests.cs +++ b/test/Client.Tests/ClientTests.cs @@ -7,11 +7,11 @@ 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; + namespace OmniSharp.Extensions.LanguageServer.Client.Tests { /// @@ -46,16 +46,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 +71,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 +87,8 @@ public async Task Hover_Success() ); var hover = await client.TextDocument.RequestHover( - new HoverParams { + new HoverParams + { TextDocument = AbsoluteDocumentPath, Position = ( line, column ) } @@ -118,11 +125,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 +140,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 +160,11 @@ public async Task Completions_Success() } ); }, - serverOptions => { + serverOptions => + { serverOptions.OnCompletion( - (request, _) => { + (request, _) => + { Assert.NotNull(request.TextDocument); Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); @@ -168,7 +184,8 @@ public async Task Completions_Success() ); var actualCompletions = await client.TextDocument.RequestCompletion( - new CompletionParams { + new CompletionParams + { TextDocument = AbsoluteDocumentPath, Position = ( line, column ), }, CancellationToken @@ -179,7 +196,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 +241,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 +264,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 +300,8 @@ public async Task SignatureHelp_Success() ); var actualSignatureHelp = await client.TextDocument.RequestSignatureHelp( - new SignatureHelpParams { + new SignatureHelpParams + { TextDocument = AbsoluteDocumentPath, Position = ( line, column ), }, CancellationToken @@ -282,7 +312,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 +325,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 +350,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 +359,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 +387,8 @@ public async Task Definition_Success() ); var definitions = await client.TextDocument.RequestDefinition( - new DefinitionParams { + new DefinitionParams + { TextDocument = AbsoluteDocumentPath, Position = ( line, column ), }, CancellationToken @@ -358,7 +396,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 +432,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 +465,8 @@ public async Task DocumentHighlights_Success() ); var definitions = await client.TextDocument.RequestDocumentHighlight( - new DocumentHighlightParams { + new DocumentHighlightParams + { TextDocument = AbsoluteDocumentPath, Position = ( line, column ), }, CancellationToken @@ -430,7 +474,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 +503,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 +514,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 +551,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 +595,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 +606,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 +630,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 +660,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 +690,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 +707,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/Dap.Tests.csproj b/test/Dap.Tests/Dap.Tests.csproj index 91db07c80..e61abe1ff 100644 --- a/test/Dap.Tests/Dap.Tests.csproj +++ b/test/Dap.Tests/Dap.Tests.csproj @@ -1,6 +1,6 @@  - netcoreapp3.1;net5.0;netcoreapp2.1 + netcoreapp3.1;net6.0 true AnyCPU 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 715f763b7..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,20 +25,23 @@ 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); }; - action.Should().Throw(); + await action.Should().ThrowAsync(); } [Fact(Skip = "Needs Work")] - public void Should_Cancel_Requests_After_Timeout() + 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)); } @@ -47,19 +49,22 @@ public void Should_Cancel_Requests_After_Timeout() return await client.RequestCompletions(new CompletionsArguments()); }; - action.Should().Throw(); + await action.Should().ThrowAsync(); } 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 67abc23a2..3565b53ae 100644 --- a/test/Generation.Tests/AutoImplementParamsGeneratorTests.cs +++ b/test/Generation.Tests/AutoImplementParamsGeneratorTests.cs @@ -1,7 +1,5 @@ using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc.Generators; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; -using TestingUtils; using Xunit; namespace Generation.Tests @@ -32,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 @@ -39,22 +39,13 @@ namespace Test public partial class DeclarationParams { [Optional] - public ProgressToken? WorkDoneToken - { - get; - init; - } + public ProgressToken? WorkDoneToken { get; init; } [Optional] - public ProgressToken? PartialResultToken - { - get; - init; - } + public ProgressToken? PartialResultToken { get; init; } } } #nullable restore"; - CacheKeyHasher.Cache = true; await GenerationHelpers.AssertGeneratedAsExpected(source, expected); await GenerationHelpers.AssertGeneratedAsExpected(source, expected); } diff --git a/test/Generation.Tests/EnumLikeStringGeneratorTests.cs b/test/Generation.Tests/EnumLikeStringGeneratorTests.cs index e151a270b..320a396fc 100644 --- a/test/Generation.Tests/EnumLikeStringGeneratorTests.cs +++ b/test/Generation.Tests/EnumLikeStringGeneratorTests.cs @@ -1,7 +1,5 @@ using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc.Generators; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; -using TestingUtils; using Xunit; namespace Generation.Tests @@ -41,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; @@ -58,7 +56,6 @@ namespace Test } } #nullable restore"; - CacheKeyHasher.Cache = true; await GenerationHelpers.AssertGeneratedAsExpected(source, expected); } } diff --git a/test/Generation.Tests/GeneratedRegistrationOptionsTests.cs b/test/Generation.Tests/GeneratedRegistrationOptionsTests.cs index 1ff3de714..1ab1e1561 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 @@ -35,11 +34,7 @@ namespace Test public partial class WorkspaceSymbolRegistrationOptions : OmniSharp.Extensions.LanguageServer.Protocol.IRegistrationOptions, OmniSharp.Extensions.LanguageServer.Protocol.Models.IWorkDoneProgressOptions { [Optional] - public bool WorkDoneProgress - { - get; - set; - } + public bool WorkDoneProgress { get; set; } class WorkspaceSymbolRegistrationOptionsConverter : RegistrationOptionsConverterBase { @@ -57,17 +52,14 @@ public override StaticOptions Convert(WorkspaceSymbolRegistrationOptions source) public partial class StaticOptions : OmniSharp.Extensions.LanguageServer.Protocol.Models.IWorkDoneProgressOptions { [Optional] - public bool WorkDoneProgress - { - get; - set; - } + public bool WorkDoneProgress { get; set; } } } } #nullable restore"; await GenerationHelpers.AssertGeneratedAsExpected(source, expected); } + [Fact] public async Task Supports_Generating_Strongly_Typed_WorkDone_Registration_Options_Interface() { @@ -99,11 +91,7 @@ namespace Test public partial class WorkspaceSymbolRegistrationOptions : OmniSharp.Extensions.LanguageServer.Protocol.IRegistrationOptions { [Optional] - public bool WorkDoneProgress - { - get; - set; - } + public bool WorkDoneProgress { get; set; } class WorkspaceSymbolRegistrationOptionsConverter : RegistrationOptionsConverterBase { @@ -121,11 +109,7 @@ public override StaticOptions Convert(WorkspaceSymbolRegistrationOptions source) public partial class StaticOptions : IWorkDoneProgressOptions { [Optional] - public bool WorkDoneProgress - { - get; - set; - } + public bool WorkDoneProgress { get; set; } } } } @@ -153,7 +137,7 @@ public async Task Supports_Generating_Strongly_Typed_Registration_Options() using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server; using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + #nullable enable namespace OmniSharp.Extensions.LanguageServer.Protocol.Test @@ -199,7 +183,6 @@ public partial class CodeActionRegistrationOptions using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server; using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; #nullable enable namespace OmniSharp.Extensions.LanguageServer.Protocol.Test @@ -208,18 +191,10 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Test [RegistrationOptionsConverterAttribute(typeof(CodeActionRegistrationOptionsConverter))] public partial class CodeActionRegistrationOptions : OmniSharp.Extensions.LanguageServer.Protocol.IRegistrationOptions, OmniSharp.Extensions.LanguageServer.Protocol.Models.ITextDocumentRegistrationOptions, OmniSharp.Extensions.LanguageServer.Protocol.Models.IWorkDoneProgressOptions { - public DocumentSelector? DocumentSelector - { - get; - set; - } + public DocumentSelector? DocumentSelector { get; set; } [Optional] - public bool WorkDoneProgress - { - get; - set; - } + public bool WorkDoneProgress { get; set; } class CodeActionRegistrationOptionsConverter : RegistrationOptionsConverterBase { @@ -243,13 +218,7 @@ public partial class StaticOptions : OmniSharp.Extensions.LanguageServer.Protoco /// may list out every specific kind they provide. /// [Optional] - public Container? CodeActionKinds - { - get; - set; - } - - = new Container(); + public Container? CodeActionKinds { get; set; } = new Container(); /// /// The server provides support to resolve additional /// information for a code action. @@ -257,18 +226,10 @@ public Container? CodeActionKinds /// @since 3.16.0 /// [Optional] - public bool ResolveProvider - { - get; - set; - } + public bool ResolveProvider { get; set; } [Optional] - public bool WorkDoneProgress - { - get; - set; - } + public bool WorkDoneProgress { get; set; } } } } @@ -295,7 +256,6 @@ public async Task Supports_Generating_Strongly_Typed_Registration_Options_With_C using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; #nullable enable namespace OmniSharp.Extensions.LanguageServer.Protocol.Test @@ -360,7 +320,6 @@ public override StaticCodeActionRegistrationOptions Convert(CodeActionRegistrati using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; #nullable enable @@ -369,18 +328,10 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Test [RegistrationOptionsKey(nameof(ServerCapabilities.CodeActionProvider))] public partial class CodeActionRegistrationOptions : OmniSharp.Extensions.LanguageServer.Protocol.IRegistrationOptions { - public DocumentSelector? DocumentSelector - { - get; - set; - } + public DocumentSelector? DocumentSelector { get; set; } [Optional] - public bool WorkDoneProgress - { - get; - set; - } + public bool WorkDoneProgress { get; set; } [RegistrationOptionsKey(nameof(ServerCapabilities.CodeActionProvider))] public partial class StaticOptions : IWorkDoneProgressOptions @@ -392,13 +343,7 @@ public partial class StaticOptions : IWorkDoneProgressOptions /// may list out every specific kind they provide. /// [Optional] - public Container? CodeActionKinds - { - get; - set; - } - - = new Container(); + public Container? CodeActionKinds { get; set; } = new Container(); /// /// The server provides support to resolve additional /// information for a code action. @@ -406,18 +351,10 @@ public Container? CodeActionKinds /// @since 3.16.0 /// [Optional] - public bool ResolveProvider - { - get; - set; - } + public bool ResolveProvider { get; set; } [Optional] - public bool WorkDoneProgress - { - get; - set; - } + public bool WorkDoneProgress { get; set; } } } } diff --git a/test/Generation.Tests/Generation.Tests.csproj b/test/Generation.Tests/Generation.Tests.csproj index 9da152b04..8f8f18ef0 100644 --- a/test/Generation.Tests/Generation.Tests.csproj +++ b/test/Generation.Tests/Generation.Tests.csproj @@ -1,6 +1,6 @@ - netcoreapp3.1;net5.0;netcoreapp2.1 + netcoreapp3.1;net6.0 true AnyCPU @@ -12,6 +12,5 @@ - diff --git a/test/Generation.Tests/GenerationHelpers.cs b/test/Generation.Tests/GenerationHelpers.cs index b1aa84fdc..5dc0da1a2 100644 --- a/test/Generation.Tests/GenerationHelpers.cs +++ b/test/Generation.Tests/GenerationHelpers.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; @@ -11,10 +12,12 @@ using Newtonsoft.Json.Linq; using OmniSharp.Extensions.DebugAdapter.Protocol.Client; using OmniSharp.Extensions.JsonRpc.Generation; -using OmniSharp.Extensions.JsonRpc.Generators; 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 @@ -23,7 +26,8 @@ static GenerationHelpers() { // this "core assemblies hack" is from https://stackoverflow.com/a/47196516/4418060 var coreAssemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location)!; - var coreAssemblyNames = new[] { + var coreAssemblyNames = new[] + { "mscorlib.dll", "netstandard.dll", "System.dll", @@ -35,9 +39,11 @@ static GenerationHelpers() }; var coreMetaReferences = coreAssemblyNames.Select(x => MetadataReference.CreateFromFile(Path.Combine(coreAssemblyPath, x))); - var otherAssemblies = new[] { + var otherAssemblies = new[] + { typeof(CSharpCompilation).Assembly, typeof(GenerateHandlerMethodsAttribute).Assembly, + typeof(GenerationHelpers).Assembly, typeof(IDebugAdapterClientRegistry).Assembly, typeof(Unit).Assembly, typeof(JToken).Assembly, @@ -54,33 +60,34 @@ static GenerationHelpers() internal const string CSharpDefaultFileExt = "cs"; internal const string TestProjectName = "TestProject"; - internal static readonly string NormalizedPreamble = NormalizeToLf(Preamble.GeneratedByATool + Lf); - internal static readonly ImmutableArray MetadataReferences; - public static async Task AssertGeneratedAsExpected(string source, string expected) where T : ISourceGenerator, new() + public static async Task AssertGeneratedAsExpected(string source, string expected) where T : IIncrementalGenerator, new() { var generatedTree = await GenerateAsync(source); // normalize line endings to just LF - var generatedText = NormalizeToLf(generatedTree.GetText().ToString()).Trim(); + var generatedText = NormalizeToLf(generatedTree.Last().GetText().ToString()).Trim(); // and append preamble to the expected - var expectedText = NormalizedPreamble + NormalizeToLf(expected).Trim(); + var expectedText = NormalizeToLf(expected).Trim(); // Assert.Equal(expectedText, generatedText); generatedText.Should().Be(expectedText); } - public static async Task Generate(string source) where T : ISourceGenerator, new() + public static async Task Generate(string source) where T : IIncrementalGenerator, new() { var generatedTree = await GenerateAsync(source); // normalize line endings to just LF - var generatedText = NormalizeToLf(generatedTree.GetText().ToString()); + var generatedText = NormalizeToLf(generatedTree.Last().GetText().ToString()); // and append preamble to the expected 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 : ISourceGenerator, new() + public static async Task> GenerateAsync(string source) where T : IIncrementalGenerator, new() { var document = CreateProject(source).Documents.Single(); var tree = await document.GetSyntaxTreeAsync(); @@ -89,7 +96,7 @@ static GenerationHelpers() throw new InvalidOperationException("Could not get the syntax tree of the sources"); } - var compilation = (CSharpCompilation) (await document.Project.GetCompilationAsync())!; + var compilation = (CSharpCompilation)( await document.Project.GetCompilationAsync() )!; if (compilation is null) { throw new InvalidOperationException("Could not compile the sources"); @@ -98,10 +105,10 @@ static GenerationHelpers() var diagnostics = compilation.GetDiagnostics(); // Assert.Empty(diagnostics.Where(x => x.Severity >= DiagnosticSeverity.Warning)); - ISourceGenerator generator = new T(); + IIncrementalGenerator generator = new T(); var driver = CSharpGeneratorDriver.Create( - ImmutableArray.Create(generator), + ImmutableArray.Create(generator.AsSourceGenerator()), ImmutableArray.Empty, compilation.SyntaxTrees[0].Options as CSharpParseOptions ); @@ -110,7 +117,9 @@ compilation.SyntaxTrees[0].Options as CSharpParseOptions Assert.Empty(diagnostics.Where(x => x.Severity >= DiagnosticSeverity.Warning)); // the syntax tree added by the generator will be the last one in the compilation - return outputCompilation.SyntaxTrees.Last(z => !z.FilePath.Contains("AssemblyRegistrationOptions") && !z.FilePath.Contains("GeneratedAssemblyJsonRpcHandlers")); + return outputCompilation.SyntaxTrees.Where( + z => !z.FilePath.Contains("AssemblyRegistrationOptions") && !z.FilePath.Contains("GeneratedAssemblyJsonRpcHandlers") + ); } public static Project CreateProject(params string[] sources) @@ -148,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 87b7e43de..496e8eed2 100644 --- a/test/Generation.Tests/JsonRpcGenerationTests.cs +++ b/test/Generation.Tests/JsonRpcGenerationTests.cs @@ -1,9 +1,6 @@ -using System; using System.Threading.Tasks; using FluentAssertions; using OmniSharp.Extensions.JsonRpc.Generators; -using OmniSharp.Extensions.JsonRpc.Generators.Cache; -using TestingUtils; using Xunit; using Xunit.Sdk; using static Generation.Tests.GenerationHelpers; @@ -206,10 +203,9 @@ public interface IExitHandler : IJsonRpcNotificationHandler } }"; - CacheKeyHasher.Cache = true; - Func a = () => AssertGeneratedAsExpected(source, ""); - a.Should().Throw().WithMessage("*Could not infer the request router(s)*"); - a.Should().Throw("cache").WithMessage("*Could not infer the request router(s)*"); + 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)*"); } [Fact] diff --git a/test/Generation.Tests/LspFeatureTests.cs b/test/Generation.Tests/LspFeatureTests.cs index ed42f75f3..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 @@ -54,7 +53,7 @@ abstract public partial class WorkspaceSymbolsHandlerBase : AbstractHandlers.Req [System.Runtime.CompilerServices.CompilerGeneratedAttribute, System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] abstract public partial class WorkspaceSymbolsPartialHandlerBase : AbstractHandlers.PartialResults?, SymbolInformation, WorkspaceSymbolRegistrationOptions, WorkspaceSymbolCapability>, IWorkspaceSymbolsHandler { - protected WorkspaceSymbolsPartialHandlerBase(System.Guid id, IProgressManager progressManager): base(progressManager, Container.From) + protected WorkspaceSymbolsPartialHandlerBase(System.Guid id, IProgressManager progressManager) : base(progressManager, Container.From) { } } @@ -109,12 +108,6 @@ public static ILanguageServerRegistry ObserveWorkspaceSymbols(this ILanguageServ public async Task Supports_Generating_Custom_Language_Extensions() { var source = @" -// ------------------------------------------------------------------------------ -// -// This code was generated a code generator. -// -// ------------------------------------------------------------------------------ - using MediatR; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; @@ -189,11 +182,7 @@ namespace Lsp.Tests.Integration.Fixtures public partial class UnitTestRegistrationOptions : OmniSharp.Extensions.LanguageServer.Protocol.IRegistrationOptions { [Optional] - public bool WorkDoneProgress - { - get; - set; - } + public bool WorkDoneProgress { get; set; } class UnitTestRegistrationOptionsConverter : RegistrationOptionsConverterBase { @@ -211,18 +200,10 @@ public override StaticOptions Convert(UnitTestRegistrationOptions source) public partial class StaticOptions : IWorkDoneProgressOptions { [Optional] - public bool SupportsDebugging - { - get; - set; - } + public bool SupportsDebugging { get; set; } [Optional] - public bool WorkDoneProgress - { - get; - set; - } + public bool WorkDoneProgress { get; set; } } } } @@ -321,7 +302,7 @@ abstract public partial class DiscoverUnitTestsHandlerBase : AbstractHandlers.Re [System.Runtime.CompilerServices.CompilerGeneratedAttribute, System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] abstract public partial class DiscoverUnitTestsPartialHandlerBase : AbstractHandlers.PartialResults, UnitTest, UnitTestRegistrationOptions, UnitTestCapability>, IDiscoverUnitTestsHandler { - protected DiscoverUnitTestsPartialHandlerBase(System.Guid id, IProgressManager progressManager): base(progressManager, Container.From) + protected DiscoverUnitTestsPartialHandlerBase(System.Guid id, IProgressManager progressManager) : base(progressManager, Container.From) { } } diff --git a/test/Generation.Tests/TypedCanBeResolvedTests.cs b/test/Generation.Tests/TypedCanBeResolvedTests.cs index 2d7b0b28e..e3512ef7e 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 @@ -26,7 +25,6 @@ public async Task Supports_Generating_Strongly_Typed_ICanBeResolved_Data() using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; #nullable enable namespace OmniSharp.Extensions.LanguageServer.Protocol.Test @@ -77,7 +75,6 @@ public partial record CodeLens : IRequest, ICanBeResolved using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Immutable; @@ -98,10 +95,9 @@ public CodeLens WithData(TData data) public static CodeLens? From(CodeLens? item) where T : class?, IHandlerIdentity? => item switch { - not null => item, _ => null - } - - ; + not null => item, + _ => null + }; } /// @@ -118,29 +114,17 @@ public partial record CodeLens : ICanBeResolved where T : class?, IHandlerIde /// /// 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; } [Optional] - public Command? Command - { - get; - init; - } + public Command? Command { get; init; } /// /// A data entry field that is preserved on a code lens item between /// a code lens and a code lens resolve request. /// [Optional] - public T Data - { - get => this.GetRawData()!; - init => this.SetRawData(value); - } + public T Data { get => this.GetRawData()!; init => this.SetRawData(value); } private string DebuggerDisplay => $""{Range}{(Command != null ? $"" {Command}"" : """")}""; public override string ToString() => DebuggerDisplay; @@ -150,133 +134,111 @@ public CodeLens WithData(TData data) return new CodeLens{Range = Range, Command = Command, Data = data}; } - JToken? ICanBeResolved.Data - { - get; - init; - } + JToken? ICanBeResolved.Data { get; init; } - private JToken? JData - { - get => this.GetRawData(); - init => this.SetRawData(value); - } + private JToken? JData { get => this.GetRawData(); init => this.SetRawData(value); } public static implicit operator CodeLens(CodeLens value) => new CodeLens{Range = value.Range, Command = value.Command, JData = value.Data}; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""value"")] public static implicit operator CodeLens? (CodeLens? value) => value switch { - not null => new CodeLens{Range = value.Range, Command = value.Command, Data = value.JData}, _ => null - } - - ; + not null => new CodeLens{Range = value.Range, Command = value.Command, Data = value.JData}, + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""item"")] public static CodeLens? From(CodeLens? item) => item switch { - not null => item, _ => null - } - - ; + not null => item, + _ => null + }; } public partial class CodeLensContainer : ContainerBase> where T : class?, IHandlerIdentity? { - public CodeLensContainer(): this(Enumerable.Empty>()) + public CodeLensContainer() : this(Enumerable.Empty>()) { } - public CodeLensContainer(IEnumerable> items): base(items) + public CodeLensContainer(IEnumerable> items) : base(items) { } - public CodeLensContainer(params CodeLens[] items): base(items) + public CodeLensContainer(params CodeLens[] items) : base(items) { } [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static CodeLensContainer? From(IEnumerable>? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static implicit operator CodeLensContainer? (CodeLens[] items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static CodeLensContainer? From(params CodeLens[] items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static implicit operator CodeLensContainer? (Collection>? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static CodeLensContainer? From(Collection>? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static implicit operator CodeLensContainer? (List>? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static CodeLensContainer? From(List>? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static implicit operator CodeLensContainer? (in ImmutableArray>? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static CodeLensContainer? From(in ImmutableArray>? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static implicit operator CodeLensContainer? (ImmutableList>? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static CodeLensContainer? From(ImmutableList>? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""container"")] public static implicit operator CodeLensContainer? (CodeLensContainer? container) => container switch { - not null => new CodeLensContainer(container.Select(value => (CodeLens)value)), _ => null - } - - ; + not null => new CodeLensContainer(container.Select(value => (CodeLens)value)), + _ => null + }; } } #nullable restore"; @@ -302,7 +264,6 @@ public async Task Supports_Generating_Strongly_Typed_Container() using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; #nullable enable namespace OmniSharp.Extensions.LanguageServer.Protocol.Test @@ -352,7 +313,6 @@ public partial class CodeLens : IRequest, ICanBeResolved using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Immutable; @@ -364,95 +324,84 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Test [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute, System.Runtime.CompilerServices.CompilerGeneratedAttribute] public partial class CodeLensContainer : ContainerBase { - public CodeLensContainer(): this(Enumerable.Empty()) + public CodeLensContainer() : this(Enumerable.Empty()) { } - public CodeLensContainer(IEnumerable items): base(items) + public CodeLensContainer(IEnumerable items) : base(items) { } - public CodeLensContainer(params CodeLens[] items): base(items) + public CodeLensContainer(params CodeLens[] items) : base(items) { } [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static CodeLensContainer? From(IEnumerable? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static implicit operator CodeLensContainer? (CodeLens[] items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static CodeLensContainer? From(params CodeLens[] items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static implicit operator CodeLensContainer? (Collection? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static CodeLensContainer? From(Collection? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static implicit operator CodeLensContainer? (List? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static CodeLensContainer? From(List? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static implicit operator CodeLensContainer? (in ImmutableArray? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static CodeLensContainer? From(in ImmutableArray? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static implicit operator CodeLensContainer? (ImmutableList? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(""items"")] public static CodeLensContainer? From(ImmutableList? items) => items switch { - not null => new CodeLensContainer(items), _ => null - } - - ; + not null => new CodeLensContainer(items), + _ => null + }; } } #nullable restore"; diff --git a/test/JsonRpc.Tests/HandlerResolverTests.cs b/test/JsonRpc.Tests/HandlerResolverTests.cs index fcdf543f9..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; @@ -39,28 +38,40 @@ public interface IJsonRpcNotificationDataHandler : IJsonRpcNotificationHandler(), new AssemblyScanningHandlerTypeDescriptorProvider(new [] { typeof(AssemblyScanningHandlerTypeDescriptorProvider).Assembly, typeof(HandlerResolverTests).Assembly })) { - (IJsonRpcHandler) Substitute.For(new[] { requestHandler }, new object[0]) + 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); } - [Theory] + [Theory(Skip = "Inaccurate")] [InlineData(typeof(IJsonRpcRequestHandler), "request", null)] [InlineData(typeof(IJsonRpcRequestResponseHandler), "requestresponse", typeof(Request))] [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 }, new object[0]) + 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().IsSameOrEqualTo(expected); + 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 755efba60..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,29 +49,32 @@ 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); - clientRequest.Should().Throw(); + Func clientRequest = () => client.SendRequest("myrequest", (Request)null!).Returning(CancellationToken); + await clientRequest.Should().ThrowAsync(); - Func serverRequest = () => server.SendRequest("myrequest", (Request) null!).Returning(CancellationToken); - serverRequest.Should().Throw(); + Func serverRequest = () => server.SendRequest("myrequest", (Request)null!).Returning(CancellationToken); + await serverRequest.Should().ThrowAsync(); } [Fact] 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); - clientRequest.Should().Throw(); + await clientRequest.Should().ThrowAsync(); Func serverRequest = () => server.SendRequest("myrequest", new Request()).Returning(CancellationToken); - serverRequest.Should().Throw(); + await serverRequest.Should().ThrowAsync(); } [Fact] @@ -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/JsonRpc.Tests.csproj b/test/JsonRpc.Tests/JsonRpc.Tests.csproj index 2c42ce7ea..163f47307 100644 --- a/test/JsonRpc.Tests/JsonRpc.Tests.csproj +++ b/test/JsonRpc.Tests/JsonRpc.Tests.csproj @@ -1,6 +1,6 @@ - netcoreapp3.1;net5.0;netcoreapp2.1 + netcoreapp3.1;net6.0 true AnyCPU diff --git a/test/JsonRpc.Tests/RecursiveResolutionTests.cs b/test/JsonRpc.Tests/RecursiveResolutionTests.cs index 16fa140f1..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; @@ -21,9 +20,10 @@ public RecursiveResolutionTests(ITestOutputHelper testOutputHelper) : base(new J } [Fact(Skip = "appears to cause a deadlock")] - public void Server_Can_Be_Injected_Into_Handler_After_Creation_Using_Registration() + 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 => { } @@ -34,11 +34,11 @@ public void Server_Can_Be_Injected_Into_Handler_After_Creation_Using_Registratio .AddHandler>() ); }; - a.Should().NotThrow(); + await a.Should().NotThrowAsync(); } [Fact(Skip = "appears to cause a deadlock")] - public void Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_Registration() + public async Task Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_Registration() { Func a = () => Initialize( options => { }, @@ -46,12 +46,12 @@ public void Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_Registr .AddHandler>() .AddHandler>() ); - var result = a.Should().Throw(); + var result = await a.Should().ThrowAsync(); result.And.ErrorName.Should().Be("UnableToResolveFromRegisteredServices"); } [Fact(Skip = "appears to cause a deadlock")] - public void Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_Description() + public async Task Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_Description() { Func a = () => Initialize( options => { }, @@ -59,12 +59,12 @@ public void Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_Descrip .AddSingleton(JsonRpcHandlerDescription.Infer(typeof(InterfaceHandler))) .AddSingleton(JsonRpcHandlerDescription.Infer(typeof(ClassHandler))) ); - var result = a.Should().Throw(); + var result = await a.Should().ThrowAsync(); result.And.ErrorName.Should().Be("UnableToResolveFromRegisteredServices"); } [Fact(Skip = "appears to cause a deadlock")] - public void Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_Injection() + public async Task Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_Injection() { Func a = () => Initialize( options => { }, @@ -72,7 +72,7 @@ public void Server_Cannot_Be_Injected_Into_Handler_During_Creation_Using_Injecti .AddSingleton>() .AddSingleton>() ); - var result = a.Should().Throw(); + var result = await a.Should().ThrowAsync(); result.And.ErrorName.Should().Be("UnableToResolveFromRegisteredServices"); } @@ -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 581d12a5b..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,22 +26,26 @@ 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() } }; var req = client.SendRequest(TextDocumentNames.CodeAction, codeActionParams); Func a = () => req.Returning(CancellationToken); - a.Should().Throw(); + await a.Should().ThrowAsync(); } [Fact] @@ -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..9066bf3a4 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..732a46dde 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 684b95d3d..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,14 +51,16 @@ 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" }); - a.Should().NotThrow(); + Func a = () => server.Configuration.GetConfiguration(new ConfigurationItem { Section = "mysection" }); + await a.Should().NotThrowAsync(); } [Fact] @@ -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/Lsp.Integration.Tests.csproj b/test/Lsp.Integration.Tests/Lsp.Integration.Tests.csproj index 46970d637..fcb489822 100644 --- a/test/Lsp.Integration.Tests/Lsp.Integration.Tests.csproj +++ b/test/Lsp.Integration.Tests/Lsp.Integration.Tests.csproj @@ -1,6 +1,6 @@  - net5.0;netcoreapp3.1;netcoreapp2.1 + net6.0;netcoreapp3.1;net6.0 true AnyCPU @@ -19,6 +19,12 @@ - + 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..7c4d6be93 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; @@ -17,9 +16,9 @@ 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 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 4e964bbcc..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,16 +31,18 @@ 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(); }; - action.Should().Throw(); + await action.Should().ThrowAsync(); } [Fact] @@ -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, }, @@ -65,63 +70,72 @@ public async Task Should_Abandon_Pending_Requests_For_Text_Changes() ); Func action = () => request1; - action.Should().Throw(); + await action.Should().ThrowAsync(); } [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(); }; - action.Should().Throw(); + await action.Should().ThrowAsync(); } [Fact] - public void Should_Cancel_Requests_After_Timeout_without_Content_Modified() + 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(); }; - action.Should().Throw(); + await action.Should().ThrowAsync(); } [Fact] 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/Usings.global.cs b/test/Lsp.Integration.Tests/Usings.global.cs new file mode 100644 index 000000000..1f6c6a094 --- /dev/null +++ b/test/Lsp.Integration.Tests/Usings.global.cs @@ -0,0 +1 @@ +global using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; diff --git a/test/Lsp.Integration.Tests/WorkspaceFolderTests.cs b/test/Lsp.Integration.Tests/WorkspaceFolderTests.cs index 2c716f85c..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,19 +75,23 @@ 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(); - a.Should().NotThrow(); + await a.Should().NotThrowAsync(); } [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 972026a55..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 @@ -19,7 +18,7 @@ public void SimpleTest(string expected) result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x.UsingStructuralRecordEquality()); + deresult.Should().Be(model); } } } 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/Lsp.Tests.csproj b/test/Lsp.Tests/Lsp.Tests.csproj index 46970d637..fcb489822 100644 --- a/test/Lsp.Tests/Lsp.Tests.csproj +++ b/test/Lsp.Tests/Lsp.Tests.csproj @@ -1,6 +1,6 @@  - net5.0;netcoreapp3.1;netcoreapp2.1 + net6.0;netcoreapp3.1;net6.0 true AnyCPU @@ -19,6 +19,12 @@ - + diff --git a/test/Lsp.Tests/Matchers/ResolveCommandMatcherTests.cs b/test/Lsp.Tests/Matchers/ResolveCommandMatcherTests.cs index b7313da9c..3633d7007 100644 --- a/test/Lsp.Tests/Matchers/ResolveCommandMatcherTests.cs +++ b/test/Lsp.Tests/Matchers/ResolveCommandMatcherTests.cs @@ -58,7 +58,7 @@ public void Should_Return_Empty_Descriptor() } [Fact] - public void Should_Not_Throw_Given_Another_Descriptor() + public async Task Should_Not_Throw_Given_Another_Descriptor() { // Given var resolveHandler = Substitute.For(); @@ -84,7 +84,7 @@ public void Should_Not_Throw_Given_Another_Descriptor() // When Func a = async () => await handlerMatcher.Handle(new CodeLensParams(), CancellationToken.None, () => Task.FromResult(new CodeLensContainer())); - a.Should().NotThrow(); + await a.Should().NotThrowAsync(); } [Fact] diff --git a/test/Lsp.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs b/test/Lsp.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs index 0b4e8c6a2..e322ee26f 100644 --- a/test/Lsp.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs +++ b/test/Lsp.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs @@ -22,7 +22,6 @@ using Xunit.Abstractions; using Xunit.Sdk; using Arg = NSubstitute.Arg; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; using Request = OmniSharp.Extensions.JsonRpc.Server.Request; #pragma warning disable CS0162 diff --git a/test/Lsp.Tests/Models/ApplyWorkspaceEditParamsTests.cs b/test/Lsp.Tests/Models/ApplyWorkspaceEditParamsTests.cs index ec62c4c1c..9ac2f424c 100644 --- a/test/Lsp.Tests/Models/ApplyWorkspaceEditParamsTests.cs +++ b/test/Lsp.Tests/Models/ApplyWorkspaceEditParamsTests.cs @@ -7,7 +7,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using TestingUtils; using Xunit; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; namespace Lsp.Tests.Models { diff --git a/test/Lsp.Tests/Models/CodeActionParamsTests.cs b/test/Lsp.Tests/Models/CodeActionParamsTests.cs index cbe63cae8..d795dc4a6 100644 --- a/test/Lsp.Tests/Models/CodeActionParamsTests.cs +++ b/test/Lsp.Tests/Models/CodeActionParamsTests.cs @@ -5,7 +5,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using TestingUtils; using Xunit; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace Lsp.Tests.Models { 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 e2bd817e4..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 @@ -19,7 +18,7 @@ public void SimpleTest(string expected) result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x.UsingStructuralRecordEquality()); + deresult.Should().Be(model); } } } diff --git a/test/Lsp.Tests/Models/DiagnosticSeverityTests.cs b/test/Lsp.Tests/Models/DiagnosticSeverityTests.cs index d22423e33..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 @@ -19,7 +18,7 @@ public void SimpleTest(string expected) result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x.UsingStructuralRecordEquality()); + deresult.Should().Be(model); } } } diff --git a/test/Lsp.Tests/Models/DiagnosticTests.cs b/test/Lsp.Tests/Models/DiagnosticTests.cs index 735da6d6c..5af0bf2b3 100644 --- a/test/Lsp.Tests/Models/DiagnosticTests.cs +++ b/test/Lsp.Tests/Models/DiagnosticTests.cs @@ -5,7 +5,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using TestingUtils; using Xunit; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace Lsp.Tests.Models { diff --git a/test/Lsp.Tests/Models/DocumentHighlightKindTests.cs b/test/Lsp.Tests/Models/DocumentHighlightKindTests.cs index 6d1ed3a48..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 @@ -19,7 +18,7 @@ public void SimpleTest(string expected) result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x.UsingStructuralRecordEquality()); + deresult.Should().Be(model); } } } diff --git a/test/Lsp.Tests/Models/DocumentLinkTests.cs b/test/Lsp.Tests/Models/DocumentLinkTests.cs index 92d65f404..a3ddedc5a 100644 --- a/test/Lsp.Tests/Models/DocumentLinkTests.cs +++ b/test/Lsp.Tests/Models/DocumentLinkTests.cs @@ -4,7 +4,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using Xunit; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace Lsp.Tests.Models { diff --git a/test/Lsp.Tests/Models/DocumentSymbolInformationTests.cs b/test/Lsp.Tests/Models/DocumentSymbolInformationTests.cs index c0ff3b0da..07fed7f34 100644 --- a/test/Lsp.Tests/Models/DocumentSymbolInformationTests.cs +++ b/test/Lsp.Tests/Models/DocumentSymbolInformationTests.cs @@ -5,7 +5,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using TestingUtils; using Xunit; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace Lsp.Tests.Models { diff --git a/test/Lsp.Tests/Models/FileChangeTypeTests.cs b/test/Lsp.Tests/Models/FileChangeTypeTests.cs index ea73243cf..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 @@ -19,7 +18,7 @@ public void SimpleTest(string expected) result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x.UsingStructuralRecordEquality()); + deresult.Should().Be(model); } } } diff --git a/test/Lsp.Tests/Models/InsertTextFormatTests.cs b/test/Lsp.Tests/Models/InsertTextFormatTests.cs index 82f3f81fb..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 @@ -19,7 +18,7 @@ public void SimpleTest(string expected) result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x.UsingStructuralRecordEquality()); + deresult.Should().Be(model); } } } diff --git a/test/Lsp.Tests/Models/LocationOrLocationLinksTests.cs b/test/Lsp.Tests/Models/LocationOrLocationLinksTests.cs index 5d6a68457..300d1cb4a 100644 --- a/test/Lsp.Tests/Models/LocationOrLocationLinksTests.cs +++ b/test/Lsp.Tests/Models/LocationOrLocationLinksTests.cs @@ -5,7 +5,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using TestingUtils; using Xunit; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace Lsp.Tests.Models { diff --git a/test/Lsp.Tests/Models/LocationTests.cs b/test/Lsp.Tests/Models/LocationTests.cs index c3d6424f6..025db8316 100644 --- a/test/Lsp.Tests/Models/LocationTests.cs +++ b/test/Lsp.Tests/Models/LocationTests.cs @@ -5,7 +5,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using TestingUtils; using Xunit; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace Lsp.Tests.Models { diff --git a/test/Lsp.Tests/Models/MessageTypeTests.cs b/test/Lsp.Tests/Models/MessageTypeTests.cs index 48f71fe72..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 @@ -19,7 +18,7 @@ public void SimpleTest(string expected) result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x.UsingStructuralRecordEquality()); + deresult.Should().Be(model); } } } diff --git a/test/Lsp.Tests/Models/PublishDiagnosticsParamsTests.cs b/test/Lsp.Tests/Models/PublishDiagnosticsParamsTests.cs index 8a5ae567b..c5e9e6bcd 100644 --- a/test/Lsp.Tests/Models/PublishDiagnosticsParamsTests.cs +++ b/test/Lsp.Tests/Models/PublishDiagnosticsParamsTests.cs @@ -5,7 +5,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using TestingUtils; using Xunit; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace Lsp.Tests.Models { diff --git a/test/Lsp.Tests/Models/SymbolKindTests.cs b/test/Lsp.Tests/Models/SymbolKindTests.cs index 03324b193..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 @@ -19,7 +18,7 @@ public void SimpleTest(string expected) result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x.UsingStructuralRecordEquality()); + deresult.Should().Be(model); } } } diff --git a/test/Lsp.Tests/Models/TextDocumentEditTests.cs b/test/Lsp.Tests/Models/TextDocumentEditTests.cs index 9ee46bca0..9489f32ee 100644 --- a/test/Lsp.Tests/Models/TextDocumentEditTests.cs +++ b/test/Lsp.Tests/Models/TextDocumentEditTests.cs @@ -5,7 +5,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using TestingUtils; using Xunit; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace Lsp.Tests.Models { diff --git a/test/Lsp.Tests/Models/TextDocumentSaveReasonTests.cs b/test/Lsp.Tests/Models/TextDocumentSaveReasonTests.cs index 1bf797457..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 @@ -19,7 +18,7 @@ public void SimpleTest(string expected) result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x.UsingStructuralRecordEquality()); + deresult.Should().Be(model); } } } diff --git a/test/Lsp.Tests/Models/WorkspaceEditTests.cs b/test/Lsp.Tests/Models/WorkspaceEditTests.cs index 75334924d..964dd1561 100644 --- a/test/Lsp.Tests/Models/WorkspaceEditTests.cs +++ b/test/Lsp.Tests/Models/WorkspaceEditTests.cs @@ -7,7 +7,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using TestingUtils; using Xunit; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace Lsp.Tests.Models { diff --git a/test/Lsp.Tests/Models/WorkspaceSymbolInformationTests.cs b/test/Lsp.Tests/Models/WorkspaceSymbolInformationTests.cs index 24780de5f..a5105a878 100644 --- a/test/Lsp.Tests/Models/WorkspaceSymbolInformationTests.cs +++ b/test/Lsp.Tests/Models/WorkspaceSymbolInformationTests.cs @@ -5,7 +5,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using TestingUtils; using Xunit; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; + namespace Lsp.Tests.Models { diff --git a/test/Lsp.Tests/SemanticTokensDocumentTests.cs b/test/Lsp.Tests/SemanticTokensDocumentTests.cs index 0e780a36f..41752c565 100644 --- a/test/Lsp.Tests/SemanticTokensDocumentTests.cs +++ b/test/Lsp.Tests/SemanticTokensDocumentTests.cs @@ -4,16 +4,14 @@ 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; + #pragma warning disable 618 @@ -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/Lsp.Tests/Usings.global.cs b/test/Lsp.Tests/Usings.global.cs new file mode 100644 index 000000000..1f6c6a094 --- /dev/null +++ b/test/Lsp.Tests/Usings.global.cs @@ -0,0 +1 @@ +global using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; diff --git a/test/TestingUtils/AutoNSubstitute/DryIocExtensions.cs b/test/TestingUtils/AutoNSubstitute/DryIocExtensions.cs index d2ca14963..975f1aee3 100644 --- a/test/TestingUtils/AutoNSubstitute/DryIocExtensions.cs +++ b/test/TestingUtils/AutoNSubstitute/DryIocExtensions.cs @@ -35,7 +35,7 @@ internal static Rules WithTestLoggerResolver(this Rules rules, Func).MakeGenericType( request.ServiceType.GetGenericArguments()[0] ); - instance = new DelegateFactory(_ => creator(request, loggerType), Reuse.Singleton); + instance = DelegateFactory.Of(_ => creator(request, loggerType), Reuse.Singleton); dictionary.TryAdd(serviceType, instance); } @@ -66,7 +66,7 @@ internal static Rules WithUndefinedTestDependenciesResolver(this Rules rules, Fu if (!dictionary.TryGetValue(serviceType, out var instance)) { - instance = new DelegateFactory(_ => creator(request), Reuse.Singleton); + instance = DelegateFactory.Of(_ => creator(request), Reuse.Singleton); dictionary.TryAdd(serviceType, instance); } diff --git a/test/TestingUtils/AutoNSubstitute/TestLogger.cs b/test/TestingUtils/AutoNSubstitute/TestLogger.cs index bf9a8f3dc..cb777ed61 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; @@ -17,7 +16,7 @@ public TestLogger(IEnumerable loggers) _loggers = loggers; } - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { foreach (var logger in _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/AutoNSubstitute/TraceWriter.cs b/test/TestingUtils/AutoNSubstitute/TraceWriter.cs index fda504366..8eb873e54 100644 --- a/test/TestingUtils/AutoNSubstitute/TraceWriter.cs +++ b/test/TestingUtils/AutoNSubstitute/TraceWriter.cs @@ -1,11 +1,10 @@ using System; -using FluentAssertions.Equivalency; using Microsoft.Extensions.Logging; // ReSharper disable once CheckNamespace namespace NSubstitute { - public class TraceWriter : ITraceWriter + public class TraceWriter : FluentAssertions.Equivalency.Tracing.ITraceWriter { private readonly ILogger _logger; 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/RecordStructuralEqualityEquivalencyStep.cs b/test/TestingUtils/RecordStructuralEqualityEquivalencyStep.cs index 58df13de0..c874e8499 100644 --- a/test/TestingUtils/RecordStructuralEqualityEquivalencyStep.cs +++ b/test/TestingUtils/RecordStructuralEqualityEquivalencyStep.cs @@ -1,15 +1,13 @@ using FluentAssertions.Equivalency; +using FluentAssertions.Equivalency.Steps; namespace TestingUtils { public class RecordStructuralEqualityEquivalencyStep : StructuralEqualityEquivalencyStep, IEquivalencyStep { - bool IEquivalencyStep.CanHandle( - IEquivalencyValidationContext context, - IEquivalencyAssertionOptions config - ) + EquivalencyResult IEquivalencyStep.Handle(Comparands comparands, IEquivalencyValidationContext context, IEquivalencyValidator nestedValidator) { - return context?.Subject?.GetType()?.GetMethod("$") != null; + return comparands.Subject?.GetType()?.GetMethod("$") != null ? EquivalencyResult.AssertionCompleted : EquivalencyResult.ContinueWithNext; } } } 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 + ) + { + } } } diff --git a/test/TestingUtils/TestingUtils.csproj b/test/TestingUtils/TestingUtils.csproj index 60d9e1d41..5f9c8393f 100644 --- a/test/TestingUtils/TestingUtils.csproj +++ b/test/TestingUtils/TestingUtils.csproj @@ -1,7 +1,7 @@ - netstandard2.0;netstandard2.1 + netstandard2.0;netstandard2.1;net6.0 false diff --git a/vscode-testextension/package-lock.json b/vscode-testextension/package-lock.json index deefca770..a3b636974 100644 --- a/vscode-testextension/package-lock.json +++ b/vscode-testextension/package-lock.json @@ -309,9 +309,9 @@ } }, "typescript": { - "version": "3.9.7", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.7.tgz", - "integrity": "sha512-BLbiRkiBzAwsjut4x/dsibSTB6yWpwT5qWmC2OfuCg3GgVQCSgMs4vEctYPhsaGtd0AeuuHMkjZ2h2WG8MSzRw==", + "version": "3.9.10", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.10.tgz", + "integrity": "sha512-w6fIxVE/H1PkLKcCPsFqKE7Kv7QUwhU8qQY2MueZXWx5cPZdwFupLgKK3vntcK98BtNHZtAF4LA/yl2a7k8R6Q==", "dev": true }, "vscode": { diff --git a/vscode-testextension/package.json b/vscode-testextension/package.json index 7b4f7f137..fb7291b4a 100644 --- a/vscode-testextension/package.json +++ b/vscode-testextension/package.json @@ -46,10 +46,10 @@ "postinstall": "node ./node_modules/vscode/bin/install" }, "devDependencies": { - "@types/mocha": "^8.0.0", - "@types/node": "^14.0.25", - "typescript": "^3.9.7", - "vscode": "^1.1.37" + "@types/mocha": "8.0.0", + "@types/node": "14.0.25", + "typescript": "3.9.10", + "vscode": "1.1.37" }, "dependencies": { "vscode-languageclient": "^7.0.0-next.8",