From 6cb3bb538535645255f98491965180d6f5b99924 Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Mon, 10 Aug 2020 17:28:11 -0400 Subject: [PATCH 1/7] Updated lps settings --- LSP.sln.DotSettings | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/LSP.sln.DotSettings b/LSP.sln.DotSettings index e7615b0a9..45f32eede 100644 --- a/LSP.sln.DotSettings +++ b/LSP.sln.DotSettings @@ -2,8 +2,20 @@ True WARNING WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + SUGGESTION True - <?xml version="1.0" encoding="utf-16"?><Profile name="Full Cleanup"><CSCodeStyleAttributes ArrangeTypeAccessModifier="True" ArrangeTypeMemberAccessModifier="True" SortModifiers="True" RemoveRedundantParentheses="True" AddMissingParentheses="True" ArrangeBraces="True" ArrangeAttributes="True" ArrangeArgumentsStyle="True" ArrangeCodeBodyStyle="True" ArrangeVarStyle="True" /><RemoveCodeRedundancies>True</RemoveCodeRedundancies><CSUseAutoProperty>True</CSUseAutoProperty><CSMakeFieldReadonly>True</CSMakeFieldReadonly><CSMakeAutoPropertyGetOnly>True</CSMakeAutoPropertyGetOnly><CSArrangeQualifiers>True</CSArrangeQualifiers><CSFixBuiltinTypeReferences>True</CSFixBuiltinTypeReferences><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings><EmbraceInRegion>True</EmbraceInRegion><RegionName></RegionName></CSOptimizeUsings><CSShortenReferences>True</CSShortenReferences><CSReformatCode>True</CSReformatCode><CSharpFormatDocComments>True</CSharpFormatDocComments><XAMLCollapseEmptyTags>False</XAMLCollapseEmptyTags><IDEA_SETTINGS>&lt;profile version="1.0"&gt; + <?xml version="1.0" encoding="utf-16"?><Profile name="Full Cleanup"><CSCodeStyleAttributes ArrangeTypeAccessModifier="True" ArrangeTypeMemberAccessModifier="True" SortModifiers="True" RemoveRedundantParentheses="True" AddMissingParentheses="True" ArrangeBraces="False" ArrangeAttributes="True" ArrangeArgumentsStyle="True" ArrangeCodeBodyStyle="True" ArrangeVarStyle="True" ArrangeTrailingCommas="False" /><RemoveCodeRedundancies>True</RemoveCodeRedundancies><CSUseAutoProperty>True</CSUseAutoProperty><CSMakeFieldReadonly>True</CSMakeFieldReadonly><CSMakeAutoPropertyGetOnly>True</CSMakeAutoPropertyGetOnly><CSArrangeQualifiers>True</CSArrangeQualifiers><CSFixBuiltinTypeReferences>True</CSFixBuiltinTypeReferences><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings><EmbraceInRegion>False</EmbraceInRegion><RegionName></RegionName></CSOptimizeUsings><CSShortenReferences>True</CSShortenReferences><CSReformatCode>True</CSReformatCode><CSharpFormatDocComments>True</CSharpFormatDocComments><XAMLCollapseEmptyTags>False</XAMLCollapseEmptyTags><IDEA_SETTINGS>&lt;profile version="1.0"&gt; &lt;option name="myName" value="Full Cleanup" /&gt; &lt;inspection_tool class="ES6ShorthandObjectProperty" enabled="false" level="INFORMATION" enabled_by_default="false" /&gt; &lt;inspection_tool class="JSArrowFunctionBracesCanBeRemoved" enabled="false" level="INFORMATION" enabled_by_default="false" /&gt; From 765efadd774df0f12cee449dfac0ba5d3e94da15 Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Mon, 10 Aug 2020 20:02:55 -0400 Subject: [PATCH 2/7] updated editor config --- .config/dotnet-tools.json | 82 ++++++++---------- .editorconfig | 173 +++++++++++++++++++++++++++++--------- LSP.sln.DotSettings | 38 +++++++++ 3 files changed, 208 insertions(+), 85 deletions(-) diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 765622af4..33ec38808 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -1,48 +1,38 @@ { - "version": 1, - "isRoot": true, - "tools": { - "cake.tool": { - "version": "0.35.0", - "commands": [ - "dotnet-cake" - ] - }, - "gitversion.tool": { - "version": "5.2.4", - "commands": [ - "dotnet-gitversion" - ] - }, - "dotnet-reportgenerator-globaltool": { - "version": "4.3.0", - "commands": [ - "reportgenerator" - ] - }, - "codecov.tool": { - "version": "1.10.0", - "commands": [ - "codecov" - ] - }, - "gitreleasemanager.tool": { - "version": "0.11.0", - "commands": [ - "dotnet-gitreleasemanager" - ] - }, - "nuke.globaltool": { - "version": "0.24.4", - "commands": [ - "nuke" - ] - }, - "nukeeper": { - "version": "0.26.1", - "commands": [ - "nukeeper" - ] + "version": 1, + "isRoot": true, + "tools": { + "cake.tool": { + "version": "0.35.0", + "commands": ["dotnet-cake"] + }, + "gitversion.tool": { + "version": "5.2.4", + "commands": ["dotnet-gitversion"] + }, + "dotnet-reportgenerator-globaltool": { + "version": "4.3.0", + "commands": ["reportgenerator"] + }, + "codecov.tool": { + "version": "1.10.0", + "commands": ["codecov"] + }, + "gitreleasemanager.tool": { + "version": "0.11.0", + "commands": ["dotnet-gitreleasemanager"] + }, + "nuke.globaltool": { + "version": "0.24.4", + "commands": ["nuke"] + }, + "nukeeper": { + "version": "0.26.1", + "commands": ["nukeeper"] + }, + "jetbrains.resharper.globaltools": { + "version": "2020.2.0-eap09", + "commands": ["jb"] + } } - } -} \ No newline at end of file +} diff --git a/.editorconfig b/.editorconfig index 6c1295052..63f5f80c8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,4 +1,12 @@ root=true +[*] +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 [*.{cs,cshtml}] charset=utf-8 @@ -17,33 +25,120 @@ indent_size=2 insert_final_newline=true [*.{xml,csproj,props,targets}] -indent_style = space +indent_style=space -[*] -charset = utf-8 -indent_style = space -indent_size = 4 -trim_trailing_whitespace = true -insert_final_newline = true -max_line_length = 180 +[{*.har,*.inputactions,*.jsb2,*.jsb3,*.json,.babelrc,.eslintrc,.prettierrc,.stylelintrc,bowerrc,jest.config}] +indent_style=space +indent_size=2 + +[{*.yaml,*.yml}] +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 + +# Microsoft .NET properties +csharp_new_line_before_members_in_object_initializers=false +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_var_elsewhere=true:suggestion +csharp_style_var_for_built_in_types=true:suggestion +csharp_style_var_when_type_is_apparent=true:suggestion +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:suggestion +dotnet_style_predefined_type_for_member_access=true:suggestion +dotnet_style_qualification_for_event=false:suggestion +dotnet_style_qualification_for_field=false:suggestion +dotnet_style_qualification_for_method=false:suggestion +dotnet_style_qualification_for_property=false:suggestion +dotnet_style_require_accessibility_modifiers=for_non_interface_members:suggestion + +# ReSharper properties +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_csharp_outdent_commas=true +resharper_csharp_outdent_dots=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_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_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_indent_from_vs=false +resharper_wrap_lines=true +resharper_xmldoc_attribute_style=on_single_line +resharper_xmldoc_pi_attribute_style=on_single_line +resharper_xmldoc_space_after_last_pi_attribute=true + +# ReSharper inspection severities +resharper_annotate_can_be_null_parameter_highlighting=warning +resharper_annotate_can_be_null_type_member_highlighting=warning +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 [*.{cs,vb}] # Sort using and Import directives with System.* appearing first -dotnet_sort_system_directives_first = true +dotnet_sort_system_directives_first=true # Avoid "this." and "Me." if not necessary -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_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 # Use language keywords instead of framework type names for type references -dotnet_style_predefined_type_for_locals_parameters_members = true:error -dotnet_style_predefined_type_for_member_access = true:error +dotnet_style_predefined_type_for_locals_parameters_members=true:error +dotnet_style_predefined_type_for_member_access=true:error # 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 +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 @@ -52,22 +147,22 @@ dotnet_style_object_initializer = true:warning #dotnet_naming_style.pascal_case_style.capitalization = pascal_case [*.cs] -csharp_style_conditional_delegate_call = true:suggestion -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_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_style_var_elsewhere = true:warning -csharp_style_var_for_built_in_types = true:warning -csharp_style_var_when_type_is_apparent = true:error -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_open_brace = types,methods,properties,indexers,events,event_accessors,control_blocks,anonymous_types,object_collections,array_initializers,local_functions +csharp_style_conditional_delegate_call=true:suggestion +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_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_style_var_elsewhere=true:warning +csharp_style_var_for_built_in_types=true:warning +csharp_style_var_when_type_is_apparent=true:error +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_open_brace=types,methods,properties,indexers,events,event_accessors,control_blocks,anonymous_types,object_collections,array_initializers,local_functions diff --git a/LSP.sln.DotSettings b/LSP.sln.DotSettings index 45f32eede..5f6d29ea7 100644 --- a/LSP.sln.DotSettings +++ b/LSP.sln.DotSettings @@ -31,6 +31,40 @@ &lt;inspection_tool class="WrongPropertyKeyValueDelimiter" enabled="false" level="WEAK WARNING" enabled_by_default="false" /&gt; &lt;/profile&gt;</IDEA_SETTINGS><XMLReformatCode>True</XMLReformatCode></Profile> Full Cleanup + True + True + True + True + True + True + True + True + True + True + True + True + True + False + 2 + True + True + True + True + True + True + True + True + True + True + True + True + True + True + ZeroIndent + 1 + OnSingleLine + True + OnSingleLine <?xml version="1.0" encoding="utf-16"?> <Patterns xmlns="urn:schemas-jetbrains-com:member-reordering-patterns"> <TypePattern DisplayName="Non-reorderable types"> @@ -204,6 +238,10 @@ </Entry> </TypePattern> </Patterns> + True + True + True True + True From 2ef887b17a25f411a3dddebccdba0a1e8bf5cd95 Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Mon, 10 Aug 2020 23:29:15 -0400 Subject: [PATCH 3/7] ran code cleanup to get files in sync with the general rules --- .build/Build.cs | 47 +- .build/Configuration.cs | 2 +- .build/Solution.cs | 116 +-- Directory.Build.props | 3 +- Directory.Build.targets | 1 + NuGet.config | 7 +- benchmarks/Pipeline/Class1.cs | 10 +- benchmarks/Pipeline/ClassicHandler.cs | 14 +- benchmarks/Pipeline/PipelinesBased.cs | 23 +- .../DidChangeWatchedFilesHandler.cs | 17 +- sample/SampleServer/FoldingRangeHandler.cs | 40 +- sample/SampleServer/Program.cs | 234 ++--- sample/SampleServer/SemanticTokensHandler.cs | 47 +- sample/SampleServer/TextDocumentHandler.cs | 209 +++-- src/Client/LangaugeClientRegistry.cs | 5 +- src/Client/LanguageClient.cs | 56 +- src/Client/LanguageClientOptions.cs | 99 +- src/Client/LanguageClientOptionsExtensions.cs | 36 +- .../LanguageClientRegistrationManager.cs | 52 +- src/Client/LanguageClientResolver.cs | 2 +- ...nguageClientServiceCollectionExtensions.cs | 58 +- .../LanguageClientWorkspaceFoldersManager.cs | 60 +- src/Client/LspClientReceiver.cs | 13 +- src/Dap.Client/DebugAdapterClient.cs | 28 +- src/Dap.Client/DebugAdapterClientOptions.cs | 98 +- .../DebugAdapterClientOptionsExtensions.cs | 15 +- .../DebugAdapterClientProgressManager.cs | 6 +- src/Dap.Client/DebugAdapterClientResolver.cs | 2 +- ...dapterClientServiceCollectionExtensions.cs | 68 +- src/Dap.Client/ProgressObservable.cs | 16 +- .../Client/IDebugAdapterClient.cs | 2 - .../Client/IOnDebugAdapterClientInitialize.cs | 2 +- .../IOnDebugAdapterClientInitialized.cs | 2 +- .../Client/IOnDebugAdapterClientStarted.cs | 2 +- .../OnDebugAdapterClientInitializeDelegate.cs | 2 +- ...OnDebugAdapterClientInitializedDelegate.cs | 6 +- .../OnDebugAdapterClientStartedDelegate.cs | 2 +- src/Dap.Protocol/DapReceiver.cs | 24 +- .../DapClientNotificationConverter.cs | 16 +- .../DapClientRequestConverter.cs | 12 +- .../DapClientResponseConverter.cs | 17 +- .../DapRpcErrorConverter.cs | 8 +- .../DebugAdapterRpcOptionsBase.cs | 5 +- src/Dap.Protocol/DebugAdapterSettingsBag.cs | 2 +- src/Dap.Protocol/Events/BreakpointEvent.cs | 4 +- .../Events/BreakpointExtensions.cs | 11 +- src/Dap.Protocol/Events/CapabilitiesEvent.cs | 4 +- .../Events/CapabilitiesExtensions.cs | 6 +- src/Dap.Protocol/Events/ContinuedEvent.cs | 5 +- .../Events/ContinuedExtensions.cs | 11 +- src/Dap.Protocol/Events/ExitedEvent.cs | 1 - src/Dap.Protocol/Events/ExitedExtensions.cs | 11 +- .../Events/IProgressEndHandler.cs | 6 +- .../Events/IProgressStartHandler.cs | 6 +- .../Events/IProgressUpdateHandler.cs | 6 +- .../Events/InitializedExtensions.cs | 11 +- src/Dap.Protocol/Events/LoadedSourceEvent.cs | 3 +- .../Events/LoadedSourceExtensions.cs | 11 +- src/Dap.Protocol/Events/ModuleEvent.cs | 4 +- src/Dap.Protocol/Events/ModuleEventReason.cs | 1 - src/Dap.Protocol/Events/ModuleExtensions.cs | 11 +- src/Dap.Protocol/Events/OutputEvent.cs | 21 +- src/Dap.Protocol/Events/OutputExtensions.cs | 10 +- src/Dap.Protocol/Events/ProcessEvent.cs | 16 +- .../Events/ProcessEventStartMethod.cs | 1 - src/Dap.Protocol/Events/ProcessExtensions.cs | 11 +- src/Dap.Protocol/Events/ProgressEndEvent.cs | 2 - src/Dap.Protocol/Events/ProgressEvent.cs | 4 +- .../Events/ProgressUpdateEvent.cs | 3 +- src/Dap.Protocol/Events/StoppedEvent.cs | 20 +- src/Dap.Protocol/Events/StoppedExtensions.cs | 11 +- src/Dap.Protocol/Events/TerminatedEvent.cs | 5 +- .../Events/TerminatedExtensions.cs | 11 +- src/Dap.Protocol/Events/ThreadEvent.cs | 1 - src/Dap.Protocol/Events/ThreadExtensions.cs | 11 +- src/Dap.Protocol/IProgressObservable.cs | 2 +- src/Dap.Protocol/IProgressObserver.cs | 2 +- src/Dap.Protocol/Models/Breakpoint.cs | 27 +- src/Dap.Protocol/Models/Capabilities.cs | 108 ++- src/Dap.Protocol/Models/Checksum.cs | 3 +- src/Dap.Protocol/Models/ChecksumAlgorithm.cs | 2 +- src/Dap.Protocol/Models/ColumnDescriptor.cs | 10 +- .../Models/ColumnDescriptorType.cs | 2 +- src/Dap.Protocol/Models/CompletionItem.cs | 18 +- src/Dap.Protocol/Models/CompletionItemType.cs | 2 +- src/Dap.Protocol/Models/Container.cs | 15 +- src/Dap.Protocol/Models/ContainerBase.cs | 57 +- src/Dap.Protocol/Models/DataBreakpoint.cs | 9 +- .../Models/DataBreakpointAccessType.cs | 2 +- .../Models/DisassembledInstruction.cs | 27 +- src/Dap.Protocol/Models/ExceptionBreakMode.cs | 2 +- .../Models/ExceptionBreakpointsFilter.cs | 8 +- src/Dap.Protocol/Models/ExceptionDetails.cs | 21 +- src/Dap.Protocol/Models/ExceptionOptions.cs | 9 +- .../Models/ExceptionPathSegment.cs | 6 +- src/Dap.Protocol/Models/FunctionBreakpoint.cs | 11 +- src/Dap.Protocol/Models/GotoTarget.cs | 12 +- .../Models/InstructionBreakpoint.cs | 12 +- src/Dap.Protocol/Models/Message.cs | 17 +- src/Dap.Protocol/Models/Module.cs | 28 +- src/Dap.Protocol/Models/NumberString.cs | 19 +- src/Dap.Protocol/Models/ProgressToken.cs | 45 +- src/Dap.Protocol/Models/Scope.cs | 24 +- src/Dap.Protocol/Models/Source.cs | 30 +- src/Dap.Protocol/Models/SourceBreakpoint.cs | 15 +- .../Models/SourcePresentationHint.cs | 2 +- src/Dap.Protocol/Models/StackFrame.cs | 24 +- src/Dap.Protocol/Models/StackFrameFormat.cs | 23 +- .../Models/StackFramePresentationHint.cs | 2 +- src/Dap.Protocol/Models/StepInTarget.cs | 2 +- .../Models/SteppingGranularity.cs | 6 +- src/Dap.Protocol/Models/Thread.cs | 2 +- src/Dap.Protocol/Models/ValueFormat.cs | 5 +- src/Dap.Protocol/Models/Variable.cs | 20 +- .../Models/VariablePresentationHint.cs | 12 +- .../Requests/AttachRequestArguments.cs | 8 +- src/Dap.Protocol/Requests/AttachResponse.cs | 1 - .../Requests/BreakpointLocationsArguments.cs | 5 +- .../Requests/BreakpointLocationsResponse.cs | 5 +- .../Requests/CompletionsArguments.cs | 9 +- .../Requests/CompletionsResponse.cs | 1 - .../Requests/ConfigurationDoneArguments.cs | 1 - .../Requests/ConfigurationDoneResponse.cs | 1 - .../Requests/ContinueArguments.cs | 5 +- src/Dap.Protocol/Requests/ContinueResponse.cs | 7 +- .../Requests/DataBreakpointInfoArguments.cs | 6 +- .../Requests/DataBreakpointInfoResponse.cs | 7 +- .../Requests/DisassembleArguments.cs | 15 +- .../Requests/DisassembleResponse.cs | 1 - .../Requests/DisconnectArguments.cs | 9 +- .../Requests/DisconnectResponse.cs | 1 - .../Requests/EvaluateArguments.cs | 12 +- src/Dap.Protocol/Requests/EvaluateResponse.cs | 16 +- .../Requests/ExceptionInfoResponse.cs | 7 +- src/Dap.Protocol/Requests/GotoArguments.cs | 1 - src/Dap.Protocol/Requests/GotoResponse.cs | 1 - .../Requests/GotoTargetsArguments.cs | 6 +- .../Requests/GotoTargetsResponse.cs | 1 - src/Dap.Protocol/Requests/IAttachHandler.cs | 6 +- .../Requests/IBreakpointLocationsHandler.cs | 6 +- src/Dap.Protocol/Requests/ICancelHandler.cs | 6 +- .../Requests/ICompletionsHandler.cs | 10 +- .../Requests/IConfigurationDoneHandler.cs | 12 +- src/Dap.Protocol/Requests/IContinueHandler.cs | 6 +- .../Requests/IDataBreakpointInfoHandler.cs | 13 +- .../IDebugAdapterInitializeHandler.cs | 13 +- .../Requests/IDisassembleHandler.cs | 12 +- .../Requests/IDisconnectHandler.cs | 12 +- src/Dap.Protocol/Requests/IEvaluateHandler.cs | 6 +- .../Requests/IExceptionInfoHandler.cs | 12 +- src/Dap.Protocol/Requests/IGotoHandler.cs | 6 +- .../Requests/IGotoTargetsHandler.cs | 12 +- src/Dap.Protocol/Requests/ILaunchHandler.cs | 6 +- .../Requests/ILoadedSourcesHandler.cs | 12 +- src/Dap.Protocol/Requests/IModulesHandler.cs | 6 +- src/Dap.Protocol/Requests/INextHandler.cs | 6 +- src/Dap.Protocol/Requests/IPauseHandler.cs | 6 +- .../Requests/IReadMemoryHandler.cs | 12 +- .../Requests/IRestartFrameHandler.cs | 13 +- src/Dap.Protocol/Requests/IRestartHandler.cs | 6 +- .../Requests/IReverseContinueHandler.cs | 12 +- .../Requests/IRunInTerminalHandler.cs | 6 +- src/Dap.Protocol/Requests/IScopesHandler.cs | 6 +- .../Requests/ISetBreakpointsHandler.cs | 12 +- .../Requests/ISetDataBreakpointsHandler.cs | 12 +- .../ISetExceptionBreakpointsHandler.cs | 12 +- .../Requests/ISetExpressionHandler.cs | 12 +- .../ISetFunctionBreakpointsHandler.cs | 12 +- .../ISetInstructionBreakpointsHandler.cs | 6 +- .../Requests/ISetVariableHandler.cs | 12 +- src/Dap.Protocol/Requests/ISourceHandler.cs | 6 +- .../Requests/IStackTraceHandler.cs | 12 +- src/Dap.Protocol/Requests/IStepBackHandler.cs | 6 +- src/Dap.Protocol/Requests/IStepInHandler.cs | 6 +- .../Requests/IStepInTargetsHandler.cs | 12 +- src/Dap.Protocol/Requests/IStepOutHandler.cs | 6 +- .../Requests/ITerminateHandler.cs | 6 +- .../Requests/ITerminateThreadsHandler.cs | 12 +- src/Dap.Protocol/Requests/IThreadsHandler.cs | 6 +- .../Requests/IVariablesHandler.cs | 7 +- .../Requests/InitializeRequestArguments.cs | 36 +- .../Requests/InitializeResponse.cs | 4 +- .../Requests/LaunchRequestArguments.cs | 7 +- src/Dap.Protocol/Requests/LaunchResponse.cs | 1 - .../Requests/LoadedSourcesArguments.cs | 1 - .../Requests/LoadedSourcesResponse.cs | 1 - src/Dap.Protocol/Requests/ModulesArguments.cs | 9 +- src/Dap.Protocol/Requests/ModulesResponse.cs | 4 +- src/Dap.Protocol/Requests/NextResponse.cs | 1 - src/Dap.Protocol/Requests/PauseArguments.cs | 1 - src/Dap.Protocol/Requests/PauseResponse.cs | 1 - .../Requests/ReadMemoryArguments.cs | 6 +- .../Requests/ReadMemoryResponse.cs | 10 +- src/Dap.Protocol/Requests/RequestNames.cs | 1 - src/Dap.Protocol/Requests/RestartArguments.cs | 1 - .../Requests/RestartFrameArguments.cs | 1 - .../Requests/RestartFrameResponse.cs | 1 - src/Dap.Protocol/Requests/RestartResponse.cs | 1 - .../Requests/ReverseContinueArguments.cs | 1 - .../Requests/ReverseContinueResponse.cs | 1 - .../Requests/RunInTerminalArguments.cs | 12 +- .../Requests/RunInTerminalArgumentsKind.cs | 1 - .../Requests/RunInTerminalResponse.cs | 7 +- src/Dap.Protocol/Requests/ScopesArguments.cs | 1 - src/Dap.Protocol/Requests/ScopesResponse.cs | 1 - .../Requests/SetBreakpointsArguments.cs | 12 +- .../Requests/SetBreakpointsResponse.cs | 1 - .../Requests/SetDataBreakpointsArguments.cs | 2 +- .../SetExceptionBreakpointsArguments.cs | 6 +- .../SetExceptionBreakpointsResponse.cs | 1 - .../Requests/SetExpressionArguments.cs | 9 +- .../Requests/SetExpressionResponse.cs | 16 +- .../SetFunctionBreakpointsArguments.cs | 3 +- .../SetFunctionBreakpointsResponse.cs | 1 - .../Requests/SetVariableArguments.cs | 6 +- .../Requests/SetVariableResponse.cs | 13 +- src/Dap.Protocol/Requests/SourceArguments.cs | 6 +- src/Dap.Protocol/Requests/SourceResponse.cs | 4 +- .../Requests/StackTraceArguments.cs | 12 +- .../Requests/StackTraceResponse.cs | 5 +- .../Requests/StepBackArguments.cs | 1 - src/Dap.Protocol/Requests/StepBackResponse.cs | 1 - src/Dap.Protocol/Requests/StepInArguments.cs | 6 +- src/Dap.Protocol/Requests/StepInResponse.cs | 1 - .../Requests/StepInTargetsArguments.cs | 1 - .../Requests/StepInTargetsResponse.cs | 1 - src/Dap.Protocol/Requests/StepOutArguments.cs | 1 - src/Dap.Protocol/Requests/StepOutResponse.cs | 1 - .../Requests/TerminateArguments.cs | 5 +- .../Requests/TerminateResponse.cs | 1 - .../Requests/TerminateThreadsArguments.cs | 6 +- .../Requests/TerminateThreadsResponse.cs | 1 - src/Dap.Protocol/Requests/ThreadsArguments.cs | 1 - src/Dap.Protocol/Requests/ThreadsResponse.cs | 1 - .../Requests/VariablesArguments.cs | 15 +- .../Requests/VariablesArgumentsFilter.cs | 1 - .../Requests/VariablesResponse.cs | 1 - .../Serialization/ContractResolver.cs | 7 +- src/Dap.Protocol/Serialization/ISerializer.cs | 4 +- .../Serialization/NumberStringConverter.cs | 6 +- .../Serialization/OptionalAttribute.cs | 4 +- .../Server/IDebugAdapterServer.cs | 2 - .../Server/IOnDebugAdapterServerInitialize.cs | 2 +- .../IOnDebugAdapterServerInitialized.cs | 2 +- .../Server/IOnDebugAdapterServerStarted.cs | 2 +- .../OnDebugAdapterServerInitializeDelegate.cs | 2 +- ...OnDebugAdapterServerInitializedDelegate.cs | 6 +- .../OnDebugAdapterServerStartedDelegate.cs | 2 +- src/Dap.Server/DebugAdapterServer.cs | 19 +- src/Dap.Server/DebugAdapterServerOptions.cs | 119 ++- .../DebugAdapterServerOptionsExtensions.cs | 1 - .../DebugAdapterServerProgressManager.cs | 2 +- src/Dap.Server/DebugAdapterServerResolver.cs | 2 +- ...dapterServerServiceCollectionExtensions.cs | 36 +- src/Dap.Server/ProgressObserver.cs | 38 +- src/Dap.Shared/DapResponseRouter.cs | 80 +- src/Dap.Shared/DebugAdapterEventingHelper.cs | 14 +- .../DebugAdapterHandlerCollection.cs | 86 +- ...pterProtocolServiceCollectionExtensions.cs | 14 +- src/Dap.Shared/DebugAdapterRequestRouter.cs | 30 +- src/Dap.Shared/HandlerDescriptor.cs | 26 +- .../DebugAdapterProtocolTestBase.cs | 78 +- src/Dap.Testing/DebugAdapterServerTestBase.cs | 33 +- .../GenerateHandlerMethodsGenerator.cs | 344 ++++--- .../GenerateRequestMethodsGenerator.cs | 301 +++--- .../GeneratorDiagnostics.cs | 20 +- src/JsonRpc.Generators/Helpers.cs | 614 +++++++----- src/JsonRpc.Testing/AggregateSettler.cs | 29 +- .../JsonRpcIntegrationServerTestBase.cs | 2 +- src/JsonRpc.Testing/JsonRpcServerTestBase.cs | 75 +- src/JsonRpc.Testing/JsonRpcTestBase.cs | 2 +- src/JsonRpc.Testing/JsonRpcTestOptions.cs | 9 +- .../JsonRpcTestOptionsExtensions.cs | 5 + src/JsonRpc.Testing/SettlePipeline.cs | 5 +- src/JsonRpc.Testing/Settler.cs | 64 +- src/JsonRpc/AggregateResponse.cs | 11 +- src/JsonRpc/CompositeHandlersManager.cs | 8 +- src/JsonRpc/Connection.cs | 8 +- src/JsonRpc/ContentModified.cs | 9 +- src/JsonRpc/CreateResponseExceptionHandler.cs | 2 +- src/JsonRpc/DelegatingHandlers.cs | 25 +- .../DelegatingJsonNotificationHandler.cs | 5 +- src/JsonRpc/DelegatingJsonRequestHandler.cs | 5 +- src/JsonRpc/DelegatingNotification.cs | 5 +- src/JsonRpc/DelegatingNotificationHandler.cs | 2 +- src/JsonRpc/DelegatingRequest.cs | 7 +- src/JsonRpc/EmptyRequest.cs | 5 +- src/JsonRpc/ErrorResponse.cs | 12 +- src/JsonRpc/Events.cs | 2 +- src/JsonRpc/ExternalServiceProvider.cs | 7 +- src/JsonRpc/HandlerCollection.cs | 49 +- src/JsonRpc/HandlerInstance.cs | 25 +- src/JsonRpc/HandlerTypeDescriptor.cs | 29 +- src/JsonRpc/HandlerTypeDescriptorHelper.cs | 89 +- src/JsonRpc/IExternalServiceProvider.cs | 6 +- src/JsonRpc/IHandlerTypeDescriptor.cs | 1 - src/JsonRpc/IJsonRpcHandler.cs | 8 +- src/JsonRpc/IJsonRpcHandlerCollection.cs | 2 +- src/JsonRpc/IJsonRpcHandlerInstance.cs | 2 +- src/JsonRpc/IJsonRpcHandlerRegistry.cs | 10 +- src/JsonRpc/IJsonRpcNotificationHandler.cs | 7 +- src/JsonRpc/IJsonRpcRequestHandler.cs | 18 +- src/JsonRpc/IJsonRpcServer.cs | 1 - src/JsonRpc/IJsonRpcServerOptions.cs | 2 - src/JsonRpc/IJsonRpcServerRegistry.cs | 2 +- src/JsonRpc/IOutputHandler.cs | 1 - src/JsonRpc/IRequestRouter.cs | 1 - src/JsonRpc/IResponseHandler.cs | 8 +- src/JsonRpc/InputHandler.cs | 257 ++--- src/JsonRpc/InputProcessingException.cs | 7 +- src/JsonRpc/InterimJsonRpcServerRegistry.cs | 16 +- src/JsonRpc/JsonRpcCancelRequestExtensions.cs | 19 +- src/JsonRpc/JsonRpcCommonMethodsBase.cs | 202 ++-- src/JsonRpc/JsonRpcHandlerCollection.cs | 2 +- .../JsonRpcHandlerCollectionExtensions.cs | 1 + src/JsonRpc/JsonRpcHandlerDescription.cs | 59 +- src/JsonRpc/JsonRpcHandlerFactory.cs | 2 +- .../JsonRpcHandlerFactoryDescription.cs | 4 +- .../JsonRpcHandlerInstanceDescription.cs | 4 +- src/JsonRpc/JsonRpcHandlerLinkDescription.cs | 2 +- .../JsonRpcHandlerRegistrationExtensions.cs | 26 +- src/JsonRpc/JsonRpcHandlerTypeDescription.cs | 4 +- src/JsonRpc/JsonRpcOptionsRegistryBase.cs | 15 +- src/JsonRpc/JsonRpcServer.cs | 26 +- src/JsonRpc/JsonRpcServerBase.cs | 39 +- src/JsonRpc/JsonRpcServerContainer.cs | 42 +- src/JsonRpc/JsonRpcServerOptions.cs | 8 - src/JsonRpc/JsonRpcServerOptionsBase.cs | 22 +- src/JsonRpc/JsonRpcServerOptionsExtensions.cs | 9 - src/JsonRpc/JsonRpcServerRegistry.cs | 6 +- src/JsonRpc/JsonRpcServerResolver.cs | 1 - ...sonRpcServerServiceCollectionExtensions.cs | 113 +-- src/JsonRpc/LinkedHandler.cs | 8 +- src/JsonRpc/MethodAttribute.cs | 24 +- src/JsonRpc/NoopResponseRouter.cs | 34 +- src/JsonRpc/NotificationHandler.cs | 24 +- src/JsonRpc/OnUnhandledExceptionHandler.cs | 2 +- src/JsonRpc/OutputHandler.cs | 27 +- src/JsonRpc/ParallelAttribute.cs | 4 +- .../ParallelRequestProcessIdentifier.cs | 5 +- .../RequestMustNotBeNullProcessor.cs | 3 +- .../ResponseMustNotBeNullProcessor.cs | 3 +- src/JsonRpc/ProcessAttribute.cs | 7 +- src/JsonRpc/ProcessScheduler.cs | 182 ++-- src/JsonRpc/Receiver.cs | 17 +- src/JsonRpc/RequestCancelled.cs | 9 +- src/JsonRpc/RequestContext.cs | 2 +- src/JsonRpc/RequestDescriptor.cs | 6 +- src/JsonRpc/RequestHandler.cs | 36 +- src/JsonRpc/RequestRouter.cs | 22 +- src/JsonRpc/RequestRouterBase.cs | 106 ++- src/JsonRpc/ResponseRouter.cs | 87 +- src/JsonRpc/RpcError.cs | 3 +- src/JsonRpc/SchedulerDelegate.cs | 2 +- src/JsonRpc/SerialAttribute.cs | 6 +- src/JsonRpc/SerialRequestProcessIdentifier.cs | 5 +- .../Converters/AggregateConverter.cs | 5 +- .../Converters/ClientNotificationConverter.cs | 10 +- .../Converters/ClientRequestConverter.cs | 10 +- .../Converters/ClientResponseConverter.cs | 13 +- .../Converters/ErrorMessageConverter.cs | 4 +- .../Converters/RpcErrorConverter.cs | 10 +- src/JsonRpc/Serialization/SerializerBase.cs | 27 +- .../Server/ContentModifiedException.cs | 34 +- src/JsonRpc/Server/ErrorCodes.cs | 22 +- src/JsonRpc/Server/IRequestException.cs | 4 +- src/JsonRpc/Server/InternalErrorException.cs | 12 +- .../Server/InvalidParametersException.cs | 12 +- src/JsonRpc/Server/InvalidRequestException.cs | 12 +- src/JsonRpc/Server/JsonRpcException.cs | 5 +- src/JsonRpc/Server/Messages/IErrorMessage.cs | 2 +- src/JsonRpc/Server/Messages/InternalError.cs | 14 +- src/JsonRpc/Server/Messages/InvalidParams.cs | 9 +- src/JsonRpc/Server/Messages/InvalidRequest.cs | 14 +- src/JsonRpc/Server/Messages/MethodNotFound.cs | 4 +- src/JsonRpc/Server/Messages/ParseError.cs | 9 +- .../Server/MethodNotSupportedException.cs | 30 +- src/JsonRpc/Server/Notification.cs | 3 +- src/JsonRpc/Server/ParseErrorException.cs | 14 +- src/JsonRpc/Server/Renor.cs | 25 +- src/JsonRpc/Server/Request.cs | 3 +- .../Server/RequestCancelledException.cs | 34 +- src/JsonRpc/Server/RequestException.cs | 40 +- src/JsonRpc/Server/ResponseBase.cs | 5 +- src/JsonRpc/Server/ServerError.cs | 10 +- src/JsonRpc/Server/ServerErrorResult.cs | 2 + .../Server/ServerNotInitializedException.cs | 12 +- src/JsonRpc/Server/ServerResponse.cs | 5 +- src/JsonRpc/Server/UnknownErrorException.cs | 12 +- src/JsonRpc/TimeLoggerExtensions.cs | 35 +- src/JsonRpc/ValueOptionsFactory.cs | 8 +- src/Protocol/AbstractHandlers.cs | 45 +- src/Protocol/CharCode.cs | 389 ++++---- .../Capabilities/CallHierarchyCapability.cs | 2 +- .../ClientCapabilitiesExtensions.cs | 6 +- .../Client/Capabilities/CodeLensCapability.cs | 4 +- .../Capabilities/ColorProviderCapability.cs | 4 +- .../Capabilities/CompletionCapability.cs | 2 +- .../Capabilities/ConnectedCapability.cs | 3 +- .../Capabilities/DeclarationCapability.cs | 4 +- .../Capabilities/DefinitionCapability.cs | 4 +- .../DidChangeConfigurationCapability.cs | 4 +- .../DidChangeWatchedFilesCapability.cs | 4 +- .../DocumentFormattingCapability.cs | 4 +- .../DocumentHighlightCapability.cs | 4 +- .../DocumentOnTypeFormattingCapability.cs | 4 +- .../DocumentRangeFormattingCapability.cs | 4 +- .../Capabilities/DocumentSymbolCapability.cs | 2 +- .../Client/Capabilities/DynamicCapability.cs | 3 +- .../Capabilities/ExecuteCommandCapability.cs | 4 +- .../Client/Capabilities/ICapability.cs | 1 - .../Capabilities/ImplementationCapability.cs | 4 +- .../Capabilities/LinkSupportCapability.cs | 3 +- .../PublishDiagnosticsCapability.cs | 2 +- .../Capabilities/ReferenceCapability.cs | 4 +- .../Capabilities/SemanticTokensCapability.cs | 2 +- .../SemanticTokensCapabilityRequestFull.cs | 2 +- .../SemanticTokensCapabilityRequestRange.cs | 2 +- .../SemanticTokensCapabilityRequests.cs | 1 - .../Capabilities/SynchronizationCapability.cs | 12 +- .../Capabilities/TypeDefinitionCapability.cs | 4 +- .../Capabilities/WorkspaceEditCapability.cs | 12 +- src/Protocol/Client/ClientLanguageClient.cs | 7 +- src/Protocol/Client/GeneralLanguageClient.cs | 7 +- src/Protocol/Client/IClientLanguageClient.cs | 6 +- src/Protocol/Client/IGeneralLanguageClient.cs | 8 +- src/Protocol/Client/ILanguageClient.cs | 1 - src/Protocol/Client/ILogTraceHandler.cs | 10 +- .../Client/IOnLanguageClientInitialize.cs | 2 +- .../Client/IOnLanguageClientInitialized.cs | 2 +- .../Client/IOnLanguageClientStarted.cs | 3 +- .../Client/IRegisterCapabilityHandler.cs | 6 +- .../Client/ITextDocumentLanguageClient.cs | 6 +- .../Client/IUnregisterCapabilityHandler.cs | 10 +- src/Protocol/Client/IWindowLanguageClient.cs | 2 - .../Client/IWorkspaceLanguageClient.cs | 6 +- .../OnLanguageClientInitializeDelegate.cs | 3 +- .../OnLanguageClientInitializedDelegate.cs | 3 +- .../Client/OnLanguageClientStartedDelegate.cs | 3 +- .../Client/TextDocumentLanguageClient.cs | 7 +- src/Protocol/Client/WindowLanguageClient.cs | 7 +- .../WorkDone/LanguageClientWorkDoneManager.cs | 35 +- .../WorkDone/WorkDoneProxyExtensions.cs | 43 +- .../Client/WorkspaceLanguageClient.cs | 7 +- src/Protocol/Document/ICodeActionHandler.cs | 19 +- src/Protocol/Document/ICodeLensHandler.cs | 428 +++++---- .../Document/IColorPresentationHandler.cs | 16 +- src/Protocol/Document/ICompletionHandler.cs | 437 +++++---- src/Protocol/Document/IDeclarationHandler.cs | 16 +- src/Protocol/Document/IDefinitionHandler.cs | 18 +- .../Document/IDidChangeTextDocumentHandler.cs | 16 +- .../Document/IDidCloseTextDocumentHandler.cs | 16 +- .../Document/IDidOpenTextDocumentHandler.cs | 15 +- .../Document/IDidSaveTextDocumentHandler.cs | 16 +- .../Document/IDocumentColorHandler.cs | 21 +- .../Document/IDocumentFormattingHandler.cs | 16 +- .../Document/IDocumentHighlightHandler.cs | 21 +- src/Protocol/Document/IDocumentLinkHandler.cs | 421 +++++---- .../IDocumentOnTypeFormattingHandler.cs | 16 +- .../IDocumentRangeFormattingHandler.cs | 16 +- .../Document/IDocumentSymbolHandler.cs | 16 +- src/Protocol/Document/IFoldingRangeHandler.cs | 20 +- src/Protocol/Document/IHoverHandler.cs | 15 +- .../Document/IImplementationHandler.cs | 16 +- .../Document/IPrepareRenameHandler.cs | 16 +- .../Document/IPublishDiagnosticsHandler.cs | 11 +- src/Protocol/Document/IReferencesHandler.cs | 15 +- src/Protocol/Document/IRenameHandler.cs | 15 +- .../Document/ISelectionRangeHandler.cs | 19 +- .../Document/ISignatureHelpHandler.cs | 18 +- .../Document/ITextDocumentIdentifier.cs | 12 +- .../Document/ITextDocumentSyncHandler.cs | 184 ++-- .../Document/ITypeDefinitionHandler.cs | 16 +- .../Document/IWillSaveTextDocumentHandler.cs | 18 +- .../IWillSaveWaitUntilTextDocumentHandler.cs | 16 +- .../Proposals/ICallHierarchyHandler.cs | 392 +++++--- .../Proposals/ISemanticTokensDeltaHandler.cs | 153 +-- .../Proposals/SemanticTokensBuilder.cs | 63 +- .../Proposals/SemanticTokensDocument.cs | 15 +- .../Document/TextDocumentAttributes.cs | 28 +- src/Protocol/DocumentUri.Internal.cs | 75 +- src/Protocol/DocumentUri.cs | 111 ++- src/Protocol/General/IExitHandler.cs | 10 +- .../ILanguageProtocolInitializeHandler.cs | 6 +- .../ILanguageProtocolInitializedHandler.cs | 10 +- src/Protocol/General/IShutdownHandler.cs | 12 +- .../ILanguageClientWorkspaceFoldersManager.cs | 2 +- src/Protocol/ILanguageProtocolSettings.cs | 6 +- src/Protocol/IProgressHandler.cs | 15 +- src/Protocol/IRegistration.cs | 1 - src/Protocol/ISupports.cs | 1 - .../LanguageProtocolDelegatingHandlers.cs | 251 +++-- .../LanguageProtocolEventingHelper.cs | 14 +- src/Protocol/LanguageProtocolProxy.cs | 4 +- .../LanguageProtocolRpcOptionsBase.cs | 9 +- src/Protocol/LanguageProtocolSettingsBag.cs | 2 +- src/Protocol/Minimatch/Minimatcher.cs | 308 +++--- src/Protocol/Minimatch/Options.cs | 28 +- .../Models/ApplyWorkspaceEditParams.cs | 1 + src/Protocol/Models/BooleanNumberString.cs | 29 +- src/Protocol/Models/BooleanOr.cs | 37 +- src/Protocol/Models/BooleanString.cs | 20 +- src/Protocol/Models/ClientInfo.cs | 2 +- src/Protocol/Models/CodeAction.cs | 1 + src/Protocol/Models/CodeActionKind.cs | 18 +- src/Protocol/Models/CodeLens.cs | 12 +- src/Protocol/Models/CodeLensContainer.cs | 34 +- src/Protocol/Models/ColorInformation.cs | 1 + src/Protocol/Models/ColorPresentation.cs | 2 + .../Models/ColorPresentationParams.cs | 2 + src/Protocol/Models/Command.cs | 4 +- src/Protocol/Models/CommandOrCodeAction.cs | 34 +- .../Models/CommandOrCodeActionContainer.cs | 15 +- src/Protocol/Models/CompletionItem.cs | 13 +- src/Protocol/Models/CompletionList.cs | 80 +- src/Protocol/Models/CompletionTriggerKind.cs | 2 + src/Protocol/Models/ConfigurationItem.cs | 6 +- src/Protocol/Models/Container.cs | 15 +- src/Protocol/Models/ContainerBase.cs | 57 +- src/Protocol/Models/CreateFile.cs | 2 + src/Protocol/Models/CreateFileOptions.cs | 1 + .../Models/DeclarationRegistrationOptions.cs | 4 +- .../Models/DefinitionRegistrationOptions.cs | 4 +- src/Protocol/Models/DeleteFile.cs | 2 + src/Protocol/Models/DeleteFileOptions.cs | 1 + src/Protocol/Models/Diagnostic.cs | 8 +- src/Protocol/Models/DiagnosticCode.cs | 24 +- src/Protocol/Models/DiagnosticSeverity.cs | 3 + .../Models/DidChangeConfigurationParams.cs | 2 +- .../Models/DidChangeTextDocumentParams.cs | 8 +- .../Models/DidChangeWatchedFilesParams.cs | 2 +- .../Models/DidCloseTextDocumentParams.cs | 2 +- .../Models/DidOpenTextDocumentParams.cs | 2 +- .../Models/DidSaveTextDocumentParams.cs | 6 +- src/Protocol/Models/DocumentColor.cs | 2 +- src/Protocol/Models/DocumentFilter.cs | 30 +- .../Models/DocumentFormattingParams.cs | 2 +- .../DocumentFormattingRegistrationOptions.cs | 4 +- .../Models/DocumentHighlightContainer.cs | 15 +- .../DocumentHighlightRegistrationOptions.cs | 4 +- src/Protocol/Models/DocumentLink.cs | 13 +- src/Protocol/Models/DocumentLinkContainer.cs | 34 +- ...umentRangeFormattingRegistrationOptions.cs | 4 +- src/Protocol/Models/DocumentSelector.cs | 49 +- src/Protocol/Models/DocumentSymbol.cs | 1 + src/Protocol/Models/DocumentSymbolParams.cs | 3 +- .../DocumentSymbolRegistrationOptions.cs | 4 +- src/Protocol/Models/ExitRequest.cs | 1 - src/Protocol/Models/FailureHandlingKind.cs | 12 +- src/Protocol/Models/FileChangeType.cs | 10 +- src/Protocol/Models/FileEvent.cs | 7 +- src/Protocol/Models/FileSystemWatcher.cs | 1 + src/Protocol/Models/FoldingRange.cs | 4 +- src/Protocol/Models/FoldingRangeKind.cs | 11 +- .../Models/FoldingRangeRegistrationOptions.cs | 4 +- src/Protocol/Models/FormattingOptions.cs | 50 +- src/Protocol/Models/HandlerIdentity.cs | 3 +- src/Protocol/Models/Hover.cs | 3 +- .../Models/HoverRegistrationOptions.cs | 4 +- src/Protocol/Models/ICanBeResolvedHandler.cs | 3 +- src/Protocol/Models/IDeclarationOptions.cs | 1 - src/Protocol/Models/IDefinitionOptions.cs | 4 +- .../Models/IDocumentFormattingOptions.cs | 4 +- .../Models/IDocumentHighlightOptions.cs | 4 +- .../Models/IDocumentRangeFormattingOptions.cs | 4 +- src/Protocol/Models/IDocumentSymbolOptions.cs | 4 +- .../Models/IDocumentSymbolOptionsOptions.cs | 4 +- src/Protocol/Models/IFoldingRangeOptions.cs | 4 +- src/Protocol/Models/IHoverOptions.cs | 1 - src/Protocol/Models/IImplementationOptions.cs | 4 +- src/Protocol/Models/IPartialItem.cs | 5 +- src/Protocol/Models/IReferencesOptions.cs | 4 +- src/Protocol/Models/ISelectionRangeOptions.cs | 4 +- src/Protocol/Models/ITypeDefinitionOptions.cs | 4 +- .../Models/IWorkDoneProgressOptions.cs | 3 +- .../Models/IWorkspaceFolderOptions.cs | 1 + .../Models/IWorkspaceSymbolOptions.cs | 1 - .../ImplementationRegistrationOptions.cs | 4 +- src/Protocol/Models/InitializeParams.cs | 8 +- src/Protocol/Models/InitializeResult.cs | 6 +- src/Protocol/Models/InitializeTrace.cs | 9 +- src/Protocol/Models/Location.cs | 26 +- src/Protocol/Models/LocationContainer.cs | 15 +- src/Protocol/Models/LocationOrLocationLink.cs | 14 +- .../Models/LocationOrLocationLinks.cs | 15 +- src/Protocol/Models/LogMessageParams.cs | 4 +- src/Protocol/Models/MarkedString.cs | 21 +- .../Models/MarkedStringsOrMarkupContent.cs | 19 +- src/Protocol/Models/MarkupContent.cs | 19 +- src/Protocol/Models/MarkupKind.cs | 7 +- src/Protocol/Models/MessageActionItem.cs | 3 +- src/Protocol/Models/MessageType.cs | 11 +- src/Protocol/Models/ParameterInformation.cs | 3 +- .../Models/ParameterInformationLabel.cs | 21 +- src/Protocol/Models/Position.cs | 33 +- src/Protocol/Models/ProgressParams.cs | 7 +- src/Protocol/Models/ProgressToken.cs | 49 +- .../Models/Proposals/CallHierarchyOptions.cs | 6 +- .../CallHierarchyOutgoingCallsParams.cs | 2 +- .../Proposals/ISemanticTokensOptions.cs | 8 +- .../Models/Proposals/SemanticTokenFormat.cs | 28 +- .../Proposals/SemanticTokenModifiers.cs | 28 +- .../Models/Proposals/SemanticTokenTypes.cs | 28 +- .../Proposals/SemanticTokensDeltaParams.cs | 2 +- .../SemanticTokensDeltaPartialResult.cs | 1 - .../Proposals/SemanticTokensFullOrDelta.cs | 10 +- .../SemanticTokensFullOrDeltaPartialResult.cs | 18 +- .../Models/Proposals/SemanticTokensLegend.cs | 102 +- .../Models/Proposals/SemanticTokensOptions.cs | 18 +- .../Models/Proposals/SemanticTokensParams.cs | 2 +- .../Proposals/SemanticTokensRangeParams.cs | 2 +- .../SemanticTokensRegistrationOptions.cs | 12 +- .../Models/PublishDiagnosticsParams.cs | 4 +- src/Protocol/Models/Range.cs | 35 +- .../Models/RangeOrPlaceholderRange.cs | 41 +- src/Protocol/Models/ReferenceContext.cs | 3 - .../Models/ReferenceRegistrationOptions.cs | 4 +- src/Protocol/Models/Registration.cs | 11 +- src/Protocol/Models/RegistrationContainer.cs | 24 +- src/Protocol/Models/RenameFile.cs | 3 + src/Protocol/Models/RenameFileOptions.cs | 1 + src/Protocol/Models/ResourceOperationKind.cs | 17 +- src/Protocol/Models/SelectionRange.cs | 1 + .../SelectionRangeRegistrationOptions.cs | 4 +- src/Protocol/Models/ServerInfo.cs | 11 +- src/Protocol/Models/ShowMessageParams.cs | 8 +- .../Models/ShowMessageRequestParams.cs | 11 +- src/Protocol/Models/ShutdownParams.cs | 1 - .../Models/SignatureHelpTriggerKind.cs | 2 + src/Protocol/Models/StringOrMarkupContent.cs | 25 +- src/Protocol/Models/SymbolInformation.cs | 1 + .../SymbolInformationOrDocumentSymbol.cs | 40 +- ...bolInformationOrDocumentSymbolContainer.cs | 54 +- src/Protocol/Models/TelemetryEventParams.cs | 3 +- src/Protocol/Models/TextDocument.cs | 2 +- .../TextDocumentChangeRegistrationOptions.cs | 6 +- .../Models/TextDocumentContentChangeEvent.cs | 10 +- src/Protocol/Models/TextDocumentIdentifier.cs | 21 +- src/Protocol/Models/TextDocumentItem.cs | 1 + .../Models/TextDocumentRegistrationOptions.cs | 4 +- src/Protocol/Models/TextDocumentSaveReason.cs | 11 +- .../TextDocumentSaveRegistrationOptions.cs | 2 +- src/Protocol/Models/TextEdit.cs | 3 +- src/Protocol/Models/TextEditContainer.cs | 15 +- .../TypeDefinitionRegistrationOptions.cs | 4 +- src/Protocol/Models/Unregistration.cs | 15 +- .../Models/UnregistrationContainer.cs | 39 +- src/Protocol/Models/UnregistrationParams.cs | 6 +- .../Models/VersionedTextDocumentIdentifier.cs | 7 +- .../Models/WillSaveTextDocumentParams.cs | 6 +- .../WillSaveWaitUntilTextDocumentParams.cs | 6 +- src/Protocol/Models/WorkDoneProgress.cs | 33 +- src/Protocol/Models/WorkDoneProgressBegin.cs | 4 +- src/Protocol/Models/WorkDoneProgressEnd.cs | 4 +- .../Models/WorkDoneProgressOptions.cs | 3 +- src/Protocol/Models/WorkDoneProgressReport.cs | 4 +- .../WorkDoneTextDocumentPositionParams.cs | 2 +- .../Models/WorkspaceEditDocumentChange.cs | 20 +- src/Protocol/Models/WorkspaceFolder.cs | 7 +- src/Protocol/Models/WorkspaceFolderParams.cs | 5 - src/Protocol/Models/WorkspaceSymbolOptions.cs | 7 +- .../WorkspaceSymbolRegistrationOptions.cs | 1 - src/Protocol/Progress/EmptySubject.cs | 4 +- src/Protocol/Progress/IProgressContext.cs | 2 +- src/Protocol/Progress/IProgressManager.cs | 13 +- src/Protocol/Progress/IProgressObservable.cs | 4 +- src/Protocol/Progress/IProgressObserver.cs | 3 +- .../Progress/IRequestProgressObservable.cs | 1 + .../PartialItemsRequestProgressObservable.cs | 39 +- src/Protocol/Progress/ProgressManager.cs | 111 ++- src/Protocol/Progress/ProgressObservable.cs | 14 +- src/Protocol/Progress/ProgressObserver.cs | 31 +- .../Progress/RequestProgressObservable.cs | 17 +- .../Serialization/ContractResolver.cs | 44 +- .../AggregateCompletionListConverter.cs | 6 +- .../BooleanNumberStringConverter.cs | 8 +- .../Converters/BooleanOrConverter.cs | 18 +- .../Converters/BooleanStringConverter.cs | 6 +- .../CommandOrCodeActionConverter.cs | 8 +- .../Converters/CompletionListConverter.cs | 3 +- .../Converters/DiagnosticCodeConverter.cs | 8 +- .../Converters/DocumentUriConverter.cs | 9 +- .../Converters/EnumLikeStringConverter.cs | 19 +- .../LocationOrLocationLinkConverter.cs | 6 +- .../LocationOrLocationLinksConverter.cs | 9 +- .../MarkedStringCollectionConverter.cs | 12 +- .../Converters/MarkedStringConverter.cs | 3 +- .../MarkedStringsOrMarkupContentConverter.cs | 6 +- .../NullableDiagnosticCodeConverter.cs | 10 +- .../Converters/NumberEnumConverter.cs | 14 +- .../ParameterInformationLabelConverter.cs | 12 +- .../Converters/ProgressTokenConverter.cs | 6 +- .../RangeOrPlaceholderRangeConverter.cs | 9 +- .../SemanticTokensFullOrDeltaConverter.cs | 10 +- ...TokensFullOrDeltaPartialResultConverter.cs | 10 +- .../StringOrMarkupContentConverter.cs | 3 +- .../Converters/SupportsConverter.cs | 42 +- ...bolInformationOrDocumentSymbolConverter.cs | 10 +- .../Converters/TextDocumentSyncConverter.cs | 4 +- .../Converters/ValueTupleContractResolver.cs | 11 +- .../WorkspaceEditDocumentChangeConverter.cs | 10 +- src/Protocol/Serialization/ISerializer.cs | 2 +- .../Serialization/OptionalAttribute.cs | 4 +- src/Protocol/Serialization/Serializer.cs | 41 +- .../Server/Capabilities/CodeActionOptions.cs | 6 +- .../Server/Capabilities/CodeLensOptions.cs | 10 +- .../Server/Capabilities/CompletionOptions.cs | 9 +- .../Server/Capabilities/DeclarationOptions.cs | 7 +- .../Server/Capabilities/DefinitionOptions.cs | 7 +- .../Capabilities/DocumentColorOptions.cs | 6 +- .../Capabilities/DocumentFormattingOptions.cs | 7 +- .../Capabilities/DocumentHighlightOptions.cs | 7 +- .../Capabilities/DocumentLinkOptions.cs | 12 +- .../DocumentOnTypeFormattingOptions.cs | 13 +- .../DocumentRangeFormattingOptions.cs | 8 +- .../Capabilities/DocumentSymbolOptions.cs | 7 +- .../DocumentSymbolOptionsOptions.cs | 7 +- .../Capabilities/ExecuteCommandOptions.cs | 10 +- .../Capabilities/FoldingRangeOptions.cs | 6 +- .../Server/Capabilities/HoverOptions.cs | 8 +- .../Capabilities/ImplementationOptions.cs | 9 +- .../Server/Capabilities/ReferencesOptions.cs | 8 +- .../Server/Capabilities/RenameOptions.cs | 6 +- .../Server/Capabilities/SaveOptions.cs | 4 +- .../Capabilities/SelectionRangeOptions.cs | 7 +- .../Server/Capabilities/ServerCapabilities.cs | 38 +- .../Capabilities/SignatureHelpOptions.cs | 8 +- .../Capabilities/SynchronizationOptions.cs | 8 +- .../Server/Capabilities/TextDocumentSync.cs | 27 +- .../Capabilities/TextDocumentSyncKind.cs | 14 +- .../Capabilities/TextDocumentSyncOptions.cs | 25 +- .../Capabilities/TypeDefinitionOptions.cs | 7 +- src/Protocol/Server/ClientLanguageServer.cs | 7 +- src/Protocol/Server/GeneralLanguageServer.cs | 7 +- src/Protocol/Server/IClientLanguageServer.cs | 4 +- src/Protocol/Server/IGeneralLanguageServer.cs | 4 +- .../Server/ILanguageServerConfiguration.cs | 4 +- .../ILanguageServerWorkspaceFolderManager.cs | 1 - .../Server/IOnLanguageServerInitialize.cs | 4 +- .../Server/IOnLanguageServerInitialized.cs | 4 +- .../Server/IOnLanguageServerStarted.cs | 2 +- src/Protocol/Server/IScopedConfiguration.cs | 4 +- src/Protocol/Server/ISetTraceHandler.cs | 6 +- .../Server/ITextDocumentLanguageServer.cs | 4 +- .../Server/IWorkspaceLanguageServer.cs | 4 +- .../OnLanguageServerInitializeDelegate.cs | 2 +- .../OnLanguageServerInitializedDelegate.cs | 2 +- .../Server/OnLanguageServerStartedDelegate.cs | 3 +- .../Server/TextDocumentLanguageServer.cs | 7 +- src/Protocol/Server/WindowLanguageServer.cs | 7 +- .../Server/WorkDone/IServerWorkDoneManager.cs | 16 +- .../WorkDone/LanguageServerWorkDoneManager.cs | 53 +- .../Server/WorkDone/NoopWorkDoneObserver.cs | 20 +- .../Server/WorkDone/WorkDoneObserver.cs | 36 +- .../Server/WorkspaceLanguageServer.cs | 7 +- src/Protocol/Shared/ILspHandlerDescriptor.cs | 2 - src/Protocol/Shared/LspHandlerDescriptor.cs | 56 +- .../Shared/LspHandlerTypeDescriptor.cs | 6 +- .../Shared/LspHandlerTypeDescriptorHelper.cs | 37 +- src/Protocol/Supports.cs | 25 +- src/Protocol/TextDocumentNames.cs | 18 +- src/Protocol/Window/ILogMessageHandler.cs | 62 +- src/Protocol/Window/IShowMessageHandler.cs | 66 +- .../Window/IShowMessageRequestHandler.cs | 10 +- src/Protocol/Window/ITelemetryEventHandler.cs | 10 +- .../Window/IWorkDoneProgressCancelHandler.cs | 30 +- .../Window/IWorkDoneProgressCreateHandler.cs | 10 +- src/Protocol/Workspace/IApplyEditHandler.cs | 12 +- .../Workspace/IConfigurationHandler.cs | 12 +- .../IDidChangeConfigurationHandler.cs | 10 +- .../IDidChangeWatchedFilesHandler.cs | 18 +- .../IDidChangeWorkspaceFoldersHandler.cs | 14 +- .../Workspace/IExecuteCommandHandler.cs | 308 +++--- .../Workspace/IWorkspaceFoldersHandler.cs | 10 +- .../Workspace/IWorkspaceSymbolsHandler.cs | 16 +- src/Protocol/WorkspaceFolderChange.cs | 2 +- src/Server/ClientCapabilityProvider.cs | 42 +- .../BaseWorkspaceConfigurationProvider.cs | 28 +- .../DidChangeConfigurationProvider.cs | 92 +- .../DidChangeConfigurationSource.cs | 7 +- .../Configuration/DisposableConfiguration.cs | 2 +- .../EmptyDisposableConfiguration.cs | 10 +- .../WorkspaceConfigurationProvider.cs | 8 +- .../WorkspaceConfigurationSource.cs | 9 +- src/Server/LangaugeServerRegistry.cs | 5 +- src/Server/LanguageServer.Shutdown.cs | 5 +- src/Server/LanguageServer.cs | 177 ++-- src/Server/LanguageServerOptions.cs | 99 +- src/Server/LanguageServerOptionsExtensions.cs | 9 +- src/Server/LanguageServerResolver.cs | 2 +- ...nguageServerServiceCollectionExtensions.cs | 60 +- .../LanguageServerWorkspaceFolderManager.cs | 63 +- src/Server/Logging/LanguageServerLogger.cs | 36 +- .../Logging/LanguageServerLoggerExtensions.cs | 12 +- .../LanguageServerLoggerFilterOptions.cs | 5 +- .../Logging/LanguageServerLoggerProvider.cs | 7 +- src/Server/LspServerReceiver.cs | 11 +- src/Server/Matchers/ExecuteCommandMatcher.cs | 14 +- src/Server/Matchers/ResolveCommandMatcher.cs | 8 +- src/Server/Matchers/TextDocumentMatcher.cs | 66 +- src/Server/Messages/ServerNotInitialized.cs | 4 +- src/Server/Messages/UnknownErrorCode.cs | 4 +- .../Pipelines/ResolveCommandPipeline.cs | 4 +- src/Shared/HandlerCollectionExtensions.cs | 32 +- src/Shared/InterimLanguageProtocolRegistry.cs | 17 +- ...uageProtocolServiceCollectionExtensions.cs | 31 +- src/Shared/LspHandlerDescriptorDisposable.cs | 9 +- src/Shared/LspHandlerDescriptorHelpers.cs | 40 +- src/Shared/LspRequestRouter.cs | 42 +- src/Shared/RequestProcessIdentifier.cs | 14 +- src/Shared/SharedHandlerCollection.cs | 102 +- src/Shared/SupportedCapabilities.cs | 21 +- src/Testing/ClientCapabilityExtensions.cs | 10 +- src/Testing/ConfigurationHelpers.cs | 44 +- src/Testing/LanguageProtocolTestBase.cs | 88 +- src/Testing/LanguageServerTestBase.cs | 48 +- src/Testing/TestConfigurationProvider.cs | 33 +- test/Client.Tests/ClientTests.cs | 587 +++++++----- .../Logging/TestOutputLogScope.cs | 48 +- test/Client.Tests/Logging/TestOutputLogger.cs | 63 +- .../Logging/TestOutputLoggingExtensions.cs | 12 +- .../Logging/TestOutputLoggingProvider.cs | 35 +- test/Client.Tests/PipeServerTestBase.cs | 45 +- test/Client.Tests/TestBase.cs | 44 +- test/Client.Tests/TestRequest.cs | 6 +- test/Client.Tests/TestResponse.cs | 6 +- test/Dap.Tests/DapOutputHandlerTests.cs | 11 +- .../DebugAdapterSpecifictionRecieverTests.cs | 15 +- test/Dap.Tests/EventingTests.cs | 23 +- test/Dap.Tests/FoundationTests.cs | 263 +++--- .../ConnectionAndDisconnectionTests.cs | 31 +- .../Integration/CustomRequestsTests.cs | 133 +-- .../Integration/GenericDapServerTests.cs | 5 +- test/Dap.Tests/Integration/ProgressTests.cs | 165 ++-- .../Integration/RequestCancellationTests.cs | 30 +- test/Dap.Tests/JsonRpcIntegrationTests.cs | 3 + ...uageClientServiceCollectionSupportTests.cs | 158 ++-- ...uageServerServiceCollectionSupportTests.cs | 158 ++-- test/Generation.Tests/GenerationHelpers.cs | 47 +- .../JsonRpcGenerationTests.cs | 4 +- test/JsonRpc.Tests/AggregateSettlerTests.cs | 76 +- test/JsonRpc.Tests/FoundationTests.cs | 45 +- test/JsonRpc.Tests/HandlerResolverTests.cs | 34 +- test/JsonRpc.Tests/InputHandlerTests.cs | 224 +++-- test/JsonRpc.Tests/IntegrationTests.cs | 115 ++- test/JsonRpc.Tests/JsonRpcServerTests.cs | 120 +-- test/JsonRpc.Tests/JsonRpcTestContainer.cs | 5 +- .../MediatorTestsNotificationHandler.cs | 10 +- .../MediatorTestsNotificationHandlerOfT.cs | 14 +- .../MediatorTestsRequestHandlerOfTRequest.cs | 15 +- ...rTestsRequestHandlerOfTRequestTResponse.cs | 15 +- test/JsonRpc.Tests/OutputHandlerTests.cs | 8 +- test/JsonRpc.Tests/ProcessSchedulerTests.cs | 168 ++-- test/JsonRpc.Tests/RequestRouterTests.cs | 22 +- test/JsonRpc.Tests/ResponseRouterTests.cs | 26 +- .../ServerShouldThrowCorrectExceptions.cs | 20 +- .../Server/SpecificationReceiverTests.cs | 134 +-- .../Server/SpecificatiosIdTests.cs | 17 +- .../ServiceCollectionSupportTests.cs | 261 +++--- test/JsonRpc.Tests/SettlerTests.cs | 25 +- .../TestLanguageServerRegistry.cs | 21 +- test/Lsp.Tests/AbsoluteUriConverterTests.cs | 13 +- .../Client/ClientCapabilitiesTests.cs | 88 +- .../Client/CompletionCapabilityTests.cs | 5 +- .../Client/CompletionItemCapabilityTests.cs | 14 +- .../Client/DynamicCapabilityTests.cs | 5 +- .../PublishDiagnosticsCapabilityTests.cs | 8 +- .../Client/SynchronizationCapabilityTests.cs | 6 +- .../TextDocumentClientCapabilitiesTests.cs | 44 +- .../WorkspaceClientCapabilitiesTests.cs | 19 +- .../Server/CodeLensOptionsTests.cs | 5 +- .../Server/CompletionOptionsTests.cs | 5 +- .../Server/DocumentLinkOptionsTests.cs | 5 +- .../DocumentOnTypeFormattingOptionsTests.cs | 10 +- .../Server/ExecuteCommandOptionsTests.cs | 7 +- .../Capabilities/Server/PrepareRenameTests.cs | 9 +- .../Capabilities/Server/SaveOptionsTests.cs | 5 +- .../Server/ServerCapabilitiesTests.cs | 58 +- .../Server/SignatureHelpOptionsTests.cs | 5 +- .../Server/TextDocumentSyncKindTests.cs | 3 +- .../Server/TextDocumentSyncOptionsTests.cs | 7 +- .../Server/TextDocumentSyncTests.cs | 34 +- .../ClientCapabilityProviderFixture.cs | 11 +- .../ClientCapabilityProviderTests.cs | 191 ++-- test/Lsp.Tests/CodeActionKindTests.cs | 45 +- test/Lsp.Tests/CompletionItemKindTests.cs | 79 +- test/Lsp.Tests/DiagnosticKindTests.cs | 41 +- test/Lsp.Tests/DocumentSymbolKindTests.cs | 90 +- test/Lsp.Tests/DocumentUriTests.cs | 148 ++- .../ExecuteCommandSyncHandlerExtensions.cs | 7 +- test/Lsp.Tests/Fixture.cs | 13 +- test/Lsp.Tests/FluentAssertionsExtensions.cs | 69 +- test/Lsp.Tests/FoundationTests.cs | 422 +++++---- test/Lsp.Tests/HandlerResolverTests.cs | 116 ++- .../ConnectionAndDisconnectionTests.cs | 33 +- .../Integration/DynamicRegistrationTests.cs | 262 +++--- test/Lsp.Tests/Integration/EventingTests.cs | 33 +- .../Integration/ExecuteCommandTests.cs | 879 +++++++++++------- .../Integration/InitializationTests.cs | 36 +- .../LanguageServerConfigurationTests.cs | 26 +- test/Lsp.Tests/Integration/LogMessageTests.cs | 41 +- .../Lsp.Tests/Integration/PartialItemTests.cs | 230 ++--- test/Lsp.Tests/Integration/ProgressTests.cs | 318 ++++--- .../Integration/RequestCancellationTests.cs | 142 +-- .../Lsp.Tests/Integration/ShowMessageTests.cs | 41 +- .../Integration/TypedCodeLensTests.cs | 633 +++++++------ .../Integration/TypedCompletionTests.cs | 579 ++++++------ .../Integration/TypedDocumentLinkTests.cs | 538 ++++++----- .../Integration/WorkspaceFolderTests.cs | 49 +- test/Lsp.Tests/JsonFixtureAttribute.cs | 3 +- test/Lsp.Tests/JsonRpcIntegrationTests.cs | 3 + test/Lsp.Tests/JsonRpcTestContainer.cs | 17 +- ...uageClientServiceCollectionSupportTests.cs | 160 ++-- ...uageServerServiceCollectionSupportTests.cs | 158 ++-- test/Lsp.Tests/LspRequestRouterTests.cs | 169 ++-- .../ExecuteCommandHandlerMatcherTests.cs | 15 +- .../Matchers/ResolveCommandMatcherTests.cs | 289 +++--- .../Matchers/TextDocumentMatcherTests.cs | 151 +-- ...rTestsRequestHandlerOfTRequestTResponse.cs | 40 +- .../Messages/ServerNotInitializedTests.cs | 5 +- .../Messages/UnknownErrorCodeTests.cs | 5 +- test/Lsp.Tests/Minimatch/BasicTests.cs | 207 +++-- .../Models/ApplyWorkspaceEditParamsTests.cs | 102 +- .../Models/ApplyWorkspaceEditResponseTests.cs | 5 +- test/Lsp.Tests/Models/CancelParamsTests.cs | 8 +- .../Models/CodeActionContextTests.cs | 22 +- .../Lsp.Tests/Models/CodeActionParamsTests.cs | 52 +- .../CodeActionRegistrationOptionsTests.cs | 25 +- test/Lsp.Tests/Models/CodeLensParamsTests.cs | 10 +- .../CodeLensRegistrationOptionsTests.cs | 25 +- test/Lsp.Tests/Models/CodeLensTests.cs | 17 +- test/Lsp.Tests/Models/CommandTests.cs | 5 +- .../Models/CompletionItemKindTests.cs | 3 +- test/Lsp.Tests/Models/CompletionItemTests.cs | 8 +- test/Lsp.Tests/Models/CompletionListTests.cs | 33 +- .../CompletionRegistrationOptionsTests.cs | 13 +- test/Lsp.Tests/Models/DiagnosticCodeTests.cs | 3 +- .../Models/DiagnosticSeverityTests.cs | 3 +- test/Lsp.Tests/Models/DiagnosticTests.cs | 13 +- .../DidChangeConfigurationParamsTests.cs | 17 +- .../DidChangeTextDocumentParamsTests.cs | 23 +- .../DidChangeWatchedFilesParamsTests.cs | 14 +- .../Models/DidCloseTextDocumentParamsTests.cs | 5 +- .../Models/DidOpenTextDocumentParamsTests.cs | 7 +- .../Models/DidSaveTextDocumentParamsTests.cs | 5 +- test/Lsp.Tests/Models/DocumentFilterTests.cs | 28 +- .../Models/DocumentFormattingParamsTests.cs | 7 +- .../Models/DocumentHighlightKindTests.cs | 3 +- .../Models/DocumentHighlightTests.cs | 6 +- .../Models/DocumentLinkParamsTests.cs | 5 +- .../DocumentLinkRegistrationOptionsTests.cs | 13 +- test/Lsp.Tests/Models/DocumentLinkTests.cs | 5 +- .../DocumentOnTypeFormattingParamsTests.cs | 9 +- ...nTypeFormattingRegistrationOptionsTests.cs | 15 +- .../Lsp.Tests/Models/DocumentSelectorTests.cs | 21 +- .../Models/DocumentSymbolInformationTests.cs | 7 +- .../Models/DocumentSymbolParamsTests.cs | 5 +- .../Models/ExecuteCommandParamsTests.cs | 5 +- .../ExecuteCommandRegistrationOptionsTests.cs | 7 +- test/Lsp.Tests/Models/FileChangeTypeTests.cs | 3 +- test/Lsp.Tests/Models/FileEventTests.cs | 5 +- .../Models/FormattingOptionsTests.cs | 7 +- test/Lsp.Tests/Models/HoverTests.cs | 6 +- test/Lsp.Tests/Models/InitializeErrorTests.cs | 3 +- .../Lsp.Tests/Models/InitializeParamsTests.cs | 64 +- .../Lsp.Tests/Models/InitializeResultTests.cs | 87 +- .../Lsp.Tests/Models/InsertTextFormatTests.cs | 3 +- .../Models/LocationOrLocationLinksTests.cs | 100 +- test/Lsp.Tests/Models/LocationTests.cs | 7 +- .../Lsp.Tests/Models/LogMessageParamsTests.cs | 5 +- test/Lsp.Tests/Models/MarkedStringTests.cs | 3 +- .../Models/MessageActionItemTests.cs | 5 +- test/Lsp.Tests/Models/MessageTypeTests.cs | 3 +- .../Models/ParameterInformationTests.cs | 7 +- test/Lsp.Tests/Models/PositionTests.cs | 3 +- .../Models/PublishDiagnosticsParamsTests.cs | 7 +- test/Lsp.Tests/Models/RangeTests.cs | 4 +- .../Lsp.Tests/Models/ReferenceContextTests.cs | 5 +- test/Lsp.Tests/Models/ReferenceParamsTests.cs | 9 +- .../Models/RegistrationParamsTests.cs | 17 +- test/Lsp.Tests/Models/RegistrationTests.cs | 5 +- test/Lsp.Tests/Models/RenameParamsTests.cs | 5 +- .../Models/ShowMessageParamsTests.cs | 5 +- .../Models/ShowMessageRequestParamsTests.cs | 13 +- .../SignatureHelpRegistrationOptionsTests.cs | 15 +- test/Lsp.Tests/Models/SignatureHelpTests.cs | 27 +- .../Models/SignatureInformationTests.cs | 62 +- test/Lsp.Tests/Models/SymbolKindTests.cs | 3 +- ...tDocumentChangeRegistrationOptionsTests.cs | 13 +- .../TextDocumentContentChangeEventTests.cs | 6 +- .../Lsp.Tests/Models/TextDocumentEditTests.cs | 17 +- .../Models/TextDocumentIdentifierTests.cs | 15 +- .../Lsp.Tests/Models/TextDocumentItemTests.cs | 5 +- .../Models/TextDocumentPositionParamsTests.cs | 5 +- .../TextDocumentRegistrationOptionsTests.cs | 13 +- .../Models/TextDocumentSaveReasonTests.cs | 3 +- ...extDocumentSaveRegistrationOptionsTests.cs | 13 +- test/Lsp.Tests/Models/TextEditTests.cs | 6 +- .../Models/UnregistrationParamsTests.cs | 17 +- test/Lsp.Tests/Models/UnregistrationTests.cs | 5 +- .../VersionedTextDocumentIdentifierTests.cs | 6 +- .../Models/WillSaveTextDocumentParamsTests.cs | 5 +- test/Lsp.Tests/Models/WorkspaceEditTests.cs | 145 ++- .../Models/WorkspaceSymbolInformationTests.cs | 7 +- .../Models/WorkspaceSymbolParamsTests.cs | 5 +- .../RequestProcessIdentifierTests.cs | 6 +- test/Lsp.Tests/SemanticTokensDocumentTests.cs | 211 +++-- .../Lsp.Tests/SupportedCapabilitiesFixture.cs | 5 +- .../Testing/LanguageServerTestBaseTests.cs | 10 +- .../TextDocumentSyncHandlerExtensions.cs | 32 +- test/Lsp.Tests/VsCodeDocumentUriTests.cs | 247 +++-- test/Lsp.Tests/WorkspaceSymbolKindTests.cs | 90 +- .../AutoNSubstitute/AutoSubstitute.cs | 19 +- .../AutoNSubstitute/AutoTestBase.cs | 24 +- .../AutoNSubstitute/DryIocExtensions.cs | 4 +- .../AutoNSubstitute/TestExtensions.cs | 20 +- .../AutoNSubstitute/TestLoggerFactory.cs | 24 +- .../AutoNSubstitute/TraceWriter.cs | 5 +- 1018 files changed, 15217 insertions(+), 13510 deletions(-) diff --git a/.build/Build.cs b/.build/Build.cs index 405a65fc0..6891dbf53 100644 --- a/.build/Build.cs +++ b/.build/Build.cs @@ -18,18 +18,18 @@ [MSBuildVerbosityMapping] [NuGetVerbosityMapping] public partial class Solution : NukeBuild, - ICanRestoreWithDotNetCore, - ICanBuildWithDotNetCore, - ICanTestWithDotNetCore, - ICanPackWithDotNetCore, - IHaveDataCollector, - ICanClean, - ICanUpdateReadme, - IGenerateCodeCoverageReport, - IGenerateCodeCoverageSummary, - IGenerateCodeCoverageBadges, - IHaveConfiguration, - ICanLint + ICanRestoreWithDotNetCore, + ICanBuildWithDotNetCore, + ICanTestWithDotNetCore, + ICanPackWithDotNetCore, + IHaveDataCollector, + ICanClean, + ICanUpdateReadme, + IGenerateCodeCoverageReport, + IGenerateCodeCoverageSummary, + IGenerateCodeCoverageBadges, + IHaveConfiguration, + ICanLint { /// /// Support plugins are available for: @@ -40,31 +40,28 @@ public partial class Solution : NukeBuild, /// public static int Main() => Execute(x => x.Default); - [OptionalGitRepository] - public GitRepository? GitRepository { get; } + [OptionalGitRepository] public GitRepository? GitRepository { get; } private Target Default => _ => _ - .DependsOn(Restore) - .DependsOn(Build) - .DependsOn(Test) - .DependsOn(Pack); + .DependsOn(Restore) + .DependsOn(Build) + .DependsOn(Test) + .DependsOn(Pack); public Target Build => _ => _.Inherit(x => x.CoreBuild); public Target Pack => _ => _.Inherit(x => x.CorePack) - .DependsOn(Clean); + .DependsOn(Clean); - [ComputedGitVersion] - public GitVersion GitVersion { get; } = null!; + [ComputedGitVersion] public GitVersion GitVersion { get; } = null!; public Target Clean => _ => _.Inherit(x => x.Clean); public Target Restore => _ => _.Inherit(x => x.CoreRestore); public Target Test => _ => _.Inherit(x => x.CoreTest); public Target BuildVersion => _ => _.Inherit(x => x.BuildVersion) - .Before(Default) - .Before(Clean); + .Before(Default) + .Before(Clean); - [Parameter("Configuration to build")] - public Configuration Configuration { get; } = IsLocalBuild ? Configuration.Debug : Configuration.Release; + [Parameter("Configuration to build")] public Configuration Configuration { get; } = IsLocalBuild ? Configuration.Debug : Configuration.Release; } diff --git a/.build/Configuration.cs b/.build/Configuration.cs index 549687ceb..57e9a8bf8 100644 --- a/.build/Configuration.cs +++ b/.build/Configuration.cs @@ -8,4 +8,4 @@ public class Configuration : Enumeration public static readonly Configuration Release = new Configuration { Value = nameof(Release) }; public static implicit operator string(Configuration configuration) => configuration.Value; -} \ No newline at end of file +} diff --git a/.build/Solution.cs b/.build/Solution.cs index 0544eb604..9d28ca249 100644 --- a/.build/Solution.cs +++ b/.build/Solution.cs @@ -9,8 +9,7 @@ [AzurePipelinesSteps( AutoGenerate = false, InvokeTargets = new[] { nameof(Default) }, - NonEntryTargets = new[] - { + NonEntryTargets = new[] { nameof(ICIEnvironment.CIEnvironment), nameof(ITriggerCodeCoverageReports.Trigger_Code_Coverage_Reports), nameof(ITriggerCodeCoverageReports.Generate_Code_Coverage_Report_Cobertura), @@ -21,21 +20,20 @@ }, ExcludedTargets = new[] { nameof(ICanClean.Clean), nameof(ICanRestoreWithDotNetCore.Restore), nameof(ICanRestoreWithDotNetCore.DotnetToolRestore) }, - Parameters = new[] - { + Parameters = new[] { nameof(IHaveCodeCoverage.CoverageDirectory), nameof(IHaveOutputArtifacts.ArtifactsDirectory), nameof(Verbosity), nameof(IHaveConfiguration.Configuration) } )] -[GitHubActionsSteps("ci", GitHubActionsImage.MacOsLatest, GitHubActionsImage.WindowsLatest, GitHubActionsImage.UbuntuLatest, +[GitHubActionsSteps( + "ci", GitHubActionsImage.MacOsLatest, GitHubActionsImage.WindowsLatest, GitHubActionsImage.UbuntuLatest, AutoGenerate = false, On = new[] { GitHubActionsTrigger.Push }, OnPushTags = new[] { "v*" }, OnPushBranches = new[] { "master", "next" }, OnPullRequestBranches = new[] { "master", "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), @@ -47,7 +45,9 @@ ExcludedTargets = new[] { nameof(ICanClean.Clean), nameof(ICanRestoreWithDotNetCore.DotnetToolRestore) }, Enhancements = new[] { nameof(Middleware) } )] -[PrintBuildVersion, PrintCIEnvironment, UploadLogs] +[PrintBuildVersion] +[PrintCIEnvironment] +[UploadLogs] public partial class Solution { public static RocketSurgeonGitHubActionsConfiguration Middleware(RocketSurgeonGitHubActionsConfiguration configuration) @@ -56,19 +56,20 @@ public static RocketSurgeonGitHubActionsConfiguration Middleware(RocketSurgeonGi var checkoutStep = buildJob.Steps.OfType().Single(); // For fetch all checkoutStep.FetchDepth = 0; - buildJob.Steps.InsertRange(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 SetupDotNetStep("Use .NET Core 3.1 SDK") { - DotNetVersion = "3.1.x" - }, - new RunStep("🪓 **DOTNET HACK** 🪓") { - Shell = GithubActionShell.Pwsh, - Run = @"$version = Split-Path (Split-Path $ENV:DOTNET_ROOT -Parent) -Leaf; + buildJob.Steps.InsertRange( + 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 SetupDotNetStep("Use .NET Core 3.1 SDK") { + DotNetVersion = "3.1.x" + }, + new RunStep("🪓 **DOTNET HACK** 🪓") { + Shell = GithubActionShell.Pwsh, + Run = @"$version = Split-Path (Split-Path $ENV:DOTNET_ROOT -Parent) -Leaf; $root = Split-Path (Split-Path $ENV:DOTNET_ROOT -Parent) -Parent; $directories = Get-ChildItem $root | Where-Object { $_.Name -ne $version }; foreach ($dir in $directories) { @@ -78,46 +79,51 @@ public static RocketSurgeonGitHubActionsConfiguration Middleware(RocketSurgeonGi Copy-Item ""$from\*"" $to -Recurse -Force; } " - }, - }); + }, + } + ); - buildJob.Steps.Add(new UsingStep("Publish Coverage") - { - Uses = "codecov/codecov-action@v1", - With = new Dictionary - { - ["name"] = "actions-${{ matrix.os }}", - ["fail_ci_if_error"] = "true", + buildJob.Steps.Add( + new UsingStep("Publish Coverage") { + Uses = "codecov/codecov-action@v1", + With = new Dictionary { + ["name"] = "actions-${{ matrix.os }}", + ["fail_ci_if_error"] = "true", + } } - }); + ); - buildJob.Steps.Add(new UploadArtifactStep("Publish logs") - { - Name = "logs", - Path = "artifacts/logs/", - If = "always()" - }); + buildJob.Steps.Add( + new UploadArtifactStep("Publish logs") { + Name = "logs", + Path = "artifacts/logs/", + If = "always()" + } + ); - buildJob.Steps.Add(new UploadArtifactStep("Publish coverage data") - { - Name = "coverage", - Path = "coverage/", - If = "always()" - }); + buildJob.Steps.Add( + new UploadArtifactStep("Publish coverage data") { + Name = "coverage", + Path = "coverage/", + If = "always()" + } + ); - buildJob.Steps.Add(new UploadArtifactStep("Publish test data") - { - Name = "test data", - Path = "artifacts/test/", - If = "always()" - }); + buildJob.Steps.Add( + new UploadArtifactStep("Publish test data") { + Name = "test data", + Path = "artifacts/test/", + If = "always()" + } + ); - buildJob.Steps.Add(new UploadArtifactStep("Publish NuGet Packages") - { - Name = "nuget", - Path = "artifacts/nuget/", - If = "always()" - }); + buildJob.Steps.Add( + new UploadArtifactStep("Publish NuGet Packages") { + Name = "nuget", + Path = "artifacts/nuget/", + If = "always()" + } + ); /* diff --git a/Directory.Build.props b/Directory.Build.props index 1a9bf3fa3..42bad2d6e 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -23,7 +23,8 @@ $(AllowedReferenceRelatedFileExtensions);.pdb - + diff --git a/Directory.Build.targets b/Directory.Build.targets index bb68bd18a..9acff7577 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,4 +1,5 @@  + diff --git a/NuGet.config b/NuGet.config index 485b068c3..ac153c4e2 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,6 +1,7 @@ + - - - + + + diff --git a/benchmarks/Pipeline/Class1.cs b/benchmarks/Pipeline/Class1.cs index 03291e6f3..641e34f4b 100644 --- a/benchmarks/Pipeline/Class1.cs +++ b/benchmarks/Pipeline/Class1.cs @@ -1,12 +1,12 @@ using System.Buffers; -using System.Text; -using BenchmarkDotNet.Attributes; -using BenchmarkDotNet.Running; using System.IO.Pipelines; using System.Linq; +using System.Text; using System.Threading; using System.Threading.Tasks; +using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; +using BenchmarkDotNet.Running; namespace Pipeline { @@ -27,10 +27,6 @@ public class ClassicVsPipelines private ClassicHandler _classic; private PipelinesBased _pipelines; - public ClassicVsPipelines() - { - } - [Params( sampleCommand, anotherPayload diff --git a/benchmarks/Pipeline/ClassicHandler.cs b/benchmarks/Pipeline/ClassicHandler.cs index fd3fa8044..04fee54e8 100644 --- a/benchmarks/Pipeline/ClassicHandler.cs +++ b/benchmarks/Pipeline/ClassicHandler.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Text; using System.Threading; using System.Threading.Tasks; @@ -10,14 +11,11 @@ public class ClassicHandler private readonly Stream _input; public const char CR = '\r'; public const char LF = '\n'; - public static char[] CRLF = {CR, LF}; - public static char[] HeaderKeys = {CR, LF, ':'}; + public static char[] CRLF = { CR, LF }; + public static char[] HeaderKeys = { CR, LF, ':' }; public const short MinBuffer = 21; // Minimum size of the buffer "Content-Length: X\r\n\r\n" - public ClassicHandler(Stream input) - { - _input = input; - } + public ClassicHandler(Stream input) => _input = input; // don't be async: We already allocated a seperate thread for this. public Task ProcessInputStream() @@ -42,7 +40,7 @@ public Task ProcessInputStream() current += n; } - var headersContent = System.Text.Encoding.ASCII.GetString(buffer, 0, current); + var headersContent = Encoding.ASCII.GetString(buffer, 0, current); var headers = headersContent.Split(HeaderKeys, StringSplitOptions.RemoveEmptyEntries); long length = 0; for (var i = 1; i < headers.Length; i += 2) @@ -73,7 +71,7 @@ public Task ProcessInputStream() } // TODO sometimes: encoding should be based on the respective header (including the wrong "utf8" value) - var payload = System.Text.Encoding.ASCII.GetString(requestBuffer); + var payload = Encoding.ASCII.GetString(requestBuffer); HandleRequest(payload, CancellationToken.None); } } diff --git a/benchmarks/Pipeline/PipelinesBased.cs b/benchmarks/Pipeline/PipelinesBased.cs index 4ae600c6e..08922cfcf 100644 --- a/benchmarks/Pipeline/PipelinesBased.cs +++ b/benchmarks/Pipeline/PipelinesBased.cs @@ -23,10 +23,10 @@ public PipelinesBased(PipeReader pipeReader) public static readonly byte[] HeadersFinished = - new byte[] {(byte) '\r', (byte) '\n', (byte) '\r', (byte) '\n'}.ToArray(); + new[] { (byte) '\r', (byte) '\n', (byte) '\r', (byte) '\n' }.ToArray(); public const int HeadersFinishedLength = 4; - public static readonly char[] HeaderKeys = {'\r', '\n', ':'}; + public static readonly char[] HeaderKeys = { '\r', '\n', ':' }; public const short MinBuffer = 21; // Minimum size of the buffer "Content-Length: X\r\n\r\n" public static readonly byte[] ContentLength = "Content-Length".Select(x => (byte) x).ToArray(); public static readonly int ContentLengthLength = 14; @@ -75,7 +75,7 @@ private bool TryParseHeaders(ref ReadOnlySequence buffer, out ReadOnlySequ return false; } - static bool IsEqual(in Span headers, in byte[] bytes) + private static bool IsEqual(in Span headers, in byte[] bytes) { var isEqual = true; var len = bytes.Length; @@ -89,8 +89,10 @@ static bool IsEqual(in Span headers, in byte[] bytes) return isEqual; } - private bool TryParseBodyString(in long length, ref ReadOnlySequence buffer, - out ReadOnlySequence line) + private bool TryParseBodyString( + in long length, ref ReadOnlySequence buffer, + out ReadOnlySequence line + ) { if (buffer.Length < length) { @@ -104,7 +106,7 @@ private bool TryParseBodyString(in long length, ref ReadOnlySequence buffe return true; } - bool TryParseContentLength(ref ReadOnlySequence buffer, out long length) + private bool TryParseContentLength(ref ReadOnlySequence buffer, out long length) { do { @@ -123,7 +125,7 @@ bool TryParseContentLength(ref ReadOnlySequence buffer, out long length) var position = buffer.GetPosition(1, colon.Value); var offset = 1; - while (buffer.TryGet(ref position, out var memory, true) && !memory.Span.IsEmpty) + while (buffer.TryGet(ref position, out var memory) && !memory.Span.IsEmpty) { foreach (var t in memory.Span) { @@ -155,16 +157,15 @@ bool TryParseContentLength(ref ReadOnlySequence buffer, out long length) for (var i = 0; i < lengthSlice.Length; i++) _contentLengthValueMemory.Span[i] = 0; return true; } + // Reset the array otherwise smaller numbers will be inflated; for (var i = 0; i < lengthSlice.Length; i++) _contentLengthValueMemory.Span[i] = 0; // _logger.LogError("Unable to get length from content length header..."); return false; } - else - { - buffer = buffer.Slice(buffer.GetPosition(1, buffer.PositionOf((byte) '\n') ?? buffer.End)); - } + + buffer = buffer.Slice(buffer.GetPosition(1, buffer.PositionOf((byte) '\n') ?? buffer.End)); } while (true); } diff --git a/sample/SampleServer/DidChangeWatchedFilesHandler.cs b/sample/SampleServer/DidChangeWatchedFilesHandler.cs index d9ed665f8..f3ecdffa9 100644 --- a/sample/SampleServer/DidChangeWatchedFilesHandler.cs +++ b/sample/SampleServer/DidChangeWatchedFilesHandler.cs @@ -7,23 +7,14 @@ namespace SampleServer { - class DidChangeWatchedFilesHandler : IDidChangeWatchedFilesHandler + internal class DidChangeWatchedFilesHandler : IDidChangeWatchedFilesHandler { private DidChangeWatchedFilesCapability _capability; - public DidChangeWatchedFilesRegistrationOptions GetRegistrationOptions() - { - return new DidChangeWatchedFilesRegistrationOptions(); - } + public DidChangeWatchedFilesRegistrationOptions GetRegistrationOptions() => new DidChangeWatchedFilesRegistrationOptions(); - public Task Handle(DidChangeWatchedFilesParams request, CancellationToken cancellationToken) - { - return Unit.Task; - } + public Task Handle(DidChangeWatchedFilesParams request, CancellationToken cancellationToken) => Unit.Task; - public void SetCapability(DidChangeWatchedFilesCapability capability) - { - _capability = capability; - } + public void SetCapability(DidChangeWatchedFilesCapability capability) => _capability = capability; } } diff --git a/sample/SampleServer/FoldingRangeHandler.cs b/sample/SampleServer/FoldingRangeHandler.cs index 635fb0529..1742c8b95 100644 --- a/sample/SampleServer/FoldingRangeHandler.cs +++ b/sample/SampleServer/FoldingRangeHandler.cs @@ -3,36 +3,34 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Server; namespace SampleServer { - class FoldingRangeHandler : IFoldingRangeHandler + internal class FoldingRangeHandler : IFoldingRangeHandler { private FoldingRangeCapability _capability; - public FoldingRangeRegistrationOptions GetRegistrationOptions() - { - return new FoldingRangeRegistrationOptions() { + public FoldingRangeRegistrationOptions GetRegistrationOptions() => + new FoldingRangeRegistrationOptions { DocumentSelector = DocumentSelector.ForLanguage("csharp") }; - } - public Task> Handle(FoldingRangeRequestParam request, - CancellationToken cancellationToken) - { - return Task.FromResult(new Container(new FoldingRange() { - StartLine = 10, - EndLine = 20, - Kind = FoldingRangeKind.Region, - EndCharacter = 0, - StartCharacter = 0 - })); - } + public Task> Handle( + FoldingRangeRequestParam request, + CancellationToken cancellationToken + ) => + Task.FromResult( + new Container( + new FoldingRange { + StartLine = 10, + EndLine = 20, + Kind = FoldingRangeKind.Region, + EndCharacter = 0, + StartCharacter = 0 + } + ) + ); - public void SetCapability(FoldingRangeCapability capability) - { - _capability = capability; - } + public void SetCapability(FoldingRangeCapability capability) => _capability = capability; } } diff --git a/sample/SampleServer/Program.cs b/sample/SampleServer/Program.cs index a1669a033..36264824a 100644 --- a/sample/SampleServer/Program.cs +++ b/sample/SampleServer/Program.cs @@ -1,27 +1,20 @@ using System; -using System.Diagnostics; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; -using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals; using OmniSharp.Extensions.LanguageServer.Server; using Serilog; namespace SampleServer { - class Program + internal class Program { - static void Main(string[] args) - { - MainAsync(args).Wait(); - } + private static void Main(string[] args) => MainAsync(args).Wait(); - static async Task MainAsync(string[] args) + private static async Task MainAsync(string[] args) { // Debugger.Launch(); // while (!Debugger.IsAttached) @@ -30,106 +23,132 @@ static async Task MainAsync(string[] args) // } Log.Logger = new LoggerConfiguration() - .Enrich.FromLogContext() - .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day) - .MinimumLevel.Verbose() - .CreateLogger(); + .Enrich.FromLogContext() + .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day) + .MinimumLevel.Verbose() + .CreateLogger(); Log.Logger.Information("This only goes file..."); IObserver workDone = null; - var server = await LanguageServer.From(options => - options - .WithInput(Console.OpenStandardInput()) - .WithOutput(Console.OpenStandardOutput()) - .ConfigureLogging(x => x - .AddSerilog(Log.Logger) - .AddLanguageProtocolLogging() - .SetMinimumLevel(LogLevel.Debug)) - .WithHandler() - .WithHandler() - .WithHandler() - .WithHandler() - .WithHandler() - .WithHandler() - .WithServices(x => x.AddLogging(b => b.SetMinimumLevel(LogLevel.Trace))) - .WithServices(services => { - services.AddSingleton(provider => { - var loggerFactory = provider.GetService(); - var logger = loggerFactory.CreateLogger(); - - logger.LogInformation("Configuring"); - - return new Foo(logger); - }); - services.AddSingleton(new ConfigurationItem() { - Section = "typescript", - }).AddSingleton(new ConfigurationItem() { - Section = "terminal", - }); - }) - .OnInitialize(async (server, request, token) => { - var manager = server.WorkDoneManager.For(request, new WorkDoneProgressBegin() { - Title = "Server is starting...", - Percentage = 10, - }); - workDone = manager; - - await Task.Delay(2000); - - manager.OnNext(new WorkDoneProgressReport() { - Percentage = 20, - Message = "loading in progress" - }); - }) - .OnInitialized(async (server, request, response, token) => { - workDone.OnNext(new WorkDoneProgressReport() { - Percentage = 40, - Message = "loading almost done", - }); - - await Task.Delay(2000); - - workDone.OnNext(new WorkDoneProgressReport() { - Message = "loading done", - Percentage = 100, - }); - workDone.OnCompleted(); - }) - .OnStarted(async (languageServer, token) => { - using var manager = await languageServer.WorkDoneManager.Create(new WorkDoneProgressBegin() { Title = "Doing some work..." }); - - manager.OnNext(new WorkDoneProgressReport() { Message = "doing things..." }); - await Task.Delay(10000); - manager.OnNext(new WorkDoneProgressReport() { Message = "doing things... 1234" }); - await Task.Delay(10000); - manager.OnNext(new WorkDoneProgressReport() { Message = "doing things... 56789" }); - - var logger = languageServer.Services.GetService>(); - var configuration = await languageServer.Configuration.GetConfiguration( - new ConfigurationItem() { - Section = "typescript", - }, new ConfigurationItem() { - Section = "terminal", - }); - - var baseConfig = new JObject(); - foreach (var config in languageServer.Configuration.AsEnumerable()) - { - baseConfig.Add(config.Key, config.Value); - } - - logger.LogInformation("Base Config: {Config}", baseConfig); - - var scopedConfig = new JObject(); - foreach (var config in configuration.AsEnumerable()) - { - scopedConfig.Add(config.Key, config.Value); - } - - logger.LogInformation("Scoped Config: {Config}", scopedConfig); - }) + var server = await LanguageServer.From( + options => + options + .WithInput(Console.OpenStandardInput()) + .WithOutput(Console.OpenStandardOutput()) + .ConfigureLogging( + x => x + .AddSerilog(Log.Logger) + .AddLanguageProtocolLogging() + .SetMinimumLevel(LogLevel.Debug) + ) + .WithHandler() + .WithHandler() + .WithHandler() + .WithHandler() + .WithHandler() + .WithHandler() + .WithServices(x => x.AddLogging(b => b.SetMinimumLevel(LogLevel.Trace))) + .WithServices( + services => { + services.AddSingleton( + provider => { + var loggerFactory = provider.GetService(); + var logger = loggerFactory.CreateLogger(); + + logger.LogInformation("Configuring"); + + return new Foo(logger); + } + ); + services.AddSingleton( + new ConfigurationItem { + Section = "typescript", + } + ).AddSingleton( + new ConfigurationItem { + Section = "terminal", + } + ); + } + ) + .OnInitialize( + async (server, request, token) => { + var manager = server.WorkDoneManager.For( + request, new WorkDoneProgressBegin { + Title = "Server is starting...", + Percentage = 10, + } + ); + workDone = manager; + + await Task.Delay(2000); + + manager.OnNext( + new WorkDoneProgressReport { + Percentage = 20, + Message = "loading in progress" + } + ); + } + ) + .OnInitialized( + async (server, request, response, token) => { + workDone.OnNext( + new WorkDoneProgressReport { + Percentage = 40, + Message = "loading almost done", + } + ); + + await Task.Delay(2000); + + workDone.OnNext( + new WorkDoneProgressReport { + Message = "loading done", + Percentage = 100, + } + ); + workDone.OnCompleted(); + } + ) + .OnStarted( + async (languageServer, token) => { + using var manager = await languageServer.WorkDoneManager.Create(new WorkDoneProgressBegin { Title = "Doing some work..." }); + + manager.OnNext(new WorkDoneProgressReport { Message = "doing things..." }); + await Task.Delay(10000); + manager.OnNext(new WorkDoneProgressReport { Message = "doing things... 1234" }); + await Task.Delay(10000); + manager.OnNext(new WorkDoneProgressReport { Message = "doing things... 56789" }); + + var logger = languageServer.Services.GetService>(); + var configuration = await languageServer.Configuration.GetConfiguration( + new ConfigurationItem { + Section = "typescript", + }, new ConfigurationItem { + Section = "terminal", + } + ); + + var baseConfig = new JObject(); + foreach (var config in languageServer.Configuration.AsEnumerable()) + { + baseConfig.Add(config.Key, config.Value); + } + + logger.LogInformation("Base Config: {Config}", baseConfig); + + var scopedConfig = new JObject(); + foreach (var config in configuration.AsEnumerable()) + { + scopedConfig.Add(config.Key, config.Value); + } + + logger.LogInformation("Scoped Config: {Config}", scopedConfig); + } + ) ); await server.WaitForExit; @@ -146,9 +165,6 @@ public Foo(ILogger logger) _logger = logger; } - public void SayFoo() - { - _logger.LogInformation("Fooooo!"); - } + public void SayFoo() => _logger.LogInformation("Fooooo!"); } } diff --git a/sample/SampleServer/SemanticTokensHandler.cs b/sample/SampleServer/SemanticTokensHandler.cs index ac6dc121a..480e0f914 100644 --- a/sample/SampleServer/SemanticTokensHandler.cs +++ b/sample/SampleServer/SemanticTokensHandler.cs @@ -5,7 +5,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Newtonsoft.Json; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document.Proposals; @@ -19,41 +18,47 @@ public class SemanticTokensHandler : SemanticTokensHandlerBase { private readonly ILogger _logger; - public SemanticTokensHandler(ILogger logger) : base(new SemanticTokensRegistrationOptions() { - DocumentSelector = DocumentSelector.ForLanguage("csharp"), - Legend = new SemanticTokensLegend(), - Full = new SemanticTokensCapabilityRequestFull() { - Delta = true - }, - Range = true - }) - { + public SemanticTokensHandler(ILogger logger) : base( + new SemanticTokensRegistrationOptions { + DocumentSelector = DocumentSelector.ForLanguage("csharp"), + Legend = new SemanticTokensLegend(), + Full = new SemanticTokensCapabilityRequestFull { + Delta = true + }, + Range = true + } + ) => _logger = logger; - } public override async Task Handle( - SemanticTokensParams request, CancellationToken cancellationToken) + SemanticTokensParams request, CancellationToken cancellationToken + ) { var result = await base.Handle(request, cancellationToken); return result; } public override async Task Handle( - SemanticTokensRangeParams request, CancellationToken cancellationToken) + SemanticTokensRangeParams request, CancellationToken cancellationToken + ) { var result = await base.Handle(request, cancellationToken); return result; } - public override async Task Handle(SemanticTokensDeltaParams request, - CancellationToken cancellationToken) + public override async Task Handle( + SemanticTokensDeltaParams request, + CancellationToken cancellationToken + ) { var result = await base.Handle(request, cancellationToken); return result; } - protected override async Task Tokenize(SemanticTokensBuilder builder, ITextDocumentIdentifierParams identifier, - CancellationToken cancellationToken) + protected override async Task Tokenize( + SemanticTokensBuilder builder, ITextDocumentIdentifierParams identifier, + CancellationToken cancellationToken + ) { using var typesEnumerator = RotateEnum(SemanticTokenType.Defaults).GetEnumerator(); using var modifiersEnumerator = RotateEnum(SemanticTokenModifier.Defaults).GetEnumerator(); @@ -61,7 +66,7 @@ protected override async Task Tokenize(SemanticTokensBuilder builder, ITextDocum var content = await File.ReadAllTextAsync(DocumentUri.GetFileSystemPath(identifier), cancellationToken); 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; @@ -77,10 +82,8 @@ protected override async Task Tokenize(SemanticTokensBuilder builder, ITextDocum } protected override Task - GetSemanticTokensDocument(ITextDocumentIdentifierParams @params, CancellationToken cancellationToken) - { - return Task.FromResult(new SemanticTokensDocument(GetRegistrationOptions().Legend)); - } + GetSemanticTokensDocument(ITextDocumentIdentifierParams @params, CancellationToken cancellationToken) => + Task.FromResult(new SemanticTokensDocument(GetRegistrationOptions().Legend)); private IEnumerable RotateEnum(IEnumerable values) diff --git a/sample/SampleServer/TextDocumentHandler.cs b/sample/SampleServer/TextDocumentHandler.cs index 0b0fd54df..c93498039 100644 --- a/sample/SampleServer/TextDocumentHandler.cs +++ b/sample/SampleServer/TextDocumentHandler.cs @@ -16,21 +16,23 @@ namespace SampleServer { - class TextDocumentHandler : ITextDocumentSyncHandler + internal class TextDocumentHandler : ITextDocumentSyncHandler { private readonly ILogger _logger; private readonly ILanguageServerConfiguration _configuration; private readonly DocumentSelector _documentSelector = new DocumentSelector( - new DocumentFilter() { + new DocumentFilter { Pattern = "**/*.cs" } ); private SynchronizationCapability _capability; - public TextDocumentHandler(ILogger logger, Foo foo, - ILanguageServerConfiguration configuration) + public TextDocumentHandler( + ILogger logger, Foo foo, + ILanguageServerConfiguration configuration + ) { _logger = logger; _configuration = configuration; @@ -49,18 +51,13 @@ public Task Handle(DidChangeTextDocumentParams notification, CancellationT } TextDocumentChangeRegistrationOptions IRegistration. - GetRegistrationOptions() - { - return new TextDocumentChangeRegistrationOptions() { + GetRegistrationOptions() => + new TextDocumentChangeRegistrationOptions { DocumentSelector = _documentSelector, SyncKind = Change }; - } - public void SetCapability(SynchronizationCapability capability) - { - _capability = capability; - } + public void SetCapability(SynchronizationCapability capability) => _capability = capability; public async Task Handle(DidOpenTextDocumentParams notification, CancellationToken token) { @@ -70,12 +67,10 @@ public async Task Handle(DidOpenTextDocumentParams notification, Cancellat return Unit.Value; } - TextDocumentRegistrationOptions IRegistration.GetRegistrationOptions() - { - return new TextDocumentRegistrationOptions() { + TextDocumentRegistrationOptions IRegistration.GetRegistrationOptions() => + new TextDocumentRegistrationOptions { DocumentSelector = _documentSelector, }; - } public Task Handle(DidCloseTextDocumentParams notification, CancellationToken token) { @@ -87,35 +82,31 @@ public Task Handle(DidCloseTextDocumentParams notification, CancellationTo return Unit.Task; } - public Task Handle(DidSaveTextDocumentParams notification, CancellationToken token) - { - return Unit.Task; - } + public Task Handle(DidSaveTextDocumentParams notification, CancellationToken token) => Unit.Task; - TextDocumentSaveRegistrationOptions IRegistration.GetRegistrationOptions() - { - return new TextDocumentSaveRegistrationOptions() { + TextDocumentSaveRegistrationOptions IRegistration.GetRegistrationOptions() => + new TextDocumentSaveRegistrationOptions { DocumentSelector = _documentSelector, IncludeText = true }; - } - public TextDocumentAttributes GetTextDocumentAttributes(DocumentUri uri) - { - return new TextDocumentAttributes(uri, "csharp"); - } + public TextDocumentAttributes GetTextDocumentAttributes(DocumentUri uri) => new TextDocumentAttributes(uri, "csharp"); } - class MyDocumentSymbolHandler : DocumentSymbolHandler + internal class MyDocumentSymbolHandler : DocumentSymbolHandler { - public MyDocumentSymbolHandler() : base(new DocumentSymbolRegistrationOptions() { - DocumentSelector = DocumentSelector.ForLanguage("csharp") - }) + public MyDocumentSymbolHandler() : base( + new DocumentSymbolRegistrationOptions { + DocumentSelector = DocumentSelector.ForLanguage("csharp") + } + ) { } - public override async Task Handle(DocumentSymbolParams request, - CancellationToken cancellationToken) + public override async Task Handle( + DocumentSymbolParams request, + CancellationToken cancellationToken + ) { // you would normally get this from a common source that is managed by current open editor, current active editor, etc. var content = await File.ReadAllTextAsync(DocumentUri.GetFileSystemPath(request), cancellationToken); @@ -134,20 +125,24 @@ public override async Task Handle(Do continue; } - symbols.Add(new DocumentSymbol() { - Detail = part, - Deprecated = true, - Kind = SymbolKind.Field, - Tags = new [] { SymbolTag.Deprecated }, - Range = new OmniSharp.Extensions.LanguageServer.Protocol.Models.Range( - new Position(lineIndex, currentCharacter), - new Position(lineIndex, currentCharacter + part.Length)), - SelectionRange = - new OmniSharp.Extensions.LanguageServer.Protocol.Models.Range( + symbols.Add( + new DocumentSymbol { + Detail = part, + Deprecated = true, + Kind = SymbolKind.Field, + Tags = new[] { SymbolTag.Deprecated }, + Range = new Range( new Position(lineIndex, currentCharacter), - new Position(lineIndex, currentCharacter + part.Length)), - Name = part - }); + new Position(lineIndex, currentCharacter + part.Length) + ), + SelectionRange = + new Range( + new Position(lineIndex, currentCharacter), + new Position(lineIndex, currentCharacter + part.Length) + ), + Name = part + } + ); currentCharacter += part.Length + 1; } } @@ -157,7 +152,7 @@ public override async Task Handle(Do } } - class MyWorkspaceSymbolsHandler : WorkspaceSymbolsHandler + internal class MyWorkspaceSymbolsHandler : WorkspaceSymbolsHandler { private readonly IServerWorkDoneManager _manager; private readonly IServerWorkDoneManager _serverWorkDoneManager; @@ -165,68 +160,86 @@ class MyWorkspaceSymbolsHandler : WorkspaceSymbolsHandler private readonly ILogger logger; public MyWorkspaceSymbolsHandler(IServerWorkDoneManager serverWorkDoneManager, IProgressManager progressManager, ILogger logger) : - base(new WorkspaceSymbolRegistrationOptions() { }) + base(new WorkspaceSymbolRegistrationOptions()) { _serverWorkDoneManager = serverWorkDoneManager; _progressManager = progressManager; this.logger = logger; } - public override async Task> Handle(WorkspaceSymbolParams request, - CancellationToken cancellationToken) + public override async Task> Handle( + WorkspaceSymbolParams request, + CancellationToken cancellationToken + ) { - using var reporter = _serverWorkDoneManager.For(request, new WorkDoneProgressBegin() { - Cancellable = true, - Message = "This might take a while...", - Title = "Some long task....", - Percentage = 0 - }); + using var reporter = _serverWorkDoneManager.For( + request, new WorkDoneProgressBegin { + Cancellable = true, + Message = "This might take a while...", + Title = "Some long task....", + Percentage = 0 + } + ); using var partialResults = _progressManager.For(request, cancellationToken); if (partialResults != null) { await Task.Delay(2000, cancellationToken); - reporter.OnNext(new WorkDoneProgressReport() { - Cancellable = true, - Percentage = 20 - }); + reporter.OnNext( + new WorkDoneProgressReport { + Cancellable = true, + Percentage = 20 + } + ); await Task.Delay(500, cancellationToken); - reporter.OnNext(new WorkDoneProgressReport() { - Cancellable = true, - Percentage = 40 - }); + reporter.OnNext( + new WorkDoneProgressReport { + Cancellable = true, + Percentage = 40 + } + ); await Task.Delay(500, cancellationToken); - reporter.OnNext(new WorkDoneProgressReport() { - Cancellable = true, - Percentage = 50 - }); + reporter.OnNext( + new WorkDoneProgressReport { + Cancellable = true, + Percentage = 50 + } + ); await Task.Delay(500, cancellationToken); - partialResults.OnNext(new[] { - new SymbolInformation() { - ContainerName = "Partial Container", - Deprecated = true, - Kind = SymbolKind.Constant, - Location = new Location() { - Range = new OmniSharp.Extensions.LanguageServer.Protocol.Models.Range(new Position(2, 1), - new Position(2, 10)) { } - }, - Name = "Partial name" + partialResults.OnNext( + new[] { + new SymbolInformation { + ContainerName = "Partial Container", + Deprecated = true, + Kind = SymbolKind.Constant, + Location = new Location { + Range = new Range( + new Position(2, 1), + new Position(2, 10) + ) + }, + Name = "Partial name" + } } - }); + ); - reporter.OnNext(new WorkDoneProgressReport() { - Cancellable = true, - Percentage = 70 - }); + reporter.OnNext( + new WorkDoneProgressReport { + Cancellable = true, + Percentage = 70 + } + ); await Task.Delay(500, cancellationToken); - reporter.OnNext(new WorkDoneProgressReport() { - Cancellable = true, - Percentage = 90 - }); + reporter.OnNext( + new WorkDoneProgressReport { + Cancellable = true, + Percentage = 90 + } + ); partialResults.OnCompleted(); return new SymbolInformation[] { }; @@ -235,13 +248,15 @@ public override async Task> Handle(WorkspaceSymbolP try { return new[] { - new SymbolInformation() { + new SymbolInformation { ContainerName = "Container", Deprecated = true, Kind = SymbolKind.Constant, - Location = new Location() { - Range = new OmniSharp.Extensions.LanguageServer.Protocol.Models.Range(new Position(1, 1), - new Position(1, 10)) { } + Location = new Location { + Range = new Range( + new Position(1, 1), + new Position(1, 10) + ) }, Name = "name" } @@ -249,10 +264,12 @@ public override async Task> Handle(WorkspaceSymbolP } finally { - reporter.OnNext(new WorkDoneProgressReport() { - Cancellable = true, - Percentage = 100 - }); + reporter.OnNext( + new WorkDoneProgressReport { + Cancellable = true, + Percentage = 100 + } + ); } } } diff --git a/src/Client/LangaugeClientRegistry.cs b/src/Client/LangaugeClientRegistry.cs index 836c6bacb..3d0655c83 100644 --- a/src/Client/LangaugeClientRegistry.cs +++ b/src/Client/LangaugeClientRegistry.cs @@ -6,10 +6,11 @@ namespace OmniSharp.Extensions.LanguageServer.Client { - class LangaugeClientRegistry : InterimLanguageProtocolRegistry, ILanguageClientRegistry + internal class LangaugeClientRegistry : InterimLanguageProtocolRegistry, ILanguageClientRegistry { public LangaugeClientRegistry(IServiceProvider serviceProvider, CompositeHandlersManager handlersManager, TextDocumentIdentifiers textDocumentIdentifiers) : base( - serviceProvider, handlersManager, textDocumentIdentifiers) + serviceProvider, handlersManager, textDocumentIdentifiers + ) { } } diff --git a/src/Client/LanguageClient.cs b/src/Client/LanguageClient.cs index ca01564ca..98ccfc4e6 100644 --- a/src/Client/LanguageClient.cs +++ b/src/Client/LanguageClient.cs @@ -8,22 +8,17 @@ using System.Threading; using System.Threading.Tasks; using DryIoc; -using MediatR; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; 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; using OmniSharp.Extensions.LanguageServer.Protocol.General; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; using OmniSharp.Extensions.LanguageServer.Shared; @@ -63,7 +58,7 @@ public class LanguageClient : JsonRpcServerBase, ILanguageClient internal static IContainer CreateContainer(LanguageClientOptions options, IServiceProvider outerServiceProvider) => JsonRpcServerContainer.Create(outerServiceProvider) - .AddLanguageClientInternals(options, outerServiceProvider); + .AddLanguageClientInternals(options, outerServiceProvider); public static LanguageClient Create(LanguageClientOptions options) => Create(options, null); public static LanguageClient Create(Action optionsAction) => Create(optionsAction, null); @@ -110,10 +105,7 @@ public static async Task From(LanguageClientOptions options, ISe /// /// /// - public static LanguageClient PreInit(Action optionsAction) - { - return Create(optionsAction); - } + public static LanguageClient PreInit(Action optionsAction) => Create(optionsAction); /// /// Create the server without connecting to the client @@ -122,10 +114,7 @@ public static LanguageClient PreInit(Action optionsAction /// /// /// - public static LanguageClient PreInit(LanguageClientOptions options) - { - return Create(options); - } + public static LanguageClient PreInit(LanguageClientOptions options) => Create(options); internal LanguageClient( Connection connection, @@ -151,7 +140,8 @@ internal LanguageClient( IRegistrationManager registrationManager, ILanguageClientWorkspaceFoldersManager languageClientWorkspaceFoldersManager, IEnumerable initializeDelegates, IEnumerable initializeHandlers, IEnumerable initializedDelegates, - IEnumerable initializedHandlers) : base(handlerCollection, responseRouter) + IEnumerable initializedHandlers + ) : base(handlerCollection, responseRouter) { _connection = connection; _capabilities = capabilities; @@ -359,10 +349,7 @@ private T UseOrTryAndFindCapability(Supports supports) public IObservable Start => _initializeComplete.AsObservable(); - (string method, TaskCompletionSource pendingTask) IResponseRouter.GetRequest(long id) - { - return _responseRouter.GetRequest(id); - } + (string method, TaskCompletionSource pendingTask) IResponseRouter.GetRequest(long id) => _responseRouter.GetRequest(id); public Task WasStarted => _initializeComplete.ToTask(); @@ -384,30 +371,31 @@ public IDisposable Register(Action registryAction) static IEnumerable GetUniqueHandlers(CompositeDisposable disposable) { return disposable.OfType() - .Select(z => z.Handler) - .OfType() - .Concat(disposable.OfType().SelectMany(GetUniqueHandlers)) - .Concat(disposable.OfType().SelectMany(GetLspHandlers)) - .Distinct(); + .Select(z => z.Handler) + .OfType() + .Concat(disposable.OfType().SelectMany(GetUniqueHandlers)) + .Concat(disposable.OfType().SelectMany(GetLspHandlers)) + .Distinct(); } + static IEnumerable GetLspHandlers(LspHandlerDescriptorDisposable disposable) { return disposable.Descriptors - .Select(z => z.Handler) - .OfType() - .Distinct(); + .Select(z => z.Handler) + .OfType() + .Distinct(); } Observable.Concat( GetUniqueHandlers(result) - .Select(handler => Observable.FromAsync((ct) => handler.OnInitialize(this, ClientSettings, ct))) - .Merge(), + .Select(handler => Observable.FromAsync(ct => handler.OnInitialize(this, ClientSettings, ct))) + .Merge(), GetUniqueHandlers(result) - .Select(handler => Observable.FromAsync((ct) => handler.OnInitialized(this, ClientSettings, ServerSettings, ct))) - .Merge(), + .Select(handler => Observable.FromAsync(ct => handler.OnInitialized(this, ClientSettings, ServerSettings, ct))) + .Merge(), GetUniqueHandlers(result) - .Select(handler => Observable.FromAsync((ct) => handler.OnStarted(this, ct))) - .Merge() + .Select(handler => Observable.FromAsync(ct => handler.OnStarted(this, ct))) + .Merge() ).Subscribe(); } diff --git a/src/Client/LanguageClientOptions.cs b/src/Client/LanguageClientOptions.cs index 75202e49c..84151d878 100644 --- a/src/Client/LanguageClientOptions.cs +++ b/src/Client/LanguageClientOptions.cs @@ -1,30 +1,19 @@ using System; using System.Collections.Generic; -using System.IO.Pipelines; -using System.Reactive.Disposables; -using System.Reflection; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client; 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 OmniSharp.Extensions.LanguageServer.Shared; -using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; namespace OmniSharp.Extensions.LanguageServer.Client { public class LanguageClientOptions : LanguageProtocolRpcOptionsBase, ILanguageClientRegistry { - public ClientCapabilities ClientCapabilities { get; set; } = new ClientCapabilities() { + public ClientCapabilities ClientCapabilities { get; set; } = new ClientCapabilities { Experimental = new Dictionary(), Window = new WindowClientCapabilities(), Workspace = new WorkspaceClientCapabilities(), @@ -49,62 +38,98 @@ public string RootPath public ILspClientReceiver Receiver { get; set; } = new LspClientReceiver(); - ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options) => AddHandler(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options) => + AddHandler(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => AddHandler(method, handlerFunc, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => + AddHandler(method, handlerFunc, options); ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandlers(params IJsonRpcHandler[] handlers) => AddHandlers(handlers); - ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => AddHandler(handlerFunc, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => + AddHandler(handlerFunc, options); ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptions options) => AddHandler(handler, options); ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerOptions options) => AddHandler(options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerOptions options) => AddHandler(method, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerOptions options) => + AddHandler(method, options); ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandler(Type type, JsonRpcHandlerOptions options) => AddHandler(type, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, Type type, JsonRpcHandlerOptions options) => AddHandler(method, type, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, Type type, JsonRpcHandlerOptions options) => + AddHandler(method, type, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnJsonRequest(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions options) => + OnJsonRequest(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnJsonRequest(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnJsonRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnJsonRequest(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry. + OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => + OnRequest(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnNotification( + string method, Action handler, JsonRpcHandlerOptions options + ) => OnNotification(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions options) => + OnJsonNotification(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnJsonNotification(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Func handler, JsonRpcHandlerOptions options) => + OnJsonNotification(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification( + string method, Action handler, JsonRpcHandlerOptions options + ) => OnJsonNotification(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, JsonRpcHandlerOptions options) => + OnNotification(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnNotification( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnNotification(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry. + OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, JsonRpcHandlerOptions options) => + OnNotification(method, handler, options); - ILanguageClientRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageClientRegistry IJsonRpcHandlerRegistry. + OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + + ILanguageClientRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => + OnNotification(method, handler, options); public override IRequestProcessIdentifier RequestProcessIdentifier { get; set; } } diff --git a/src/Client/LanguageClientOptionsExtensions.cs b/src/Client/LanguageClientOptionsExtensions.cs index e9fa55c02..4d50017f4 100644 --- a/src/Client/LanguageClientOptionsExtensions.cs +++ b/src/Client/LanguageClientOptionsExtensions.cs @@ -1,19 +1,12 @@ using System; -using System.IO; -using System.IO.Pipelines; -using System.Reflection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Nerdbank.Streams; -using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Shared; -using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; +using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace OmniSharp.Extensions.LanguageServer.Client { @@ -25,8 +18,10 @@ public static LanguageClientOptions WithSerializer(this LanguageClientOptions op return options; } - public static LanguageClientOptions WithReceiver(this LanguageClientOptions options, - ILspClientReceiver serverReceiver) + public static LanguageClientOptions WithReceiver( + this LanguageClientOptions options, + ILspClientReceiver serverReceiver + ) { options.Receiver = serverReceiver; return options; @@ -58,7 +53,7 @@ public static LanguageClientOptions WithWorkspaceFolder(this LanguageClientOptio public static LanguageClientOptions WithWorkspaceFolder(this LanguageClientOptions options, DocumentUri documentUri, string name) { - options.Services.AddSingleton(new WorkspaceFolder() { Name = name, Uri = documentUri}); + options.Services.AddSingleton(new WorkspaceFolder { Name = name, Uri = documentUri }); return options; } @@ -68,8 +63,10 @@ public static LanguageClientOptions WithTrace(this LanguageClientOptions options return options; } - public static LanguageClientOptions WithInitializationOptions(this LanguageClientOptions options, - object initializationOptions) + public static LanguageClientOptions WithInitializationOptions( + this LanguageClientOptions options, + object initializationOptions + ) { options.InitializationOptions = initializationOptions; return options; @@ -82,6 +79,7 @@ public static LanguageClientOptions WithCapability(this LanguageClientOptions op { options.Services.AddSingleton(item); } + return options; } @@ -110,8 +108,10 @@ public static LanguageClientOptions OnStarted(this LanguageClientOptions options return options; } - public static LanguageClientOptions ConfigureLogging(this LanguageClientOptions options, - Action builderAction) + public static LanguageClientOptions ConfigureLogging( + this LanguageClientOptions options, + Action builderAction + ) { options.LoggingBuilderAction = builderAction; return options; @@ -123,8 +123,10 @@ public static LanguageClientOptions AddDefaultLoggingProvider(this LanguageClien return options; } - public static LanguageClientOptions ConfigureConfiguration(this LanguageClientOptions options, - Action builderAction) + public static LanguageClientOptions ConfigureConfiguration( + this LanguageClientOptions options, + Action builderAction + ) { options.ConfigurationBuilderAction = builderAction; return options; diff --git a/src/Client/LanguageClientRegistrationManager.cs b/src/Client/LanguageClientRegistrationManager.cs index b6d0640aa..03399ff75 100644 --- a/src/Client/LanguageClientRegistrationManager.cs +++ b/src/Client/LanguageClientRegistrationManager.cs @@ -9,17 +9,17 @@ using MediatR; using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; +using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; using OmniSharp.Extensions.LanguageServer.Shared; -using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; namespace OmniSharp.Extensions.LanguageServer.Client { - class LanguageClientRegistrationManager : IRegisterCapabilityHandler, IUnregisterCapabilityHandler, IRegistrationManager, IDisposable + internal class LanguageClientRegistrationManager : IRegisterCapabilityHandler, IUnregisterCapabilityHandler, IRegistrationManager, IDisposable { private readonly ISerializer _serializer; private readonly ILogger _logger; @@ -62,7 +62,8 @@ Task IRequestHandler.Handle(UnregistrationPara public void RegisterCapabilities(ServerCapabilities serverCapabilities) { foreach (var registrationOptions in LspHandlerDescriptorHelpers.GetStaticRegistrationOptions( - serverCapabilities)) + serverCapabilities + )) { var descriptor = LspHandlerTypeDescriptorHelper.GetHandlerTypeForRegistrationOptions(registrationOptions); if (descriptor == null) @@ -71,12 +72,12 @@ public void RegisterCapabilities(ServerCapabilities serverCapabilities) continue; } - var reg = new Registration() { + var reg = new Registration { Id = registrationOptions.Id, Method = descriptor.Method, RegisterOptions = registrationOptions }; - _registrations.AddOrUpdate(registrationOptions.Id, (x) => reg, (a, b) => reg); + _registrations.AddOrUpdate(registrationOptions.Id, x => reg, (a, b) => reg); } if (serverCapabilities.Workspace == null) @@ -85,8 +86,10 @@ public void RegisterCapabilities(ServerCapabilities serverCapabilities) return; } - foreach (var registrationOptions in LspHandlerDescriptorHelpers.GetStaticRegistrationOptions(serverCapabilities - .Workspace)) + foreach (var registrationOptions in LspHandlerDescriptorHelpers.GetStaticRegistrationOptions( + serverCapabilities + .Workspace + )) { var descriptor = LspHandlerTypeDescriptorHelper.GetHandlerTypeForRegistrationOptions(registrationOptions); if (descriptor == null) @@ -95,12 +98,12 @@ public void RegisterCapabilities(ServerCapabilities serverCapabilities) continue; } - var reg = new Registration() { + var reg = new Registration { Id = registrationOptions.Id, Method = descriptor.Method, RegisterOptions = registrationOptions }; - _registrations.AddOrUpdate(registrationOptions.Id, (x) => reg, (a, b) => reg); + _registrations.AddOrUpdate(registrationOptions.Id, x => reg, (a, b) => reg); } } @@ -117,18 +120,18 @@ private void Register(Registration registration) var typeDescriptor = LspHandlerTypeDescriptorHelper.GetHandlerTypeDescriptor(registration.Method); if (typeDescriptor == null) { - _registrations.AddOrUpdate(registration.Id, (x) => registration, (a, b) => registration); + _registrations.AddOrUpdate(registration.Id, x => registration, (a, b) => registration); return; } - var deserializedRegistration = new Registration() { + var deserializedRegistration = new Registration { Id = registration.Id, Method = registration.Method, RegisterOptions = registration.RegisterOptions is JToken token ? token.ToObject(typeDescriptor.RegistrationType, _serializer.JsonSerializer) : registration.RegisterOptions }; - _registrations.AddOrUpdate(deserializedRegistration.Id, (x) => deserializedRegistration, (a, b) => deserializedRegistration); + _registrations.AddOrUpdate(deserializedRegistration.Id, x => deserializedRegistration, (a, b) => deserializedRegistration); } public IObservable> Registrations => _registrationSubject.AsObservable(); @@ -138,16 +141,19 @@ private void Register(Registration registration) public IEnumerable GetRegistrationsMatchingSelector(DocumentSelector documentSelector) => _registrations - .Select(z => z.Value) - .Where(x => x.RegisterOptions is ITextDocumentRegistrationOptions ro && ro.DocumentSelector - .Join(documentSelector, - z => z.HasLanguage ? z.Language : - z.HasScheme ? z.Scheme : - z.HasPattern ? z.Pattern : string.Empty, - z => z.HasLanguage ? z.Language : - z.HasScheme ? z.Scheme : - z.HasPattern ? z.Pattern : string.Empty, (a, b) => a) - .Any(x => x.HasLanguage || x.HasPattern || x.HasScheme) + .Select(z => z.Value) + .Where( + x => x.RegisterOptions is ITextDocumentRegistrationOptions ro && ro.DocumentSelector + .Join( + documentSelector, + z => z.HasLanguage ? z.Language : + z.HasScheme ? z.Scheme : + z.HasPattern ? z.Pattern : string.Empty, + z => z.HasLanguage ? z.Language : + z.HasScheme ? z.Scheme : + z.HasPattern ? z.Pattern : string.Empty, (a, b) => a + ) + .Any(x => x.HasLanguage || x.HasPattern || x.HasScheme) ); public void Dispose() => _registrationSubject.Dispose(); diff --git a/src/Client/LanguageClientResolver.cs b/src/Client/LanguageClientResolver.cs index 8e7a39251..3370a6f1d 100644 --- a/src/Client/LanguageClientResolver.cs +++ b/src/Client/LanguageClientResolver.cs @@ -35,4 +35,4 @@ public void Dispose() foreach (var item in _clients.Values) item.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Client/LanguageClientServiceCollectionExtensions.cs b/src/Client/LanguageClientServiceCollectionExtensions.cs index c6c2363d6..d20569210 100644 --- a/src/Client/LanguageClientServiceCollectionExtensions.cs +++ b/src/Client/LanguageClientServiceCollectionExtensions.cs @@ -23,7 +23,7 @@ internal static IContainer AddLanguageClientInternals(this IContainer container, throw new ArgumentException("Receiver is missing!", nameof(options)); } - container = container.AddLanguageProtocolInternals(options); + container = container.AddLanguageProtocolInternals(options); container.RegisterInstance(options.ClientCapabilities); container.RegisterInstanceMany(options.Receiver); @@ -33,7 +33,7 @@ internal static IContainer AddLanguageClientInternals(this IContainer container, } else { - container.RegisterDelegate(_ => new OnUnhandledExceptionHandler(e => _.GetRequiredService().Shutdown()), reuse: Reuse.Singleton); + container.RegisterDelegate(_ => new OnUnhandledExceptionHandler(e => _.GetRequiredService().Shutdown()), Reuse.Singleton); } container.RegisterMany(serviceTypeCondition: type => type.Name.Contains(nameof(TextDocumentLanguageClient)), reuse: Reuse.Singleton); @@ -45,15 +45,18 @@ internal static IContainer AddLanguageClientInternals(this IContainer container, container.RegisterMany(serviceTypeCondition: type => type == typeof(ILanguageClient) || type == typeof(LanguageClient), reuse: Reuse.Singleton); - container.RegisterInstance(options.ClientInfo ?? new ClientInfo() { - Name = Assembly.GetEntryAssembly()?.GetName().Name, - Version = Assembly.GetEntryAssembly()?.GetCustomAttribute() - ?.InformationalVersion ?? - Assembly.GetEntryAssembly()?.GetCustomAttribute()?.Version - }); + container.RegisterInstance( + options.ClientInfo ?? new ClientInfo { + Name = Assembly.GetEntryAssembly()?.GetName().Name, + Version = Assembly.GetEntryAssembly()?.GetCustomAttribute() + ?.InformationalVersion ?? + Assembly.GetEntryAssembly()?.GetCustomAttribute()?.Version + } + ); var providedConfiguration = options.Services.FirstOrDefault(z => z.ServiceType == typeof(IConfiguration) && z.ImplementationInstance is IConfiguration); - container.RegisterDelegate(_ => { + container.RegisterDelegate( + _ => { var builder = new ConfigurationBuilder(); var outerConfiguration = outerServiceProvider?.GetService(); if (outerConfiguration != null) @@ -69,21 +72,24 @@ internal static IContainer AddLanguageClientInternals(this IContainer container, //var didChangeConfigurationProvider = _.GetRequiredService(); return builder //.AddConfiguration(didChangeConfigurationProvider) - .Build(); + .Build(); }, - reuse: Reuse.Singleton); + Reuse.Singleton + ); - container.RegisterMany(reuse: Reuse.Singleton); - container.RegisterMany(serviceTypeCondition: type => options.WorkspaceFolders || type != typeof(IJsonRpcHandler), reuse: Reuse.Singleton); - container.RegisterMany(serviceTypeCondition: type => options.DynamicRegistration || type != typeof(IJsonRpcHandler), reuse: Reuse.Singleton); + container.RegisterMany(Reuse.Singleton); + container.RegisterMany( + serviceTypeCondition: type => options.WorkspaceFolders || type != typeof(IJsonRpcHandler), reuse: Reuse.Singleton + ); + container.RegisterMany( + serviceTypeCondition: type => options.DynamicRegistration || type != typeof(IJsonRpcHandler), reuse: Reuse.Singleton + ); return container; } - public static IServiceCollection AddLanguageClient(this IServiceCollection services, Action configureOptions = null) - { - return AddLanguageClient(services, Options.DefaultName, configureOptions); - } + public static IServiceCollection AddLanguageClient(this IServiceCollection services, Action configureOptions = null) => + AddLanguageClient(services, Options.DefaultName, configureOptions); public static IServiceCollection AddLanguageClient(this IServiceCollection services, string name, Action configureOptions = null) { @@ -93,15 +99,19 @@ public static IServiceCollection AddLanguageClient(this IServiceCollection servi { services.RemoveAll(); services.RemoveAll(); - services.AddSingleton(_ => - throw new NotSupportedException("LanguageClient has been registered multiple times, you must use LanguageClient instead")); - services.AddSingleton(_ => - throw new NotSupportedException("LanguageClient has been registered multiple times, you must use LanguageClient instead")); + services.AddSingleton( + _ => + throw new NotSupportedException("LanguageClient has been registered multiple times, you must use LanguageClient instead") + ); + services.AddSingleton( + _ => + throw new NotSupportedException("LanguageClient has been registered multiple times, you must use LanguageClient instead") + ); } services - .AddOptions() - .AddLogging(); + .AddOptions() + .AddLogging(); services.TryAddSingleton(); services.TryAddSingleton(_ => _.GetRequiredService().Get(name)); services.TryAddSingleton(_ => _.GetRequiredService().Get(name)); diff --git a/src/Client/LanguageClientWorkspaceFoldersManager.cs b/src/Client/LanguageClientWorkspaceFoldersManager.cs index 87c7ed4a1..efd59e76e 100644 --- a/src/Client/LanguageClientWorkspaceFoldersManager.cs +++ b/src/Client/LanguageClientWorkspaceFoldersManager.cs @@ -7,14 +7,14 @@ using System.Threading; using System.Threading.Tasks; using MediatR; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; namespace OmniSharp.Extensions.LanguageServer.Client { - class LanguageClientWorkspaceFoldersManager : ILanguageClientWorkspaceFoldersManager, IDisposable + internal class LanguageClientWorkspaceFoldersManager : ILanguageClientWorkspaceFoldersManager, IDisposable { private readonly IWorkspaceLanguageClient _client; private readonly ConcurrentDictionary _workspaceFolders; @@ -33,20 +33,12 @@ public LanguageClientWorkspaceFoldersManager(IWorkspaceLanguageClient client, IE } Task> IRequestHandler>. - Handle(WorkspaceFolderParams request, CancellationToken cancellationToken) - { - return Task.FromResult(new Container(_workspaceFolders.Values)); - } + Handle(WorkspaceFolderParams request, CancellationToken cancellationToken) => + Task.FromResult(new Container(_workspaceFolders.Values)); - public void Add(DocumentUri uri, string name) - { - Add(new WorkspaceFolder() {Name = name, Uri = uri}); - } + public void Add(DocumentUri uri, string name) => Add(new WorkspaceFolder { Name = name, Uri = uri }); - public void Add(WorkspaceFolder folder, params WorkspaceFolder[] workspaceFolders) - { - Add(new[] {folder}.Concat(workspaceFolders)); - } + public void Add(WorkspaceFolder folder, params WorkspaceFolder[] workspaceFolders) => Add(new[] { folder }.Concat(workspaceFolders)); public void Add(IEnumerable workspaceFolders) { @@ -61,28 +53,21 @@ public void Add(IEnumerable workspaceFolders) if (additions.Count == 0) return; - _client.DidChangeWorkspaceFolders(new DidChangeWorkspaceFoldersParams() { - Event = new WorkspaceFoldersChangeEvent() { - Added = new Container(additions) + _client.DidChangeWorkspaceFolders( + new DidChangeWorkspaceFoldersParams { + Event = new WorkspaceFoldersChangeEvent { + Added = new Container(additions) + } } - }); + ); _workspaceFoldersSubject.OnNext(_workspaceFolders.Values); } - public void Remove(DocumentUri name) - { - Remove(_workspaceFolders.Values.Where(z => z.Uri == name)); - } + public void Remove(DocumentUri name) => Remove(_workspaceFolders.Values.Where(z => z.Uri == name)); - public void Remove(string name) - { - Remove(_workspaceFolders.Values.Where(z => z.Name == name)); - } + public void Remove(string name) => Remove(_workspaceFolders.Values.Where(z => z.Name == name)); - public void Remove(WorkspaceFolder folder, params WorkspaceFolder[] workspaceFolders) - { - Remove(new [] { folder }.Concat(workspaceFolders)); - } + public void Remove(WorkspaceFolder folder, params WorkspaceFolder[] workspaceFolders) => Remove(new[] { folder }.Concat(workspaceFolders)); public void Remove(IEnumerable items) { @@ -97,11 +82,13 @@ public void Remove(IEnumerable items) if (removals.Count == 0) return; - _client.DidChangeWorkspaceFolders(new DidChangeWorkspaceFoldersParams() { - Event = new WorkspaceFoldersChangeEvent() { - Removed = new Container(removals) + _client.DidChangeWorkspaceFolders( + new DidChangeWorkspaceFoldersParams { + Event = new WorkspaceFoldersChangeEvent { + Removed = new Container(removals) + } } - }); + ); _workspaceFoldersSubject.OnNext(_workspaceFolders.Values); } @@ -109,9 +96,6 @@ public void Remove(IEnumerable items) public IEnumerable CurrentWorkspaceFolders => _workspaceFolders.Values; - public void Dispose() - { - _workspaceFoldersSubject?.Dispose(); - } + public void Dispose() => _workspaceFoldersSubject?.Dispose(); } } diff --git a/src/Client/LspClientReceiver.cs b/src/Client/LspClientReceiver.cs index b6143ab02..235b6649b 100644 --- a/src/Client/LspClientReceiver.cs +++ b/src/Client/LspClientReceiver.cs @@ -32,23 +32,22 @@ public override (IEnumerable results, bool hasResponse) GetRequests(JToke newResults.Add(item); } else if (item.IsNotification && - HandlerTypeDescriptorHelper.IsMethodName(item.Notification.Method, + HandlerTypeDescriptorHelper.IsMethodName( + item.Notification.Method, typeof(IShowMessageHandler), typeof(ILogMessageHandler), - typeof(ITelemetryEventHandler)) + typeof(ITelemetryEventHandler) + ) ) { newResults.Add(item); } } - return (newResults, hasResponse); + return ( newResults, hasResponse ); } - public void Initialized() - { - _initialized = true; - } + public void Initialized() => _initialized = true; public override bool ShouldFilterOutput(object value) { diff --git a/src/Dap.Client/DebugAdapterClient.cs b/src/Dap.Client/DebugAdapterClient.cs index 8243467f9..94a2a9c79 100644 --- a/src/Dap.Client/DebugAdapterClient.cs +++ b/src/Dap.Client/DebugAdapterClient.cs @@ -2,15 +2,12 @@ using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; -using System.Reactive.Linq; using System.Reactive.Subjects; using System.Reactive.Threading.Tasks; -using System.Reflection; using System.Threading; using System.Threading.Tasks; using DryIoc; using MediatR; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.DebugAdapter.Protocol.Client; @@ -18,8 +15,6 @@ using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; using OmniSharp.Extensions.DebugAdapter.Shared; using OmniSharp.Extensions.JsonRpc; -using IOutputHandler = OmniSharp.Extensions.JsonRpc.IOutputHandler; -using OutputHandler = OmniSharp.Extensions.JsonRpc.OutputHandler; namespace OmniSharp.Extensions.DebugAdapter.Client { @@ -43,10 +38,11 @@ public class DebugAdapterClient : JsonRpcServerBase, IDebugAdapterClient, IDebug internal static IContainer CreateContainer(DebugAdapterClientOptions options, IServiceProvider outerServiceProvider) => JsonRpcServerContainer.Create(outerServiceProvider) - .AddDebugAdapterClientInternals(options, 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(Action optionsAction, IServiceProvider outerServiceProvider) { var options = new DebugAdapterClientOptions(); @@ -54,14 +50,22 @@ 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) => + CreateContainer(options, outerServiceProvider).Resolve(); 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(Action optionsAction, CancellationToken cancellationToken) => From(optionsAction, null, cancellationToken); - public static Task From(DebugAdapterClientOptions options, IServiceProvider outerServiceProvider) => From(options, outerServiceProvider, CancellationToken.None); - public static Task From(Action optionsAction, IServiceProvider outerServiceProvider) => From(optionsAction, outerServiceProvider, CancellationToken.None); + + public static Task From(Action optionsAction, CancellationToken cancellationToken) => + From(optionsAction, null, cancellationToken); + + public static Task From(DebugAdapterClientOptions options, IServiceProvider outerServiceProvider) => + 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, CancellationToken cancellationToken) { var options = new DebugAdapterClientOptions(); @@ -91,7 +95,8 @@ internal DebugAdapterClient( IEnumerable initializeHandlers, IEnumerable initializedDelegates, IEnumerable initializedHandlers, - IEnumerable startedHandlers) : base(collection, responseRouter) + IEnumerable startedHandlers + ) : base(collection, responseRouter) { _settingsBag = settingsBag; ClientSettings = clientSettings; @@ -187,6 +192,7 @@ public InitializeResponse ServerSettings get => _settingsBag.ServerSettings; private set => _settingsBag.ServerSettings = value; } + public IDebugAdapterClientProgressManager ProgressManager { get; } public void Dispose() diff --git a/src/Dap.Client/DebugAdapterClientOptions.cs b/src/Dap.Client/DebugAdapterClientOptions.cs index 5a3ae221b..4bc68a0d2 100644 --- a/src/Dap.Client/DebugAdapterClientOptions.cs +++ b/src/Dap.Client/DebugAdapterClientOptions.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; @@ -25,61 +24,106 @@ public class DebugAdapterClientOptions : DebugAdapterRpcOptionsBase.AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options) => AddHandler(method, handler, options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => AddHandler(method, handlerFunc, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options) => + AddHandler(method, handler, options); + + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry. + AddHandler(string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => AddHandler(method, handlerFunc, options); IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandlers(params IJsonRpcHandler[] handlers) => AddHandlers(handlers); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => AddHandler(handlerFunc, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => + AddHandler(handlerFunc, options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptions options) => AddHandler(handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptions options) => + AddHandler(handler, options); IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerOptions options) => AddHandler(options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerOptions options) => AddHandler(method, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerOptions options) => + AddHandler(method, options); IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.AddHandler(Type type, JsonRpcHandlerOptions options) => 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) => + AddHandler(method, type, options); + + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnJsonRequest(method, handler, options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnJsonRequest(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnJsonRequest(method, handler, options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnJsonRequest(method, handler, options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnRequest(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 + ) => 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) => + OnJsonNotification(method, handler, options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnJsonNotification(method, handler, options); - IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); + IDebugAdapterClientRegistry IJsonRpcHandlerRegistry.OnJsonNotification( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnJsonNotification(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 + ) => OnJsonNotification(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 + ) => 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 + ) => 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 + ) => 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) => + 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 + ) => 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) => + OnNotification(method, handler, options); } } diff --git a/src/Dap.Client/DebugAdapterClientOptionsExtensions.cs b/src/Dap.Client/DebugAdapterClientOptionsExtensions.cs index 9fff8ac96..4b3f8236c 100644 --- a/src/Dap.Client/DebugAdapterClientOptionsExtensions.cs +++ b/src/Dap.Client/DebugAdapterClientOptionsExtensions.cs @@ -2,16 +2,13 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.DebugAdapter.Protocol.Client; -using OmniSharp.Extensions.DebugAdapter.Protocol.Server; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Client { public static class DebugAdapterClientOptionsExtensions { - public static DebugAdapterClientOptions WithSerializer(this DebugAdapterClientOptions options, ISerializer serializer) { options.Serializer = serializer; @@ -42,8 +39,10 @@ public static DebugAdapterClientOptions OnStarted(this DebugAdapterClientOptions return options; } - public static DebugAdapterClientOptions ConfigureLogging(this DebugAdapterClientOptions options, - Action builderAction) + public static DebugAdapterClientOptions ConfigureLogging( + this DebugAdapterClientOptions options, + Action builderAction + ) { options.LoggingBuilderAction = builderAction; return options; @@ -55,8 +54,10 @@ public static DebugAdapterClientOptions AddDefaultLoggingProvider(this DebugAdap return options; } - public static DebugAdapterClientOptions ConfigureConfiguration(this DebugAdapterClientOptions options, - Action builderAction) + public static DebugAdapterClientOptions ConfigureConfiguration( + this DebugAdapterClientOptions options, + Action builderAction + ) { options.ConfigurationBuilderAction = builderAction; return options; diff --git a/src/Dap.Client/DebugAdapterClientProgressManager.cs b/src/Dap.Client/DebugAdapterClientProgressManager.cs index 3ceb7ce15..d6ff26e9e 100644 --- a/src/Dap.Client/DebugAdapterClientProgressManager.cs +++ b/src/Dap.Client/DebugAdapterClientProgressManager.cs @@ -14,11 +14,13 @@ namespace OmniSharp.Extensions.DebugAdapter.Client { - class DebugAdapterClientProgressManager : IProgressStartHandler, IProgressUpdateHandler, IProgressEndHandler, IDebugAdapterClientProgressManager, IDisposable + internal class DebugAdapterClientProgressManager : IProgressStartHandler, IProgressUpdateHandler, IProgressEndHandler, IDebugAdapterClientProgressManager, IDisposable { private readonly IObserver _observer; private readonly CompositeDisposable _disposable = new CompositeDisposable(); - private readonly ConcurrentDictionary _activeObservables = new ConcurrentDictionary(EqualityComparer.Default); + + private readonly ConcurrentDictionary _activeObservables = + new ConcurrentDictionary(EqualityComparer.Default); public DebugAdapterClientProgressManager() { diff --git a/src/Dap.Client/DebugAdapterClientResolver.cs b/src/Dap.Client/DebugAdapterClientResolver.cs index f02b80d22..f26fff874 100644 --- a/src/Dap.Client/DebugAdapterClientResolver.cs +++ b/src/Dap.Client/DebugAdapterClientResolver.cs @@ -35,4 +35,4 @@ public void Dispose() foreach (var item in _servers.Values) item.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Dap.Client/DebugAdapterClientServiceCollectionExtensions.cs b/src/Dap.Client/DebugAdapterClientServiceCollectionExtensions.cs index 5b7cd1069..48bebab01 100644 --- a/src/Dap.Client/DebugAdapterClientServiceCollectionExtensions.cs +++ b/src/Dap.Client/DebugAdapterClientServiceCollectionExtensions.cs @@ -24,35 +24,42 @@ internal static IContainer AddDebugAdapterClientInternals(this IContainer contai } else { - container.RegisterDelegate(_ => new OnUnhandledExceptionHandler(e => { }), reuse: Reuse.Singleton); + container.RegisterDelegate(_ => new OnUnhandledExceptionHandler(e => { }), Reuse.Singleton); } container.RegisterInstance>(new ValueOptionsFactory(options)); - container.RegisterMany(serviceTypeCondition: type => type == typeof(IDebugAdapterClient) || type == typeof(DebugAdapterClient), reuse: Reuse.Singleton); + container.RegisterMany( + serviceTypeCondition: type => type == typeof(IDebugAdapterClient) || type == typeof(DebugAdapterClient), reuse: Reuse.Singleton + ); - container.RegisterInstance(new InitializeRequestArguments() { - Locale = options.Locale, - AdapterId = options.AdapterId, - ClientId = options.ClientId, - ClientName = options.ClientName, - PathFormat = options.PathFormat, - ColumnsStartAt1 = options.ColumnsStartAt1, - LinesStartAt1 = options.LinesStartAt1, - SupportsMemoryReferences = options.SupportsMemoryReferences, - SupportsProgressReporting = options.SupportsProgressReporting, - SupportsVariablePaging = options.SupportsVariablePaging, - SupportsVariableType = options.SupportsVariableType, - SupportsRunInTerminalRequest = options.SupportsRunInTerminalRequest, - }); + container.RegisterInstance( + new InitializeRequestArguments { + Locale = options.Locale, + AdapterId = options.AdapterId, + ClientId = options.ClientId, + ClientName = options.ClientName, + PathFormat = options.PathFormat, + ColumnsStartAt1 = options.ColumnsStartAt1, + LinesStartAt1 = options.LinesStartAt1, + SupportsMemoryReferences = options.SupportsMemoryReferences, + SupportsProgressReporting = options.SupportsProgressReporting, + SupportsVariablePaging = options.SupportsVariablePaging, + SupportsVariableType = options.SupportsVariableType, + SupportsRunInTerminalRequest = options.SupportsRunInTerminalRequest, + } + ); container.RegisterInstance(options.RequestProcessIdentifier); container.RegisterMany(nonPublicServiceTypes: true, reuse: Reuse.Singleton); - container.RegisterMany(serviceTypeCondition: type => type == typeof(IDebugAdapterClient) || type == typeof(DebugAdapterClient), reuse: Reuse.Singleton); + container.RegisterMany( + serviceTypeCondition: type => type == typeof(IDebugAdapterClient) || type == typeof(DebugAdapterClient), reuse: Reuse.Singleton + ); // container. var providedConfiguration = options.Services.FirstOrDefault(z => z.ServiceType == typeof(IConfiguration) && z.ImplementationInstance is IConfiguration); - container.RegisterDelegate(_ => { + container.RegisterDelegate( + _ => { var builder = new ConfigurationBuilder(); if (outerServiceProvider != null) { @@ -70,15 +77,14 @@ internal static IContainer AddDebugAdapterClientInternals(this IContainer contai return builder.Build(); }, - reuse: Reuse.Singleton); + Reuse.Singleton + ); return container; } - public static IServiceCollection AddDebugAdapterClient(this IServiceCollection services, Action configureOptions = null) - { - return AddDebugAdapterClient(services, Options.DefaultName, configureOptions); - } + public static IServiceCollection AddDebugAdapterClient(this IServiceCollection services, Action configureOptions = null) => + AddDebugAdapterClient(services, Options.DefaultName, configureOptions); public static IServiceCollection AddDebugAdapterClient(this IServiceCollection services, string name, Action configureOptions = null) { @@ -88,15 +94,19 @@ public static IServiceCollection AddDebugAdapterClient(this IServiceCollection s { services.RemoveAll(); services.RemoveAll(); - services.AddSingleton(_ => - throw new NotSupportedException("DebugAdapterClient has been registered multiple times, you must use DebugAdapterClient instead")); - services.AddSingleton(_ => - throw new NotSupportedException("DebugAdapterClient has been registered multiple times, you must use DebugAdapterClient instead")); + services.AddSingleton( + _ => + throw new NotSupportedException("DebugAdapterClient has been registered multiple times, you must use DebugAdapterClient instead") + ); + services.AddSingleton( + _ => + throw new NotSupportedException("DebugAdapterClient has been registered multiple times, you must use DebugAdapterClient instead") + ); } services - .AddOptions() - .AddLogging(); + .AddOptions() + .AddLogging(); services.TryAddSingleton(); services.TryAddSingleton(_ => _.GetRequiredService().Get(name)); services.TryAddSingleton(_ => _.GetRequiredService().Get(name)); diff --git a/src/Dap.Client/ProgressObservable.cs b/src/Dap.Client/ProgressObservable.cs index 8f4b5b7af..46c59c3c3 100644 --- a/src/Dap.Client/ProgressObservable.cs +++ b/src/Dap.Client/ProgressObservable.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Client { - class ProgressObservable : IProgressObservable, IObserver, IDisposable + internal class ProgressObservable : IProgressObservable, IObserver, IDisposable { private readonly CompositeDisposable _disposable; private readonly ReplaySubject _dataSubject; @@ -15,7 +15,7 @@ class ProgressObservable : IProgressObservable, IObserver, IDispo public ProgressObservable(ProgressToken token) { _dataSubject = new ReplaySubject(1); - _disposable = new CompositeDisposable() {Disposable.Create(_dataSubject.OnCompleted)}; + _disposable = new CompositeDisposable { Disposable.Create(_dataSubject.OnCompleted) }; ProgressToken = token; if (_dataSubject is IDisposable disposable) @@ -32,14 +32,8 @@ public ProgressObservable(ProgressToken token) public void OnNext(ProgressEvent value) => _dataSubject.OnNext(value); - public void Dispose() - { - _disposable.Dispose(); - } + public void Dispose() => _disposable.Dispose(); - public IDisposable Subscribe(IObserver observer) - { - return _disposable.IsDisposed ? Disposable.Empty : _dataSubject.Subscribe(observer); - } + public IDisposable Subscribe(IObserver observer) => _disposable.IsDisposed ? Disposable.Empty : _dataSubject.Subscribe(observer); } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Client/IDebugAdapterClient.cs b/src/Dap.Protocol/Client/IDebugAdapterClient.cs index 43ae18ebc..421049b67 100644 --- a/src/Dap.Protocol/Client/IDebugAdapterClient.cs +++ b/src/Dap.Protocol/Client/IDebugAdapterClient.cs @@ -1,8 +1,6 @@ using System; using System.Threading; using System.Threading.Tasks; -using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; -using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Client { diff --git a/src/Dap.Protocol/Client/IOnDebugAdapterClientInitialize.cs b/src/Dap.Protocol/Client/IOnDebugAdapterClientInitialize.cs index 7f0efa112..071a46e35 100644 --- a/src/Dap.Protocol/Client/IOnDebugAdapterClientInitialize.cs +++ b/src/Dap.Protocol/Client/IOnDebugAdapterClientInitialize.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Client { /// /// Gives your class or handler an opportunity to interact with - /// the before it is sent to the server + /// the before it is sent to the server /// public interface IOnDebugAdapterClientInitialize : IEventingHandler { diff --git a/src/Dap.Protocol/Client/IOnDebugAdapterClientInitialized.cs b/src/Dap.Protocol/Client/IOnDebugAdapterClientInitialized.cs index d3f2ef02e..b680aa13d 100644 --- a/src/Dap.Protocol/Client/IOnDebugAdapterClientInitialized.cs +++ b/src/Dap.Protocol/Client/IOnDebugAdapterClientInitialized.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Client { /// /// Gives your class or handler an opportunity to interact with - /// the and before it is processed by the client. + /// the and before it is processed by the client. /// public interface IOnDebugAdapterClientInitialized : IEventingHandler { diff --git a/src/Dap.Protocol/Client/IOnDebugAdapterClientStarted.cs b/src/Dap.Protocol/Client/IOnDebugAdapterClientStarted.cs index b9e603be6..6b102d818 100644 --- a/src/Dap.Protocol/Client/IOnDebugAdapterClientStarted.cs +++ b/src/Dap.Protocol/Client/IOnDebugAdapterClientStarted.cs @@ -6,7 +6,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Client { /// /// Gives your class or handler an opportunity to interact with - /// the after the connection has been established. + /// the after the connection has been established. /// public interface IOnDebugAdapterClientStarted : IEventingHandler { diff --git a/src/Dap.Protocol/Client/OnDebugAdapterClientInitializeDelegate.cs b/src/Dap.Protocol/Client/OnDebugAdapterClientInitializeDelegate.cs index 89ec9626a..9d40407b7 100644 --- a/src/Dap.Protocol/Client/OnDebugAdapterClientInitializeDelegate.cs +++ b/src/Dap.Protocol/Client/OnDebugAdapterClientInitializeDelegate.cs @@ -6,7 +6,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Client { /// /// Gives your class or handler an opportunity to interact with - /// the before it is sent to the server + /// the before it is sent to the server /// public delegate Task OnDebugAdapterClientInitializeDelegate(IDebugAdapterClient client, InitializeRequestArguments request, CancellationToken cancellationToken); } diff --git a/src/Dap.Protocol/Client/OnDebugAdapterClientInitializedDelegate.cs b/src/Dap.Protocol/Client/OnDebugAdapterClientInitializedDelegate.cs index 8d23243d7..f6682c6be 100644 --- a/src/Dap.Protocol/Client/OnDebugAdapterClientInitializedDelegate.cs +++ b/src/Dap.Protocol/Client/OnDebugAdapterClientInitializedDelegate.cs @@ -6,7 +6,9 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Client { /// /// Gives your class or handler an opportunity to interact with - /// the and before it is processed by the client. + /// the and before it is processed by the client. /// - public delegate Task OnDebugAdapterClientInitializedDelegate(IDebugAdapterClient client, InitializeRequestArguments request, InitializeResponse response, CancellationToken cancellationToken); + public delegate Task OnDebugAdapterClientInitializedDelegate( + IDebugAdapterClient client, InitializeRequestArguments request, InitializeResponse response, CancellationToken cancellationToken + ); } diff --git a/src/Dap.Protocol/Client/OnDebugAdapterClientStartedDelegate.cs b/src/Dap.Protocol/Client/OnDebugAdapterClientStartedDelegate.cs index 703637c23..7f69c56a6 100644 --- a/src/Dap.Protocol/Client/OnDebugAdapterClientStartedDelegate.cs +++ b/src/Dap.Protocol/Client/OnDebugAdapterClientStartedDelegate.cs @@ -5,7 +5,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Client { /// /// Gives your class or handler an opportunity to interact with - /// the after the connection has been established. + /// the after the connection has been established. /// public delegate Task OnDebugAdapterClientStartedDelegate(IDebugAdapterClient client, CancellationToken cancellationToken); } diff --git a/src/Dap.Protocol/DapReceiver.cs b/src/Dap.Protocol/DapReceiver.cs index ef1f42328..b74b343ce 100644 --- a/src/Dap.Protocol/DapReceiver.cs +++ b/src/Dap.Protocol/DapReceiver.cs @@ -1,17 +1,8 @@ using System; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using System.Reactive.Disposables; -using System.Reactive.Linq; -using System.Reactive.Subjects; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; -using MediatR; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.DebugAdapter.Protocol.Events; -using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Client; @@ -27,7 +18,7 @@ public class DapReceiver : IReceiver public (IEnumerable results, bool hasResponse) GetRequests(JToken container) { var result = GetRenor(container).ToArray(); - return (result, result.Any(z => z.IsResponse)); + return ( result, result.Any(z => z.IsResponse) ); } public bool IsValid(JToken container) @@ -42,7 +33,7 @@ public bool IsValid(JToken container) protected virtual IEnumerable GetRenor(JToken @object) { - if (!(@object is JObject request)) + if (!( @object is JObject request )) { yield return new InvalidRequest(null, "Not an object"); yield break; @@ -92,7 +83,7 @@ protected virtual IEnumerable GetRenor(JToken @object) // This makes it so that the cancel handler implementer must still return a positive response even if the request didn't make it through. if (ro.TryGetValue("requestId", out var requestId)) { - yield return new Notification(JsonRpcNames.CancelRequest, JObject.FromObject(new {id = requestId})); + yield return new Notification(JsonRpcNames.CancelRequest, JObject.FromObject(new { id = requestId })); ro.Remove("requestId"); } @@ -142,17 +133,14 @@ protected virtual IEnumerable GetRenor(JToken @object) throw new NotSupportedException($"Message type {messageType} is not supported"); } - public void Initialized() - { - _initialized = true; - } + public void Initialized() => _initialized = true; public bool ShouldFilterOutput(object value) { if (_initialized) return true; return value is OutgoingResponse || - (value is OutgoingNotification n && (n.Params is InitializedEvent)) || - (value is OutgoingRequest r && r.Params is InitializeRequestArguments); + value is OutgoingNotification n && n.Params is InitializedEvent || + value is OutgoingRequest r && r.Params is InitializeRequestArguments; } } } diff --git a/src/Dap.Protocol/DebugAdapterConverters/DapClientNotificationConverter.cs b/src/Dap.Protocol/DebugAdapterConverters/DapClientNotificationConverter.cs index 146b9cc2b..c4bd824c9 100644 --- a/src/Dap.Protocol/DebugAdapterConverters/DapClientNotificationConverter.cs +++ b/src/Dap.Protocol/DebugAdapterConverters/DapClientNotificationConverter.cs @@ -5,22 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.DebugAdapterConverters { - class DapClientNotificationConverter : JsonConverter + internal class DapClientNotificationConverter : JsonConverter { private readonly ISerializer _serializer; - public DapClientNotificationConverter(ISerializer serializer) - { - _serializer = serializer; - } + public DapClientNotificationConverter(ISerializer serializer) => _serializer = serializer; public override bool CanRead => false; - public override OutgoingNotification ReadJson(JsonReader reader, Type objectType, OutgoingNotification existingValue, - bool hasExistingValue, JsonSerializer serializer) - { + public override OutgoingNotification ReadJson( + JsonReader reader, Type objectType, OutgoingNotification existingValue, + bool hasExistingValue, JsonSerializer serializer + ) => throw new NotImplementedException(); - } public override void WriteJson(JsonWriter writer, OutgoingNotification value, JsonSerializer serializer) { @@ -36,6 +33,7 @@ public override void WriteJson(JsonWriter writer, OutgoingNotification value, Js writer.WritePropertyName("body"); serializer.Serialize(writer, value.Params); } + writer.WriteEndObject(); } } diff --git a/src/Dap.Protocol/DebugAdapterConverters/DapClientRequestConverter.cs b/src/Dap.Protocol/DebugAdapterConverters/DapClientRequestConverter.cs index 315eb7206..1b92d21c1 100644 --- a/src/Dap.Protocol/DebugAdapterConverters/DapClientRequestConverter.cs +++ b/src/Dap.Protocol/DebugAdapterConverters/DapClientRequestConverter.cs @@ -4,14 +4,15 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.DebugAdapterConverters { - class DapClientRequestConverter : JsonConverter + internal class DapClientRequestConverter : JsonConverter { public override bool CanRead => false; - public override OutgoingRequest ReadJson(JsonReader reader, Type objectType, OutgoingRequest existingValue, - bool hasExistingValue, JsonSerializer serializer) - { + + public override OutgoingRequest ReadJson( + JsonReader reader, Type objectType, OutgoingRequest existingValue, + bool hasExistingValue, JsonSerializer serializer + ) => throw new NotImplementedException(); - } public override void WriteJson(JsonWriter writer, OutgoingRequest value, JsonSerializer serializer) { @@ -27,6 +28,7 @@ public override void WriteJson(JsonWriter writer, OutgoingRequest value, JsonSer writer.WritePropertyName("arguments"); serializer.Serialize(writer, value.Params); } + writer.WriteEndObject(); } } diff --git a/src/Dap.Protocol/DebugAdapterConverters/DapClientResponseConverter.cs b/src/Dap.Protocol/DebugAdapterConverters/DapClientResponseConverter.cs index 7b425deed..19fb1692a 100644 --- a/src/Dap.Protocol/DebugAdapterConverters/DapClientResponseConverter.cs +++ b/src/Dap.Protocol/DebugAdapterConverters/DapClientResponseConverter.cs @@ -5,21 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.DebugAdapterConverters { - class DapClientResponseConverter : JsonConverter + internal class DapClientResponseConverter : JsonConverter { private readonly ISerializer _serializer; - public DapClientResponseConverter(ISerializer serializer) - { - _serializer = serializer; - } + public DapClientResponseConverter(ISerializer serializer) => _serializer = serializer; public override bool CanRead => false; - public override OutgoingResponse ReadJson(JsonReader reader, Type objectType, OutgoingResponse existingValue, - bool hasExistingValue, JsonSerializer serializer) - { + + public override OutgoingResponse ReadJson( + JsonReader reader, Type objectType, OutgoingResponse existingValue, + bool hasExistingValue, JsonSerializer serializer + ) => throw new NotImplementedException(); - } public override void WriteJson(JsonWriter writer, OutgoingResponse value, JsonSerializer serializer) { @@ -40,6 +38,7 @@ public override void WriteJson(JsonWriter writer, OutgoingResponse value, JsonSe writer.WritePropertyName("body"); serializer.Serialize(writer, value.Result); } + writer.WriteEndObject(); } } diff --git a/src/Dap.Protocol/DebugAdapterConverters/DapRpcErrorConverter.cs b/src/Dap.Protocol/DebugAdapterConverters/DapRpcErrorConverter.cs index 2aab3267b..564d23439 100644 --- a/src/Dap.Protocol/DebugAdapterConverters/DapRpcErrorConverter.cs +++ b/src/Dap.Protocol/DebugAdapterConverters/DapRpcErrorConverter.cs @@ -10,14 +10,11 @@ public class DapRpcErrorConverter : JsonConverter { private readonly ISerializer _serializer; - public DapRpcErrorConverter(ISerializer serializer) - { - _serializer = serializer; - } + public DapRpcErrorConverter(ISerializer serializer) => _serializer = serializer; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - if (!(value is RpcError error)) + if (!( value is RpcError error )) { throw new NotSupportedException($"{typeof(RpcError).FullName} was not found!"); } @@ -32,6 +29,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s writer.WritePropertyName("request_seq"); writer.WriteValue(error.Id); } + writer.WritePropertyName("success"); writer.WriteValue(false); writer.WritePropertyName("command"); diff --git a/src/Dap.Protocol/DebugAdapterRpcOptionsBase.cs b/src/Dap.Protocol/DebugAdapterRpcOptionsBase.cs index 8ffa61d7a..20d1acd43 100644 --- a/src/Dap.Protocol/DebugAdapterRpcOptionsBase.cs +++ b/src/Dap.Protocol/DebugAdapterRpcOptionsBase.cs @@ -8,10 +8,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol { public abstract class DebugAdapterRpcOptionsBase : JsonRpcServerOptionsBase where T : IJsonRpcHandlerRegistry { - public DebugAdapterRpcOptionsBase() - { - Services.AddLogging(builder => LoggingBuilderAction?.Invoke(builder)); - } + public DebugAdapterRpcOptionsBase() => Services.AddLogging(builder => LoggingBuilderAction?.Invoke(builder)); public ISerializer Serializer { get; set; } = new DapSerializer(); public override IRequestProcessIdentifier RequestProcessIdentifier { get; set; } = new ParallelRequestProcessIdentifier(); internal bool AddDefaultLoggingProvider { get; set; } diff --git a/src/Dap.Protocol/DebugAdapterSettingsBag.cs b/src/Dap.Protocol/DebugAdapterSettingsBag.cs index 51853225a..bb7a383b2 100644 --- a/src/Dap.Protocol/DebugAdapterSettingsBag.cs +++ b/src/Dap.Protocol/DebugAdapterSettingsBag.cs @@ -2,7 +2,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol { - class DebugAdapterSettingsBag : IDebugAdapterProtocolSettings + internal class DebugAdapterSettingsBag : IDebugAdapterProtocolSettings { public InitializeRequestArguments ClientSettings { get; internal set; } diff --git a/src/Dap.Protocol/Events/BreakpointEvent.cs b/src/Dap.Protocol/Events/BreakpointEvent.cs index e2c57568c..1fc39a242 100644 --- a/src/Dap.Protocol/Events/BreakpointEvent.cs +++ b/src/Dap.Protocol/Events/BreakpointEvent.cs @@ -1,6 +1,5 @@ -using System.Diagnostics; -using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events @@ -19,5 +18,4 @@ public class BreakpointEvent : IRequest /// public Breakpoint Breakpoint { get; set; } } - } diff --git a/src/Dap.Protocol/Events/BreakpointExtensions.cs b/src/Dap.Protocol/Events/BreakpointExtensions.cs index 437c883d6..3f19f24d6 100644 --- a/src/Dap.Protocol/Events/BreakpointExtensions.cs +++ b/src/Dap.Protocol/Events/BreakpointExtensions.cs @@ -6,10 +6,13 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - - [Parallel, Method(EventNames.Breakpoint, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] - public interface IBreakpointHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(EventNames.Breakpoint, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public interface IBreakpointHandler : IJsonRpcNotificationHandler + { + } public abstract class BreakpointHandler : IBreakpointHandler { diff --git a/src/Dap.Protocol/Events/CapabilitiesEvent.cs b/src/Dap.Protocol/Events/CapabilitiesEvent.cs index e5914cf0b..8215f0fd2 100644 --- a/src/Dap.Protocol/Events/CapabilitiesEvent.cs +++ b/src/Dap.Protocol/Events/CapabilitiesEvent.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events @@ -7,11 +7,9 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events [Method(EventNames.Capabilities, Direction.ServerToClient)] public class CapabilitiesEvent : IRequest { - /// /// The set of updated capabilities. /// public Capabilities Capabilities { get; set; } } - } diff --git a/src/Dap.Protocol/Events/CapabilitiesExtensions.cs b/src/Dap.Protocol/Events/CapabilitiesExtensions.cs index 056635252..3a4a3b5d0 100644 --- a/src/Dap.Protocol/Events/CapabilitiesExtensions.cs +++ b/src/Dap.Protocol/Events/CapabilitiesExtensions.cs @@ -6,8 +6,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - [Parallel, Method(EventNames.Capabilities, Direction.ServerToClient)] - [GenerateRequestMethods, GenerateHandlerMethods] + [Parallel] + [Method(EventNames.Capabilities, Direction.ServerToClient)] + [GenerateRequestMethods] + [GenerateHandlerMethods] public interface ICapabilitiesHandler : IJsonRpcNotificationHandler { } diff --git a/src/Dap.Protocol/Events/ContinuedEvent.cs b/src/Dap.Protocol/Events/ContinuedEvent.cs index 24fa9b1b1..83b032249 100644 --- a/src/Dap.Protocol/Events/ContinuedEvent.cs +++ b/src/Dap.Protocol/Events/ContinuedEvent.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events @@ -15,6 +15,7 @@ public class ContinuedEvent : IRequest /// /// If 'allThreadsContinued' is true, a debug adapter can announce that all threads have continued. /// - [Optional] public bool? AllThreadsContinued { get; set; } + [Optional] + public bool? AllThreadsContinued { get; set; } } } diff --git a/src/Dap.Protocol/Events/ContinuedExtensions.cs b/src/Dap.Protocol/Events/ContinuedExtensions.cs index 7a7a8ef44..80016a4a7 100644 --- a/src/Dap.Protocol/Events/ContinuedExtensions.cs +++ b/src/Dap.Protocol/Events/ContinuedExtensions.cs @@ -6,10 +6,13 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - - [Parallel, Method(EventNames.Continued, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] - public interface IContinuedHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(EventNames.Continued, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public interface IContinuedHandler : IJsonRpcNotificationHandler + { + } public abstract class ContinuedHandler : IContinuedHandler { diff --git a/src/Dap.Protocol/Events/ExitedEvent.cs b/src/Dap.Protocol/Events/ExitedEvent.cs index 724bc462c..76c7e8278 100644 --- a/src/Dap.Protocol/Events/ExitedEvent.cs +++ b/src/Dap.Protocol/Events/ExitedEvent.cs @@ -6,7 +6,6 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events [Method(EventNames.Exited, Direction.ServerToClient)] public class ExitedEvent : IRequest { - /// /// The exit code returned from the debuggee. /// diff --git a/src/Dap.Protocol/Events/ExitedExtensions.cs b/src/Dap.Protocol/Events/ExitedExtensions.cs index a034b5ef5..8a1f43481 100644 --- a/src/Dap.Protocol/Events/ExitedExtensions.cs +++ b/src/Dap.Protocol/Events/ExitedExtensions.cs @@ -6,10 +6,13 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - - [Parallel, Method(EventNames.Exited, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] - public interface IExitedHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(EventNames.Exited, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public interface IExitedHandler : IJsonRpcNotificationHandler + { + } public abstract class ExitedHandler : IExitedHandler { diff --git a/src/Dap.Protocol/Events/IProgressEndHandler.cs b/src/Dap.Protocol/Events/IProgressEndHandler.cs index f7481bdcc..a63e4fc2f 100644 --- a/src/Dap.Protocol/Events/IProgressEndHandler.cs +++ b/src/Dap.Protocol/Events/IProgressEndHandler.cs @@ -6,8 +6,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - [Parallel, Method(EventNames.ProgressEnd, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(EventNames.ProgressEnd, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IProgressEndHandler : IJsonRpcNotificationHandler { } diff --git a/src/Dap.Protocol/Events/IProgressStartHandler.cs b/src/Dap.Protocol/Events/IProgressStartHandler.cs index 3695bfc38..29143b6dd 100644 --- a/src/Dap.Protocol/Events/IProgressStartHandler.cs +++ b/src/Dap.Protocol/Events/IProgressStartHandler.cs @@ -6,8 +6,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - [Parallel, Method(EventNames.ProgressStart, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(EventNames.ProgressStart, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IProgressStartHandler : IJsonRpcNotificationHandler { } diff --git a/src/Dap.Protocol/Events/IProgressUpdateHandler.cs b/src/Dap.Protocol/Events/IProgressUpdateHandler.cs index 418bf5348..1776fde5f 100644 --- a/src/Dap.Protocol/Events/IProgressUpdateHandler.cs +++ b/src/Dap.Protocol/Events/IProgressUpdateHandler.cs @@ -6,8 +6,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - [Parallel, Method(EventNames.ProgressUpdate, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(EventNames.ProgressUpdate, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IProgressUpdateHandler : IJsonRpcNotificationHandler { } diff --git a/src/Dap.Protocol/Events/InitializedExtensions.cs b/src/Dap.Protocol/Events/InitializedExtensions.cs index 4cf7f6d71..0b0eceff0 100644 --- a/src/Dap.Protocol/Events/InitializedExtensions.cs +++ b/src/Dap.Protocol/Events/InitializedExtensions.cs @@ -6,10 +6,13 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - - [Parallel, Method(EventNames.Initialized, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] - public interface IDebugAdapterInitializedHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(EventNames.Initialized, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public interface IDebugAdapterInitializedHandler : IJsonRpcNotificationHandler + { + } public abstract class DebugAdapterInitializedHandler : IDebugAdapterInitializedHandler { diff --git a/src/Dap.Protocol/Events/LoadedSourceEvent.cs b/src/Dap.Protocol/Events/LoadedSourceEvent.cs index 8a7ab98a7..9df4ca4ad 100644 --- a/src/Dap.Protocol/Events/LoadedSourceEvent.cs +++ b/src/Dap.Protocol/Events/LoadedSourceEvent.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events @@ -17,5 +17,4 @@ public class LoadedSourceEvent : IRequest /// public Source Source { get; set; } } - } diff --git a/src/Dap.Protocol/Events/LoadedSourceExtensions.cs b/src/Dap.Protocol/Events/LoadedSourceExtensions.cs index fd6167753..1d539ff3a 100644 --- a/src/Dap.Protocol/Events/LoadedSourceExtensions.cs +++ b/src/Dap.Protocol/Events/LoadedSourceExtensions.cs @@ -6,10 +6,13 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - - [Parallel, Method(EventNames.LoadedSource, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] - public interface ILoadedSourceHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(EventNames.LoadedSource, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public interface ILoadedSourceHandler : IJsonRpcNotificationHandler + { + } public abstract class LoadedSourceHandler : ILoadedSourceHandler { diff --git a/src/Dap.Protocol/Events/ModuleEvent.cs b/src/Dap.Protocol/Events/ModuleEvent.cs index 2581982a5..8b122680d 100644 --- a/src/Dap.Protocol/Events/ModuleEvent.cs +++ b/src/Dap.Protocol/Events/ModuleEvent.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events @@ -7,7 +7,6 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events [Method(EventNames.Module, Direction.ServerToClient)] public class ModuleEvent : IRequest { - /// /// The reason for the event. /// @@ -18,5 +17,4 @@ public class ModuleEvent : IRequest /// public Module Module { get; set; } } - } diff --git a/src/Dap.Protocol/Events/ModuleEventReason.cs b/src/Dap.Protocol/Events/ModuleEventReason.cs index c3700164e..89c5cbbbc 100644 --- a/src/Dap.Protocol/Events/ModuleEventReason.cs +++ b/src/Dap.Protocol/Events/ModuleEventReason.cs @@ -8,5 +8,4 @@ public enum ModuleEventReason { New, Changed, Removed } - } diff --git a/src/Dap.Protocol/Events/ModuleExtensions.cs b/src/Dap.Protocol/Events/ModuleExtensions.cs index c698e6b55..c4dd61dee 100644 --- a/src/Dap.Protocol/Events/ModuleExtensions.cs +++ b/src/Dap.Protocol/Events/ModuleExtensions.cs @@ -6,10 +6,13 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - - [Parallel, Method(EventNames.Module, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] - public interface IModuleHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(EventNames.Module, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public interface IModuleHandler : IJsonRpcNotificationHandler + { + } public abstract class ModuleHandler : IModuleHandler { diff --git a/src/Dap.Protocol/Events/OutputEvent.cs b/src/Dap.Protocol/Events/OutputEvent.cs index 5f7db9f26..ee365766f 100644 --- a/src/Dap.Protocol/Events/OutputEvent.cs +++ b/src/Dap.Protocol/Events/OutputEvent.cs @@ -1,7 +1,7 @@ +using MediatR; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; -using MediatR; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events @@ -13,7 +13,8 @@ public class OutputEvent : IRequest /// The output category. If not specified, 'console' is assumed. /// Values: 'console', 'stdout', 'stderr', 'telemetry', etc. /// - [Optional] public string Category { get; set; } + [Optional] + public string Category { get; set; } /// /// The output to report. @@ -23,27 +24,31 @@ public class OutputEvent : IRequest /// /// If an attribute 'variablesReference' exists and its value is > 0, the output contains objects which can be retrieved by passing 'variablesReference' to the 'variables' request. /// - [Optional] public long? VariablesReference { get; set; } + [Optional] + public long? VariablesReference { get; set; } /// /// An optional source location where the output was produced. /// - [Optional] public Source Source { get; set; } + [Optional] + public Source Source { get; set; } /// /// An optional source location line where the output was produced. /// - [Optional] public long? Line { get; set; } + [Optional] + public long? Line { get; set; } /// /// An optional source location column where the output was produced. /// - [Optional] public long? Column { get; set; } + [Optional] + public long? Column { get; set; } /// /// Optional data to report. For the 'telemetry' category the data will be sent to telemetry, for the other categories the data is shown in JSON format. /// - [Optional] public JToken Data { get; set; } + [Optional] + public JToken Data { get; set; } } - } diff --git a/src/Dap.Protocol/Events/OutputExtensions.cs b/src/Dap.Protocol/Events/OutputExtensions.cs index 186d44689..355965f92 100644 --- a/src/Dap.Protocol/Events/OutputExtensions.cs +++ b/src/Dap.Protocol/Events/OutputExtensions.cs @@ -6,9 +6,13 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - [Parallel, Method(EventNames.Output, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] - public interface IOutputHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(EventNames.Output, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public interface IOutputHandler : IJsonRpcNotificationHandler + { + } public abstract class OutputHandler : IOutputHandler { diff --git a/src/Dap.Protocol/Events/ProcessEvent.cs b/src/Dap.Protocol/Events/ProcessEvent.cs index 9458b6bf2..67f8163d5 100644 --- a/src/Dap.Protocol/Events/ProcessEvent.cs +++ b/src/Dap.Protocol/Events/ProcessEvent.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events @@ -7,7 +7,6 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events [Method(EventNames.Process, Direction.ServerToClient)] public class 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. /// @@ -16,12 +15,14 @@ public class ProcessEvent : IRequest /// /// The system process id of the debugged process. This property will be missing for non-system processes. /// - [Optional] public long? SystemProcessId { get; set; } + [Optional] + public long? SystemProcessId { get; set; } /// /// If true, the process is running on the same computer as the debug adapter. /// - [Optional] public bool? IsLocalProcess { get; set; } + [Optional] + public bool? IsLocalProcess { get; set; } /// /// Describes how the debug engine started debugging this process. @@ -29,12 +30,13 @@ public class ProcessEvent : IRequest /// 'attach': Debugger attached to an existing process. /// 'attachForSuspendedLaunch': A project launcher component has launched a new process in a suspended state and then asked the debugger to attach. /// - [Optional] public ProcessEventStartMethod? StartMethod { get; set; } + [Optional] + public ProcessEventStartMethod? StartMethod { get; set; } /// /// The size of a pointer or address for this process, in bits. This value may be used by clients when formatting addresses for display. /// - [Optional] public long? PointerSize { get; set; } + [Optional] + public long? PointerSize { get; set; } } - } diff --git a/src/Dap.Protocol/Events/ProcessEventStartMethod.cs b/src/Dap.Protocol/Events/ProcessEventStartMethod.cs index f2cb7219a..c9685ea71 100644 --- a/src/Dap.Protocol/Events/ProcessEventStartMethod.cs +++ b/src/Dap.Protocol/Events/ProcessEventStartMethod.cs @@ -8,5 +8,4 @@ public enum ProcessEventStartMethod { Launch, Attach, AttachForSuspendedLaunch } - } diff --git a/src/Dap.Protocol/Events/ProcessExtensions.cs b/src/Dap.Protocol/Events/ProcessExtensions.cs index 1d4e91fe4..482901dc4 100644 --- a/src/Dap.Protocol/Events/ProcessExtensions.cs +++ b/src/Dap.Protocol/Events/ProcessExtensions.cs @@ -6,10 +6,13 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - - [Parallel, Method(EventNames.Process, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] - public interface IProcessHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(EventNames.Process, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public interface IProcessHandler : IJsonRpcNotificationHandler + { + } public abstract class ProcessHandler : IProcessHandler { diff --git a/src/Dap.Protocol/Events/ProgressEndEvent.cs b/src/Dap.Protocol/Events/ProgressEndEvent.cs index 6268be688..73202a906 100644 --- a/src/Dap.Protocol/Events/ProgressEndEvent.cs +++ b/src/Dap.Protocol/Events/ProgressEndEvent.cs @@ -1,6 +1,4 @@ using MediatR; -using OmniSharp.Extensions.DebugAdapter.Protocol.Models; -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events diff --git a/src/Dap.Protocol/Events/ProgressEvent.cs b/src/Dap.Protocol/Events/ProgressEvent.cs index 5752cbb68..bccee39c5 100644 --- a/src/Dap.Protocol/Events/ProgressEvent.cs +++ b/src/Dap.Protocol/Events/ProgressEvent.cs @@ -6,12 +6,12 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events public abstract class ProgressEvent { /// - /// The ID that was introduced in the initial 'progressStart' event. + /// The ID that was introduced in the initial 'progressStart' event. /// public ProgressToken ProgressId { get; set; } /// - /// Optional, more detailed progress message. If omitted, the previous message (if any) is used. + /// Optional, more detailed progress message. If omitted, the previous message (if any) is used. /// [Optional] public string Message { get; set; } diff --git a/src/Dap.Protocol/Events/ProgressUpdateEvent.cs b/src/Dap.Protocol/Events/ProgressUpdateEvent.cs index 8030b9e0e..3bac1eee8 100644 --- a/src/Dap.Protocol/Events/ProgressUpdateEvent.cs +++ b/src/Dap.Protocol/Events/ProgressUpdateEvent.cs @@ -1,5 +1,4 @@ using MediatR; -using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; @@ -9,7 +8,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events public class ProgressUpdateEvent : ProgressEvent, IRequest { /// - /// Optional progress percentage to display (value range: 0 to 100). If omitted no percentage will be shown. + /// Optional progress percentage to display (value range: 0 to 100). If omitted no percentage will be shown. /// [Optional] public double? Percentage { get; set; } diff --git a/src/Dap.Protocol/Events/StoppedEvent.cs b/src/Dap.Protocol/Events/StoppedEvent.cs index fc78f7e6e..1d2fa973b 100644 --- a/src/Dap.Protocol/Events/StoppedEvent.cs +++ b/src/Dap.Protocol/Events/StoppedEvent.cs @@ -1,10 +1,10 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { -[Method(EventNames.Stopped, Direction.ServerToClient)] + [Method(EventNames.Stopped, Direction.ServerToClient)] public class StoppedEvent : IRequest { /// @@ -17,29 +17,33 @@ public class StoppedEvent : IRequest /// /// The full reason for the event, e.g. 'Paused on exception'. This string is shown in the UI as is and must be translated. /// - [Optional] public string Description { get; set; } + [Optional] + public string Description { get; set; } /// /// The thread which was stopped. /// - [Optional] public long? ThreadId { get; set; } + [Optional] + public long? ThreadId { get; set; } /// /// A value of true hints to the frontend that this event should not change the focus. /// - [Optional] public bool? PreserveFocusHint { get; set; } + [Optional] + public bool? PreserveFocusHint { get; set; } /// /// Additional information. E.g. if reason is 'exception', text contains the exception name. This string is shown in the UI. /// - [Optional] public string Text { get; set; } + [Optional] + public string Text { get; set; } /// /// If 'allThreadsStopped' is true, a debug adapter can announce that all threads have stopped. /// - The client should use this information to enable that all threads can be expanded to access their stacktraces. /// - If the attribute is missing or false, only the thread with the given threadId can be expanded. /// - [Optional] public bool? AllThreadsStopped { get; set; } + [Optional] + public bool? AllThreadsStopped { get; set; } } - } diff --git a/src/Dap.Protocol/Events/StoppedExtensions.cs b/src/Dap.Protocol/Events/StoppedExtensions.cs index 6012371c6..565491a86 100644 --- a/src/Dap.Protocol/Events/StoppedExtensions.cs +++ b/src/Dap.Protocol/Events/StoppedExtensions.cs @@ -6,10 +6,13 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - - [Parallel, Method(EventNames.Stopped, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] - public interface IStoppedHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(EventNames.Stopped, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public interface IStoppedHandler : IJsonRpcNotificationHandler + { + } public abstract class StoppedHandler : IStoppedHandler { diff --git a/src/Dap.Protocol/Events/TerminatedEvent.cs b/src/Dap.Protocol/Events/TerminatedEvent.cs index 275c0ca47..a97e99d5d 100644 --- a/src/Dap.Protocol/Events/TerminatedEvent.cs +++ b/src/Dap.Protocol/Events/TerminatedEvent.cs @@ -1,7 +1,7 @@ -using Newtonsoft.Json.Linq; -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events @@ -17,5 +17,4 @@ public class TerminatedEvent : IRequest [JsonProperty(PropertyName = "__restart")] public JToken Restart { get; set; } } - } diff --git a/src/Dap.Protocol/Events/TerminatedExtensions.cs b/src/Dap.Protocol/Events/TerminatedExtensions.cs index 637c546a5..b3a5bea30 100644 --- a/src/Dap.Protocol/Events/TerminatedExtensions.cs +++ b/src/Dap.Protocol/Events/TerminatedExtensions.cs @@ -6,10 +6,13 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - - [Parallel, Method(EventNames.Terminated, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] - public interface ITerminatedHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(EventNames.Terminated, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public interface ITerminatedHandler : IJsonRpcNotificationHandler + { + } public abstract class TerminatedHandler : ITerminatedHandler { diff --git a/src/Dap.Protocol/Events/ThreadEvent.cs b/src/Dap.Protocol/Events/ThreadEvent.cs index 87759def1..b473ea6a4 100644 --- a/src/Dap.Protocol/Events/ThreadEvent.cs +++ b/src/Dap.Protocol/Events/ThreadEvent.cs @@ -17,5 +17,4 @@ public class ThreadEvent : IRequest /// public long ThreadId { get; set; } } - } diff --git a/src/Dap.Protocol/Events/ThreadExtensions.cs b/src/Dap.Protocol/Events/ThreadExtensions.cs index 80950a97e..3dd91c7ad 100644 --- a/src/Dap.Protocol/Events/ThreadExtensions.cs +++ b/src/Dap.Protocol/Events/ThreadExtensions.cs @@ -6,10 +6,13 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Events { - - [Parallel, Method(EventNames.Thread, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] - public interface IThreadHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(EventNames.Thread, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public interface IThreadHandler : IJsonRpcNotificationHandler + { + } public abstract class ThreadHandler : IThreadHandler { diff --git a/src/Dap.Protocol/IProgressObservable.cs b/src/Dap.Protocol/IProgressObservable.cs index 5a58ececf..f2d5f1a6b 100644 --- a/src/Dap.Protocol/IProgressObservable.cs +++ b/src/Dap.Protocol/IProgressObservable.cs @@ -6,4 +6,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol public interface IProgressObservable : IObservable { } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/IProgressObserver.cs b/src/Dap.Protocol/IProgressObserver.cs index a96ad39ff..5687dd31b 100644 --- a/src/Dap.Protocol/IProgressObserver.cs +++ b/src/Dap.Protocol/IProgressObserver.cs @@ -9,4 +9,4 @@ public interface IProgressObserver : IObserver, IDisposable ProgressToken ProgressId { get; } void OnNext(string message, double? percentage); } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/Breakpoint.cs b/src/Dap.Protocol/Models/Breakpoint.cs index fea696fe2..81a4ace42 100644 --- a/src/Dap.Protocol/Models/Breakpoint.cs +++ b/src/Dap.Protocol/Models/Breakpoint.cs @@ -10,7 +10,8 @@ public class Breakpoint /// /// An optional identifier for the breakpoint. It is needed if breakpoint events are used to update or remove breakpoints. /// - [Optional] public long? Id { get; set; } + [Optional] + public long? Id { get; set; } /// /// If true breakpoint could be set (but not necessarily at the desired location). @@ -20,42 +21,50 @@ public class Breakpoint /// /// An optional message about the state of the breakpoint. This is shown to the user and can be used to explain why a breakpoint could not be verified. /// - [Optional] public string Message { get; set; } + [Optional] + public string Message { get; set; } /// /// The source where the breakpoint is located. /// - [Optional] public Source Source { get; set; } + [Optional] + public Source Source { get; set; } /// /// The start line of the actual range covered by the breakpoint. /// - [Optional] public int? Line { get; set; } + [Optional] + public int? Line { get; set; } /// /// An optional start column of the actual range covered by the breakpoint. /// - [Optional] public int? Column { get; set; } + [Optional] + public int? Column { get; set; } /// /// An optional end line of the actual range covered by the breakpoint. /// - [Optional] public int? EndLine { get; set; } + [Optional] + public int? EndLine { get; set; } /// /// An optional end column of the actual range covered by the breakpoint. If no end line is given, then the end column is assumed to be in the start line. /// - [Optional] public int? EndColumn { get; set; } + [Optional] + public int? EndColumn { get; set; } /// /// An optional memory reference to where the breakpoint is set. /// - [Optional] public string InstructionReference { get; set; } + [Optional] + public string InstructionReference { get; set; } /// /// An optional offset from the instruction reference. /// This can be negative. /// - [Optional] public int? Offset { get; set; } + [Optional] + public int? Offset { get; set; } } } diff --git a/src/Dap.Protocol/Models/Capabilities.cs b/src/Dap.Protocol/Models/Capabilities.cs index 736ab0325..107154adb 100644 --- a/src/Dap.Protocol/Models/Capabilities.cs +++ b/src/Dap.Protocol/Models/Capabilities.cs @@ -10,171 +10,207 @@ public class Capabilities /// /// The debug adapter supports the 'configurationDone' request. /// - [Optional] public bool? SupportsConfigurationDoneRequest { get; set; } + [Optional] + public bool? SupportsConfigurationDoneRequest { get; set; } /// /// The debug adapter supports function breakpoints. /// - [Optional] public bool? SupportsFunctionBreakpoints { get; set; } + [Optional] + public bool? SupportsFunctionBreakpoints { get; set; } /// /// The debug adapter supports conditional breakpoints. /// - [Optional] public bool? SupportsConditionalBreakpoints { get; set; } + [Optional] + public bool? SupportsConditionalBreakpoints { get; set; } /// /// The debug adapter supports breakpoints that break execution after a specified long of hits. /// - [Optional] public bool? SupportsHitConditionalBreakpoints { get; set; } + [Optional] + public bool? SupportsHitConditionalBreakpoints { get; set; } /// /// The debug adapter supports a (side effect free) evaluate request for data hovers. /// - [Optional] public bool? SupportsEvaluateForHovers { get; set; } + [Optional] + public bool? SupportsEvaluateForHovers { get; set; } /// /// Available filters or options for the setExceptionBreakpoints request. /// - [Optional] public Container ExceptionBreakpointFilters { get; set; } + [Optional] + public Container ExceptionBreakpointFilters { get; set; } /// /// The debug adapter supports stepping back via the 'stepBack' and 'reverseContinue' requests. /// - [Optional] public bool? SupportsStepBack { get; set; } + [Optional] + public bool? SupportsStepBack { get; set; } /// /// The debug adapter supports setting a variable to a value. /// - [Optional] public bool? SupportsSetVariable { get; set; } + [Optional] + public bool? SupportsSetVariable { get; set; } /// /// The debug adapter supports restarting a frame. /// - [Optional] public bool? SupportsRestartFrame { get; set; } + [Optional] + public bool? SupportsRestartFrame { get; set; } /// /// The debug adapter supports the 'gotoTargets' request. /// - [Optional] public bool? SupportsGotoTargetsRequest { get; set; } + [Optional] + public bool? SupportsGotoTargetsRequest { get; set; } /// /// The debug adapter supports the 'stepInTargets' request. /// - [Optional] public bool? SupportsStepInTargetsRequest { get; set; } + [Optional] + public bool? SupportsStepInTargetsRequest { get; set; } /// /// The debug adapter supports the 'completions' request. /// - [Optional] public bool? SupportsCompletionsRequest { get; set; } + [Optional] + public bool? SupportsCompletionsRequest { get; set; } /// /// The debug adapter supports the 'modules' request. /// - [Optional] public bool? SupportsModulesRequest { get; set; } + [Optional] + public bool? SupportsModulesRequest { get; set; } /// /// The set of additional module information exposed by the debug adapter. /// - [Optional] public Container AdditionalModuleColumns { get; set; } + [Optional] + public Container AdditionalModuleColumns { get; set; } /// /// Checksum algorithms supported by the debug adapter. /// - [Optional] public Container SupportedChecksumAlgorithms { get; set; } + [Optional] + 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 RestartRequest. + /// 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] public bool? SupportsRestartRequest { get; set; } + [Optional] + public bool? SupportsRestartRequest { get; set; } /// /// The debug adapter supports 'exceptionOptions' on the setExceptionBreakpoints request. /// - [Optional] public bool? SupportsExceptionOptions { get; set; } + [Optional] + public bool? SupportsExceptionOptions { get; set; } /// /// The debug adapter supports a 'format' attribute on the stackTraceRequest, variablesRequest, and evaluateRequest. /// - [Optional] public bool? SupportsValueFormattingOptions { get; set; } + [Optional] + public bool? SupportsValueFormattingOptions { get; set; } /// /// The debug adapter supports the 'exceptionInfo' request. /// - [Optional] public bool? SupportsExceptionInfoRequest { get; set; } + [Optional] + public bool? SupportsExceptionInfoRequest { get; set; } /// /// The debug adapter supports the 'terminateDebuggee' attribute on the 'disconnect' request. /// - [Optional] public bool? SupportTerminateDebuggee { get; set; } + [Optional] + 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 'StackTrace' request are supported. + /// 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] public bool? SupportsDelayedStackTraceLoading { get; set; } + [Optional] + public bool? SupportsDelayedStackTraceLoading { get; set; } /// /// The debug adapter supports the 'loadedSources' request. /// - [Optional] public bool? SupportsLoadedSourcesRequest { get; set; } + [Optional] + public bool? SupportsLoadedSourcesRequest { get; set; } /// /// The debug adapter supports logpoints by interpreting the 'logMessage' attribute of the SourceBreakpoint. /// - [Optional] public bool? SupportsLogPoints { get; set; } + [Optional] + public bool? SupportsLogPoints { get; set; } /// /// The debug adapter supports the 'terminateThreads' request. /// - [Optional] public bool? SupportsTerminateThreadsRequest { get; set; } + [Optional] + public bool? SupportsTerminateThreadsRequest { get; set; } /// /// The debug adapter supports the 'setExpression' request. /// - [Optional] public bool? SupportsSetExpression { get; set; } + [Optional] + public bool? SupportsSetExpression { get; set; } /// /// The debug adapter supports the 'terminate' request. /// - [Optional] public bool? SupportsTerminateRequest { get; set; } + [Optional] + public bool? SupportsTerminateRequest { get; set; } /// /// The debug adapter supports data breakpoints. /// - [Optional] public bool? SupportsDataBreakpoints { get; set; } + [Optional] + public bool? SupportsDataBreakpoints { get; set; } /// /// The debug adapter supports the 'readMemory' request. /// - [Optional] public bool? SupportsReadMemoryRequest { get; set; } + [Optional] + public bool? SupportsReadMemoryRequest { get; set; } /// /// The debug adapter supports the 'disassemble' request. /// - [Optional] public bool? SupportsDisassembleRequest { get; set; } + [Optional] + public bool? SupportsDisassembleRequest { get; set; } /// /// The debug adapter supports the 'cancel' request. /// - [Optional] public bool? SupportsCancelRequest { get; set; } + [Optional] + public bool? SupportsCancelRequest { get; set; } /// /// The debug adapter supports the 'breakpointLocations' request. /// - [Optional] public bool? SupportsBreakpointLocationsRequest { get; set; } + [Optional] + public bool? SupportsBreakpointLocationsRequest { get; set; } /// /// The debug adapter supports the 'clipboard' context value in the 'evaluate' request. /// - [Optional] public bool? SupportsClipboardContext { get; set; } + [Optional] + public bool? SupportsClipboardContext { get; set; } /// /// The debug adapter supports stepping granularities (argument 'granularity') for the stepping requests. /// - [Optional] public bool? SupportsSteppingGranularity { get; set; } + [Optional] + public bool? SupportsSteppingGranularity { get; set; } /// /// The debug adapter supports adding breakpoints based on instruction references. /// - [Optional] public bool? SupportsInstructionBreakpoints { get; set; } + [Optional] + public bool? SupportsInstructionBreakpoints { get; set; } } } diff --git a/src/Dap.Protocol/Models/Checksum.cs b/src/Dap.Protocol/Models/Checksum.cs index e1b2afd08..fb0ae66aa 100644 --- a/src/Dap.Protocol/Models/Checksum.cs +++ b/src/Dap.Protocol/Models/Checksum.cs @@ -5,7 +5,6 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models /// /// The checksum of an item calculated by the specified algorithm. /// - public class Checksum { /// @@ -19,4 +18,4 @@ public class Checksum [JsonProperty("checksum")] public string Value { get; set; } } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/ChecksumAlgorithm.cs b/src/Dap.Protocol/Models/ChecksumAlgorithm.cs index 37b7a13c4..b19ece30c 100644 --- a/src/Dap.Protocol/Models/ChecksumAlgorithm.cs +++ b/src/Dap.Protocol/Models/ChecksumAlgorithm.cs @@ -11,4 +11,4 @@ public enum ChecksumAlgorithm { Md5, Sha1, Sha256, Timestamp } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/ColumnDescriptor.cs b/src/Dap.Protocol/Models/ColumnDescriptor.cs index ec7894055..146add57f 100644 --- a/src/Dap.Protocol/Models/ColumnDescriptor.cs +++ b/src/Dap.Protocol/Models/ColumnDescriptor.cs @@ -6,7 +6,6 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models /// A ColumnDescriptor specifies what module attribute to show in a column of the ModulesView, how to format it, and what the column’s label should be. /// It is only used if the underlying UI actually supports this level of customization. /// - public class ColumnDescriptor { /// @@ -22,16 +21,19 @@ public class ColumnDescriptor /// /// Format to use for the rendered values in this column. TBD how the format strings looks like. /// - [Optional] public string Format { get; set; } + [Optional] + public string Format { get; set; } /// /// Datatype of values in this column. Defaults to 'string' if not specified. /// - [Optional] public ColumnDescriptorType? Type { get; set; } + [Optional] + public ColumnDescriptorType? Type { get; set; } /// /// Width of this column in characters (hint only). /// - [Optional] public long? Width { get; set; } + [Optional] + public long? Width { get; set; } } } diff --git a/src/Dap.Protocol/Models/ColumnDescriptorType.cs b/src/Dap.Protocol/Models/ColumnDescriptorType.cs index 1a7aa21cf..3e6482e36 100644 --- a/src/Dap.Protocol/Models/ColumnDescriptorType.cs +++ b/src/Dap.Protocol/Models/ColumnDescriptorType.cs @@ -12,4 +12,4 @@ public enum ColumnDescriptorType Bool, UnixTimestampUtc, } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/CompletionItem.cs b/src/Dap.Protocol/Models/CompletionItem.cs index d9555e793..f2d9e312e 100644 --- a/src/Dap.Protocol/Models/CompletionItem.cs +++ b/src/Dap.Protocol/Models/CompletionItem.cs @@ -15,37 +15,43 @@ public class CompletionItem /// /// If text is not falsy then it is inserted instead of the label. /// - [Optional] public string Text { get; set; } + [Optional] + public string Text { get; set; } /// /// The item's type. Typically the client uses this information to render the item in the UI with an icon. /// - [Optional] public CompletionItemType Type { get; set; } + [Optional] + public CompletionItemType Type { get; set; } /// /// This value determines the location (in the CompletionsRequest's 'text' attribute) where the completion text is added. /// If missing the text is added at the location specified by the CompletionsRequest's 'column' attribute. /// - [Optional] public int? Start { get; set; } + [Optional] + public int? Start { get; set; } /// /// This value determines how many characters are overwritten by the completion text. /// If missing the value 0 is assumed which results in the completion text being inserted. /// - [Optional] public int? Length { get; set; } + [Optional] + public int? Length { get; set; } /// /// Determines the start of the new selection after the text has been inserted (or replaced). /// The start position must in the range 0 and length of the completion text. /// If omitted the selection starts at the end of the completion text. /// - [Optional] public int? SelectionStart { get; set; } + [Optional] + public int? SelectionStart { get; set; } /// /// Determines the length of the new selection after the text has been inserted (or replaced). /// The selection can not extend beyond the bounds of the completion text. /// If omitted the length is assumed to be 0. /// - [Optional] public int? SelectionLength { get; set; } + [Optional] + public int? SelectionLength { get; set; } } } diff --git a/src/Dap.Protocol/Models/CompletionItemType.cs b/src/Dap.Protocol/Models/CompletionItemType.cs index 662295c28..dd6412356 100644 --- a/src/Dap.Protocol/Models/CompletionItemType.cs +++ b/src/Dap.Protocol/Models/CompletionItemType.cs @@ -11,4 +11,4 @@ public enum CompletionItemType { Method, Function, Constructor, Field, Variable, Class, Interface, Module, Property, Unit, Value, Enum, Keyword, Snippet, Text, Color, File, Reference, CustomColor } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/Container.cs b/src/Dap.Protocol/Models/Container.cs index a32b40865..5a3b21905 100644 --- a/src/Dap.Protocol/Models/Container.cs +++ b/src/Dap.Protocol/Models/Container.cs @@ -18,19 +18,10 @@ public Container(params T[] items) : base(items) { } - public static implicit operator Container(T[] items) - { - return new Container(items); - } + public static implicit operator Container(T[] items) => new Container(items); - public static implicit operator Container(Collection items) - { - return new Container(items); - } + public static implicit operator Container(Collection items) => new Container(items); - public static implicit operator Container(List items) - { - return new Container(items); - } + public static implicit operator Container(List items) => new Container(items); } } diff --git a/src/Dap.Protocol/Models/ContainerBase.cs b/src/Dap.Protocol/Models/ContainerBase.cs index 5ce5ec75b..c55f8cd74 100644 --- a/src/Dap.Protocol/Models/ContainerBase.cs +++ b/src/Dap.Protocol/Models/ContainerBase.cs @@ -8,45 +8,22 @@ public abstract class ContainerBase : IEnumerable, IEquatable _items; - public ContainerBase(IEnumerable items) - { - _items = items; - } - - public override bool Equals(object obj) - { - return Equals(obj as ContainerBase); - } - - public bool Equals(ContainerBase other) - { - return other != null && - EqualityComparer>.Default.Equals(_items, other._items); - } - - public IEnumerator GetEnumerator() - { - return _items.GetEnumerator(); - } - - public override int GetHashCode() - { - return -566117206 + EqualityComparer>.Default.GetHashCode(_items); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public static bool operator ==(ContainerBase base1, ContainerBase base2) - { - return EqualityComparer>.Default.Equals(base1, base2); - } - - public static bool operator !=(ContainerBase base1, ContainerBase base2) - { - return !( base1 == base2 ); - } + public ContainerBase(IEnumerable items) => _items = items; + + public override bool Equals(object obj) => Equals(obj as ContainerBase); + + public bool Equals(ContainerBase other) => + other != null && + EqualityComparer>.Default.Equals(_items, other._items); + + public IEnumerator GetEnumerator() => _items.GetEnumerator(); + + public override int GetHashCode() => -566117206 + EqualityComparer>.Default.GetHashCode(_items); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + public static bool operator ==(ContainerBase base1, ContainerBase base2) => EqualityComparer>.Default.Equals(base1, base2); + + public static bool operator !=(ContainerBase base1, ContainerBase base2) => !( base1 == base2 ); } } diff --git a/src/Dap.Protocol/Models/DataBreakpoint.cs b/src/Dap.Protocol/Models/DataBreakpoint.cs index e49e2ac14..049c9cd1a 100644 --- a/src/Dap.Protocol/Models/DataBreakpoint.cs +++ b/src/Dap.Protocol/Models/DataBreakpoint.cs @@ -15,16 +15,19 @@ public class DataBreakpoint /// /// The access type of the data. /// - [Optional] public DataBreakpointAccessType? AccessType { get; set; } + [Optional] + public DataBreakpointAccessType? AccessType { get; set; } /// /// An optional expression for conditional breakpoints. /// - [Optional] public string Condition { get; set; } + [Optional] + public string Condition { get; set; } /// /// An optional expression that controls how many hits of the breakpoint are ignored. The backend is expected to interpret the expression as needed. /// - [Optional] public string HitCondition { get; set; } + [Optional] + public string HitCondition { get; set; } } } diff --git a/src/Dap.Protocol/Models/DataBreakpointAccessType.cs b/src/Dap.Protocol/Models/DataBreakpointAccessType.cs index 81da1dd47..af65927b9 100644 --- a/src/Dap.Protocol/Models/DataBreakpointAccessType.cs +++ b/src/Dap.Protocol/Models/DataBreakpointAccessType.cs @@ -13,4 +13,4 @@ public enum DataBreakpointAccessType Write, ReadWrite } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/DisassembledInstruction.cs b/src/Dap.Protocol/Models/DisassembledInstruction.cs index 922221d56..f30972cba 100644 --- a/src/Dap.Protocol/Models/DisassembledInstruction.cs +++ b/src/Dap.Protocol/Models/DisassembledInstruction.cs @@ -2,7 +2,8 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { - /// DisassembledInstruction + /// + /// DisassembledInstruction /// Represents a single disassembled instruction. /// public class DisassembledInstruction @@ -15,7 +16,8 @@ public class DisassembledInstruction /// /// Optional raw bytes representing the instruction and its operands, in an implementation-defined format. /// - [Optional] public string InstructionBytes { get; set; } + [Optional] + public string InstructionBytes { get; set; } /// /// Text representing the instruction and its operands, in an implementation-defined format. @@ -25,31 +27,38 @@ public class DisassembledInstruction /// /// Name of the symbol that correponds with the location of this instruction, if any. /// - [Optional] public string Symbol { get; set; } + [Optional] + public string Symbol { get; set; } /// - /// 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. + /// 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] public Source Location { get; set; } + [Optional] + public Source Location { get; set; } /// /// The line within the source location that corresponds to this instruction, if any. /// - [Optional] public int? Line { get; set; } + [Optional] + public int? Line { get; set; } /// /// The column within the line that corresponds to this instruction, if any. /// - [Optional] public int? Column { get; set; } + [Optional] + public int? Column { get; set; } /// /// The end line of the range that corresponds to this instruction, if any. /// - [Optional] public int? EndLine { get; set; } + [Optional] + public int? EndLine { get; set; } /// /// The end column of the range that corresponds to this instruction, if any. /// - [Optional] public int? EndColumn { get; set; } + [Optional] + public int? EndColumn { get; set; } } } diff --git a/src/Dap.Protocol/Models/ExceptionBreakMode.cs b/src/Dap.Protocol/Models/ExceptionBreakMode.cs index 6cdaf4432..b2138d2a8 100644 --- a/src/Dap.Protocol/Models/ExceptionBreakMode.cs +++ b/src/Dap.Protocol/Models/ExceptionBreakMode.cs @@ -15,4 +15,4 @@ public enum ExceptionBreakMode { Never, Always, Unhandled, UserUnhandled } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/ExceptionBreakpointsFilter.cs b/src/Dap.Protocol/Models/ExceptionBreakpointsFilter.cs index 38bb15cb0..6e3aae6f5 100644 --- a/src/Dap.Protocol/Models/ExceptionBreakpointsFilter.cs +++ b/src/Dap.Protocol/Models/ExceptionBreakpointsFilter.cs @@ -2,7 +2,8 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { - /// ExceptionBreakpointsFilter + /// + /// ExceptionBreakpointsFilter /// An ExceptionBreakpointsFilter is shown in the UI as an option for configuring how exceptions are dealt with. /// public class ExceptionBreakpointsFilter @@ -20,6 +21,7 @@ public class ExceptionBreakpointsFilter /// /// Initial value of the filter. If not specified a value 'false' is assumed. /// - [Optional] public bool? Default { get; set; } + [Optional] + public bool? Default { get; set; } } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/ExceptionDetails.cs b/src/Dap.Protocol/Models/ExceptionDetails.cs index d14cefa5d..9eacbff7c 100644 --- a/src/Dap.Protocol/Models/ExceptionDetails.cs +++ b/src/Dap.Protocol/Models/ExceptionDetails.cs @@ -2,7 +2,8 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { - /// ExceptionDetails + /// + /// ExceptionDetails /// Detailed information about an exception that has occurred. /// public class ExceptionDetails @@ -10,31 +11,37 @@ public class ExceptionDetails /// /// Message contained in the exception. /// - [Optional] public string Message { get; set; } + [Optional] + public string Message { get; set; } /// /// Short type name of the exception object. /// - [Optional] public string TypeName { get; set; } + [Optional] + public string TypeName { get; set; } /// /// Fully-qualified type name of the exception object. /// - [Optional] public string FullTypeName { get; set; } + [Optional] + public string FullTypeName { get; set; } /// /// Optional expression that can be evaluated in the current scope to obtain the exception object. /// - [Optional] public string EvaluateName { get; set; } + [Optional] + public string EvaluateName { get; set; } /// /// Stack trace at the time the exception was thrown. /// - [Optional] public string StackTrace { get; set; } + [Optional] + public string StackTrace { get; set; } /// /// Details of the exception contained by this exception, if any. /// - [Optional] public Container InnerException { get; set; } + [Optional] + public Container InnerException { get; set; } } } diff --git a/src/Dap.Protocol/Models/ExceptionOptions.cs b/src/Dap.Protocol/Models/ExceptionOptions.cs index 07487f865..701b52547 100644 --- a/src/Dap.Protocol/Models/ExceptionOptions.cs +++ b/src/Dap.Protocol/Models/ExceptionOptions.cs @@ -2,15 +2,18 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { - /// ExceptionOptions + /// + /// ExceptionOptions /// An ExceptionOptions assigns configuration options to a set of exceptions. /// public class 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 used to group exceptions in the UI. + /// 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] public Container Path { get; set; } + [Optional] + public Container Path { get; set; } /// /// Condition when a thrown exception should result in a break. diff --git a/src/Dap.Protocol/Models/ExceptionPathSegment.cs b/src/Dap.Protocol/Models/ExceptionPathSegment.cs index 24e326920..e33d0f32d 100644 --- a/src/Dap.Protocol/Models/ExceptionPathSegment.cs +++ b/src/Dap.Protocol/Models/ExceptionPathSegment.cs @@ -3,14 +3,16 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { /// - /// 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. + /// 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 class ExceptionPathSegment { /// /// If false or missing this segment matches the names provided, otherwise it matches anything except the names provided. /// - [Optional] public bool? Negate { get; set; } + [Optional] + public bool? Negate { get; set; } /// /// Depending on the value of 'negate' the names that should match or not match. diff --git a/src/Dap.Protocol/Models/FunctionBreakpoint.cs b/src/Dap.Protocol/Models/FunctionBreakpoint.cs index 6717074b5..55e1eff5e 100644 --- a/src/Dap.Protocol/Models/FunctionBreakpoint.cs +++ b/src/Dap.Protocol/Models/FunctionBreakpoint.cs @@ -2,7 +2,8 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { - /// FunctionBreakpoint + /// + /// FunctionBreakpoint /// Properties of a breakpoint passed to the setFunctionBreakpoints request. /// public class FunctionBreakpoint @@ -15,11 +16,13 @@ public class FunctionBreakpoint /// /// An optional expression for conditional breakpoints. /// - [Optional] public string Condition { get; set; } + [Optional] + public string Condition { get; set; } /// /// An optional expression that controls how many hits of the breakpoint are ignored. The backend is expected to interpret the expression as needed. /// - [Optional] public string HitCondition { get; set; } + [Optional] + public string HitCondition { get; set; } } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/GotoTarget.cs b/src/Dap.Protocol/Models/GotoTarget.cs index 29424b552..68e773c17 100644 --- a/src/Dap.Protocol/Models/GotoTarget.cs +++ b/src/Dap.Protocol/Models/GotoTarget.cs @@ -26,21 +26,25 @@ public class GotoTarget /// /// An optional column of the goto target. /// - [Optional] public int? Column { get; set; } + [Optional] + public int? Column { get; set; } /// /// An optional end line of the range covered by the goto target. /// - [Optional] public int? EndLine { get; set; } + [Optional] + public int? EndLine { get; set; } /// /// An optional end column of the range covered by the goto target. /// - [Optional] public int? EndColumn { get; set; } + [Optional] + public int? EndColumn { get; set; } /// /// Optional memory reference for the instruction pointer value represented by this target. /// - [Optional] public string InstructionPointerReference { get; set; } + [Optional] + public string InstructionPointerReference { get; set; } } } diff --git a/src/Dap.Protocol/Models/InstructionBreakpoint.cs b/src/Dap.Protocol/Models/InstructionBreakpoint.cs index 15a8a395c..a76b0011a 100644 --- a/src/Dap.Protocol/Models/InstructionBreakpoint.cs +++ b/src/Dap.Protocol/Models/InstructionBreakpoint.cs @@ -3,7 +3,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { public class InstructionBreakpoint - { + { /// /// The instruction reference of the breakpoint. /// This should be a memory or instruction pointer reference from an EvaluateResponse, Variable, StackFrame, GotoTarget, or Breakpoint. @@ -14,20 +14,22 @@ public class InstructionBreakpoint /// An optional offset from the instruction reference. /// This can be negative. /// - [Optional] public int Offset { get; set; } + [Optional] + public int Offset { get; set; } /// /// An optional expression for conditional breakpoints. /// It is only honored by a debug adapter if the capability 'supportsConditionalBreakpoints' is true. /// - [Optional] public string Condition { get; set; } + [Optional] + public string Condition { get; set; } /// /// An optional expression that controls how many hits of the breakpoint are ignored. /// The backend is expected to interpret the expression as needed. /// The attribute is only honored by a debug adapter if the capability 'supportsHitConditionalBreakpoints' is true. /// - [Optional] public string HitCondition { get; set; } - + [Optional] + public string HitCondition { get; set; } } } diff --git a/src/Dap.Protocol/Models/Message.cs b/src/Dap.Protocol/Models/Message.cs index 659eec90f..8b4bcfee9 100644 --- a/src/Dap.Protocol/Models/Message.cs +++ b/src/Dap.Protocol/Models/Message.cs @@ -22,26 +22,31 @@ public class Message /// /// An object used as a dictionary for looking up the variables in the format string. /// - [Optional] public IDictionary Variables { get; set; } + [Optional] + public IDictionary Variables { get; set; } /// /// If true send to telemetry. /// - [Optional] public bool? SendTelemetry { get; set; } + [Optional] + public bool? SendTelemetry { get; set; } /// /// If true show user. /// - [Optional] public bool? ShowUser { get; set; } + [Optional] + public bool? ShowUser { get; set; } /// /// An optional url where additional information about this message can be found. /// - [Optional] public string Url { get; set; } + [Optional] + public string Url { get; set; } /// /// An optional label that is presented to the user as the UI for opening the url. /// - [Optional] public string UrlLabel { get; set; } + [Optional] + public string UrlLabel { get; set; } } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/Module.cs b/src/Dap.Protocol/Models/Module.cs index 3e4e5967c..86f42be12 100644 --- a/src/Dap.Protocol/Models/Module.cs +++ b/src/Dap.Protocol/Models/Module.cs @@ -12,7 +12,6 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models /// To avoid an unnecessary proliferation of additional attributes with similar semantics but different names /// we recommend to re-use attributes from the ‘recommended’ list below first, and only introduce new attributes if nothing appropriate could be found. /// - public class Module { /// @@ -31,46 +30,55 @@ public class Module /// /// Logical full path to the module. The exact definition is implementation defined, but usually this would be a full path to the on-disk file for the module. /// - [Optional] public string Path { get; set; } + [Optional] + public string Path { get; set; } /// /// True if the module is optimized. /// - [Optional] public bool? IsOptimized { get; set; } + [Optional] + public bool? IsOptimized { get; set; } /// /// True if the module is considered 'user code' by a debugger that supports 'Just My Code'. /// - [Optional] public bool? IsUserCode { get; set; } + [Optional] + public bool? IsUserCode { get; set; } /// /// Version of Module. /// - [Optional] public string Version { get; set; } + [Optional] + public string Version { get; set; } /// /// User understandable description of if symbols were found for the module (ex: 'Symbols Loaded', 'Symbols not found', etc. /// - [Optional] public string SymbolStatus { get; set; } + [Optional] + public string SymbolStatus { get; set; } /// /// Logical full path to the symbol file. The exact definition is implementation defined. /// - [Optional] public string SymbolFilePath { get; set; } + [Optional] + public string SymbolFilePath { get; set; } /// /// Module created or modified. /// - [Optional] public string DateTimeStamp { get; set; } + [Optional] + public string DateTimeStamp { get; set; } /// /// Address range covered by this module. /// - [Optional] public string AddressRange { get; set; } + [Optional] + public string AddressRange { get; set; } /// /// Allows additional data to be displayed /// - [JsonExtensionData] public Dictionary ExtensionData { get; set; } = new Dictionary(); + [JsonExtensionData] + public Dictionary ExtensionData { get; set; } = new Dictionary(); } } diff --git a/src/Dap.Protocol/Models/NumberString.cs b/src/Dap.Protocol/Models/NumberString.cs index f31423055..0b56e4bbc 100644 --- a/src/Dap.Protocol/Models/NumberString.cs +++ b/src/Dap.Protocol/Models/NumberString.cs @@ -10,6 +10,7 @@ public NumberString(long value) _long = value; _string = null; } + public NumberString(string value) { _long = null; @@ -17,35 +18,29 @@ public NumberString(string value) } public bool IsLong => _long.HasValue; + public long Long { get => _long ?? 0; - set - { + set { String = null; _long = value; } } public bool IsString => _string != null; + public string String { get => _string; - set - { + set { _string = value; _long = null; } } - public static implicit operator NumberString(long value) - { - return new NumberString(value); - } + public static implicit operator NumberString(long value) => new NumberString(value); - public static implicit operator NumberString(string value) - { - return new NumberString(value); - } + public static implicit operator NumberString(string value) => new NumberString(value); } } diff --git a/src/Dap.Protocol/Models/ProgressToken.cs b/src/Dap.Protocol/Models/ProgressToken.cs index 163fa4332..8a445a42d 100644 --- a/src/Dap.Protocol/Models/ProgressToken.cs +++ b/src/Dap.Protocol/Models/ProgressToken.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using Newtonsoft.Json; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { @@ -16,6 +15,7 @@ public ProgressToken(long value) _long = value; _string = null; } + public ProgressToken(string value) { _long = null; @@ -23,6 +23,7 @@ public ProgressToken(string value) } public bool IsLong => _long.HasValue; + public long Long { get => _long ?? 0; @@ -33,6 +34,7 @@ public long Long } public bool IsString => _string != null; + public string String { get => _string; @@ -42,21 +44,13 @@ public string String } } - public static implicit operator ProgressToken(long value) - { - return new ProgressToken(value); - } + public static implicit operator ProgressToken(long value) => new ProgressToken(value); - public static implicit operator ProgressToken(string value) - { - return new ProgressToken(value); - } + public static implicit operator ProgressToken(string value) => new ProgressToken(value); - public override bool Equals(object obj) - { - return obj is ProgressToken token && - this.Equals(token); - } + public override bool Equals(object obj) => + obj is ProgressToken token && + Equals(token); public override int GetHashCode() { @@ -68,25 +62,18 @@ public override int GetHashCode() return hashCode; } - public bool Equals(ProgressToken other) - { - return IsLong == other.IsLong && - Long == other.Long && - IsString == other.IsString && - String == other.String; - } + public bool Equals(ProgressToken other) => + IsLong == other.IsLong && + Long == other.Long && + IsString == other.IsString && + String == other.String; - public bool Equals(long other) - { - return this.IsLong && this.Long == other; - } + public bool Equals(long other) => IsLong && Long == other; - public bool Equals(string other) - { - return this.IsString && this.String == other; - } + public bool Equals(string other) => IsString && String == other; private string DebuggerDisplay => IsString ? String : IsLong ? Long.ToString() : ""; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Dap.Protocol/Models/Scope.cs b/src/Dap.Protocol/Models/Scope.cs index 14d7b8cf8..8fc03ddce 100644 --- a/src/Dap.Protocol/Models/Scope.cs +++ b/src/Dap.Protocol/Models/Scope.cs @@ -20,7 +20,8 @@ public class Scope /// 'registers': Scope contains registers. Only a single 'registers' scope should be returned from a 'scopes' request. /// etc. /// - [Optional] public string PresentationHint { get; set; } + [Optional] + public string PresentationHint { get; set; } /// /// The variables of this scope can be retrieved by passing the value of variablesReference to the VariablesRequest. @@ -31,13 +32,15 @@ public class Scope /// The long of named variables in this scope. /// The client can use this optional information to present the variables in a paged UI and fetch them in chunks. /// - [Optional] public long? NamedVariables { get; set; } + [Optional] + public long? NamedVariables { get; set; } /// /// The long of indexed variables in this scope. /// The client can use this optional information to present the variables in a paged UI and fetch them in chunks. /// - [Optional] public long? IndexedVariables { get; set; } + [Optional] + public long? IndexedVariables { get; set; } /// /// If true, the long of variables in this scope is large or expensive to retrieve. @@ -47,26 +50,31 @@ public class Scope /// /// Optional source for this scope. /// - [Optional] public Source Source { get; set; } + [Optional] + public Source Source { get; set; } /// /// Optional start line of the range covered by this scope. /// - [Optional] public int? Line { get; set; } + [Optional] + public int? Line { get; set; } /// /// Optional start column of the range covered by this scope. /// - [Optional] public int? Column { get; set; } + [Optional] + public int? Column { get; set; } /// /// Optional end line of the range covered by this scope. /// - [Optional] public int? EndLine { get; set; } + [Optional] + public int? EndLine { get; set; } /// /// Optional end column of the range covered by this scope. /// - [Optional] public int? EndColumn { get; set; } + [Optional] + public int? EndColumn { get; set; } } } diff --git a/src/Dap.Protocol/Models/Source.cs b/src/Dap.Protocol/Models/Source.cs index 853f0bbc0..745a9d85e 100644 --- a/src/Dap.Protocol/Models/Source.cs +++ b/src/Dap.Protocol/Models/Source.cs @@ -11,41 +11,51 @@ public class Source /// /// The short name of the source. Every source returned from the debug adapter has a name. When sending a source to the debug adapter this name is optional. /// - [Optional] public string Name { get; set; } + [Optional] + public string Name { get; set; } /// /// The path of the source to be shown in the UI. It is only used to locate and load the content of the source if no sourceReference is specified (or its value is 0). /// - [Optional] public string Path { get; set; } + [Optional] + public string Path { get; set; } /// - /// If sourceReference > 0 the contents of the source must be retrieved through the SourceRequest (even if a path is specified). A sourceReference is only valid for a session, so it must not be used to persist a source. + /// If sourceReference > 0 the contents of the source must be retrieved through the SourceRequest (even if a path is specified). A sourceReference is only valid for a session, so it + /// must not be used to persist a source. /// - [Optional] public long? SourceReference { get; set; } + [Optional] + public long? SourceReference { get; set; } /// /// An optional hint for how to present the source in the UI. A value of 'deemphasize' can be used to indicate that the source is not available or that it is skipped on stepping. /// - [Optional] public SourcePresentationHint? PresentationHint { get; set; } + [Optional] + public SourcePresentationHint? PresentationHint { get; set; } /// /// The (optional) origin of this source: possible values 'internal module', 'inlined content from source map', etc. /// - [Optional] public string Origin { get; set; } + [Optional] + public string Origin { get; set; } /// /// An optional list of sources that are related to this source. These may be the source that generated this source. /// - [Optional] public Container Sources { get; set; } + [Optional] + public Container Sources { get; set; } /// - /// Optional data that a debug adapter might want to loop through the client. The client should leave the data intact and persist it across sessions. The client should not interpret the data. + /// Optional data that a debug adapter might want to loop through the client. The client should leave the data intact and persist it across sessions. The client should not interpret + /// the data. /// - [Optional] public JToken AdapterData { get; set; } + [Optional] + public JToken AdapterData { get; set; } /// /// The checksums associated with this file. /// - [Optional] public Container Checksums { get; set; } + [Optional] + public Container Checksums { get; set; } } } diff --git a/src/Dap.Protocol/Models/SourceBreakpoint.cs b/src/Dap.Protocol/Models/SourceBreakpoint.cs index 59dd3cfe1..172a954b9 100644 --- a/src/Dap.Protocol/Models/SourceBreakpoint.cs +++ b/src/Dap.Protocol/Models/SourceBreakpoint.cs @@ -2,7 +2,8 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { - /// SourceBreakpoint + /// + /// SourceBreakpoint /// Properties of a breakpoint or logpoint passed to the setBreakpoints request. /// public class SourceBreakpoint @@ -15,21 +16,25 @@ public class SourceBreakpoint /// /// An optional source column of the breakpoint. /// - [Optional] public int? Column { get; set; } + [Optional] + public int? Column { get; set; } /// /// An optional expression for conditional breakpoints. /// - [Optional] public string Condition { get; set; } + [Optional] + public string Condition { get; set; } /// /// An optional expression that controls how many hits of the breakpoint are ignored. The backend is expected to interpret the expression as needed. /// - [Optional] public string HitCondition { get; set; } + [Optional] + public string HitCondition { get; set; } /// /// If this attribute exists and is non-empty, the backend must not 'break' (stop) but log the message instead. Expressions within {} are interpolated. /// - [Optional] public string LogMessage { get; set; } + [Optional] + public string LogMessage { get; set; } } } diff --git a/src/Dap.Protocol/Models/SourcePresentationHint.cs b/src/Dap.Protocol/Models/SourcePresentationHint.cs index 95c463ec7..774d6f270 100644 --- a/src/Dap.Protocol/Models/SourcePresentationHint.cs +++ b/src/Dap.Protocol/Models/SourcePresentationHint.cs @@ -10,4 +10,4 @@ public enum SourcePresentationHint Emphasize, Deemphasize, } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/StackFrame.cs b/src/Dap.Protocol/Models/StackFrame.cs index 43a357f2a..d36bb1d5d 100644 --- a/src/Dap.Protocol/Models/StackFrame.cs +++ b/src/Dap.Protocol/Models/StackFrame.cs @@ -8,7 +8,8 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models public class StackFrame { /// - /// An identifier for the stack frame. It must be unique across all threads. This id can be used to retrieve the scopes of the frame with the 'scopesRequest' or to restart the execution of a stackframe. + /// An identifier for the stack frame. It must be unique across all threads. This id can be used to retrieve the scopes of the frame with the 'scopesRequest' or to restart the + /// execution of a stackframe. /// public long Id { get; set; } @@ -20,7 +21,8 @@ public class StackFrame /// /// The optional source of the frame. /// - [Optional] public Source Source { get; set; } + [Optional] + public Source Source { get; set; } /// /// The line within the file of the frame. If source is null or doesn't exist, line is 0 and must be ignored. @@ -35,26 +37,32 @@ public class StackFrame /// /// An optional end line of the range covered by the stack frame. /// - [Optional] public int? EndLine { get; set; } + [Optional] + public int? EndLine { get; set; } /// /// An optional end column of the range covered by the stack frame. /// - [Optional] public int? EndColumn { get; set; } + [Optional] + public int? EndColumn { get; set; } /// /// Optional memory reference for the current instruction pointer in this frame. /// - [Optional] public string InstructionPointerReference { get; set; } + [Optional] + public string InstructionPointerReference { get; set; } /// /// The module associated with this frame, if any. /// - [Optional] public NumberString? ModuleId { get; set; } + [Optional] + public NumberString? ModuleId { get; set; } /// - /// An optional hint for how to present this frame in the UI. A value of 'label' can be used to indicate that the frame is an artificial frame that is used as a visual label or separator. A value of 'subtle' can be used to change the appearance of a frame in a 'subtle' way. + /// An optional hint for how to present this frame in the UI. A value of 'label' can be used to indicate that the frame is an artificial frame that is used as a visual label or + /// separator. A value of 'subtle' can be used to change the appearance of a frame in a 'subtle' way. /// - [Optional] public StackFramePresentationHint? PresentationHint { get; set; } + [Optional] + public StackFramePresentationHint? PresentationHint { get; set; } } } diff --git a/src/Dap.Protocol/Models/StackFrameFormat.cs b/src/Dap.Protocol/Models/StackFrameFormat.cs index b9ffd0058..dd8e0cf91 100644 --- a/src/Dap.Protocol/Models/StackFrameFormat.cs +++ b/src/Dap.Protocol/Models/StackFrameFormat.cs @@ -10,36 +10,43 @@ public class StackFrameFormat : ValueFormat /// /// Displays parameters for the stack frame. /// - [Optional] public bool? Parameters { get; set; } + [Optional] + public bool? Parameters { get; set; } /// /// Displays the types of parameters for the stack frame. /// - [Optional] public bool? ParameterTypes { get; set; } + [Optional] + public bool? ParameterTypes { get; set; } /// /// Displays the names of parameters for the stack frame. /// - [Optional] public bool? ParameterNames { get; set; } + [Optional] + public bool? ParameterNames { get; set; } /// /// Displays the values of parameters for the stack frame. /// - [Optional] public bool? ParameterValues { get; set; } + [Optional] + public bool? ParameterValues { get; set; } /// /// Displays the line long of the stack frame. /// - [Optional] public bool? Line { get; set; } + [Optional] + public bool? Line { get; set; } /// /// Displays the module of the stack frame. /// - [Optional] public bool? Module { get; set; } + [Optional] + public bool? Module { get; set; } /// /// Includes all stack frames, including those the debug adapter might otherwise hide. /// - [Optional] public bool? IncludeAll { get; set; } + [Optional] + public bool? IncludeAll { get; set; } } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/StackFramePresentationHint.cs b/src/Dap.Protocol/Models/StackFramePresentationHint.cs index e9cac0f3c..ecc21d8db 100644 --- a/src/Dap.Protocol/Models/StackFramePresentationHint.cs +++ b/src/Dap.Protocol/Models/StackFramePresentationHint.cs @@ -10,4 +10,4 @@ public enum StackFramePresentationHint Label, Subtle, } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/StepInTarget.cs b/src/Dap.Protocol/Models/StepInTarget.cs index 5dce0e983..641b91198 100644 --- a/src/Dap.Protocol/Models/StepInTarget.cs +++ b/src/Dap.Protocol/Models/StepInTarget.cs @@ -15,4 +15,4 @@ public class StepInTarget /// public string Label { get; set; } } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/SteppingGranularity.cs b/src/Dap.Protocol/Models/SteppingGranularity.cs index 5f7a465e4..d2d655b2c 100644 --- a/src/Dap.Protocol/Models/SteppingGranularity.cs +++ b/src/Dap.Protocol/Models/SteppingGranularity.cs @@ -5,9 +5,9 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { [JsonConverter(typeof(StringEnumConverter))] public enum SteppingGranularity - { - Statement, - Line, + { + Statement, + Line, Instruction, } } diff --git a/src/Dap.Protocol/Models/Thread.cs b/src/Dap.Protocol/Models/Thread.cs index 35be9951c..c29f9d3ef 100644 --- a/src/Dap.Protocol/Models/Thread.cs +++ b/src/Dap.Protocol/Models/Thread.cs @@ -15,4 +15,4 @@ public class Thread /// public string Name { get; set; } } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/ValueFormat.cs b/src/Dap.Protocol/Models/ValueFormat.cs index 8442f6465..cebaa3d7f 100644 --- a/src/Dap.Protocol/Models/ValueFormat.cs +++ b/src/Dap.Protocol/Models/ValueFormat.cs @@ -10,6 +10,7 @@ public class ValueFormat /// /// Display the value in hex. /// - [Optional] public bool? Hex { get; set; } + [Optional] + public bool? Hex { get; set; } } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/Variable.cs b/src/Dap.Protocol/Models/Variable.cs index af2244f4e..de81d72aa 100644 --- a/src/Dap.Protocol/Models/Variable.cs +++ b/src/Dap.Protocol/Models/Variable.cs @@ -25,17 +25,20 @@ public class Variable /// /// The type of the variable's value. Typically shown in the UI when hovering over the value. /// - [Optional] public string Type { get; set; } + [Optional] + public string Type { get; set; } /// /// Properties of a variable that can be used to determine how to render the variable in the UI. /// - [Optional] public VariablePresentationHint PresentationHint { get; set; } + [Optional] + public VariablePresentationHint PresentationHint { get; set; } /// /// Optional evaluatable name of this variable which can be passed to the 'EvaluateRequest' to fetch the variable's value. /// - [Optional] public string EvaluateName { get; set; } + [Optional] + public string EvaluateName { get; set; } /// /// If variablesReference is > 0, the variable is structured and its children can be retrieved by passing variablesReference to the VariablesRequest. @@ -46,17 +49,20 @@ public class Variable /// The long of named child variables. /// The client can use this optional information to present the children in a paged UI and fetch them in chunks. /// - [Optional] public long? NamedVariables { get; set; } + [Optional] + public long? NamedVariables { get; set; } /// /// The long of indexed child variables. /// The client can use this optional information to present the children in a paged UI and fetch them in chunks. /// - [Optional] public long? IndexedVariables { get; set; } + [Optional] + public long? IndexedVariables { get; set; } /// /// Optional memory reference for the variable if the variable represents executable code, such as a function pointer. /// - [Optional] public string MemoryReference { get; set; } + [Optional] + public string MemoryReference { get; set; } } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Models/VariablePresentationHint.cs b/src/Dap.Protocol/Models/VariablePresentationHint.cs index e79aaf00a..08bc4eb12 100644 --- a/src/Dap.Protocol/Models/VariablePresentationHint.cs +++ b/src/Dap.Protocol/Models/VariablePresentationHint.cs @@ -2,7 +2,8 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { - /// VariablePresentationHint + /// + /// VariablePresentationHint /// Optional properties of a variable that can be used to determine how to render the variable in the UI. /// public class VariablePresentationHint @@ -23,7 +24,8 @@ public class VariablePresentationHint /// 'dataBreakpoint': Indicates that a data breakpoint is registered for the object. /// etc. /// - [Optional] public string Kind { get; set; } + [Optional] + public string Kind { get; set; } /// /// Set of attributes represented as an array of strings. Before introducing additional values, try to use the listed values. @@ -37,12 +39,14 @@ public class VariablePresentationHint /// 'hasSideEffects': Indicates that the evaluation had side effects. /// etc. /// - [Optional] public Container Attributes { get; set; } + [Optional] + public Container Attributes { get; set; } /// /// Visibility of variable. Before introducing additional values, try to use the listed values. /// Values: 'public', 'private', 'protected', 'internal', 'final', etc. /// - [Optional] public string Visibility { get; set; } + [Optional] + public string Visibility { get; set; } } } diff --git a/src/Dap.Protocol/Requests/AttachRequestArguments.cs b/src/Dap.Protocol/Requests/AttachRequestArguments.cs index 9cba9163f..bcf1fc99a 100644 --- a/src/Dap.Protocol/Requests/AttachRequestArguments.cs +++ b/src/Dap.Protocol/Requests/AttachRequestArguments.cs @@ -1,9 +1,8 @@ -using System.Collections; using System.Collections.Generic; -using Newtonsoft.Json.Linq; -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -20,7 +19,6 @@ public class AttachRequestArguments : IRequest [JsonProperty(PropertyName = "__restart")] public JToken Restart { get; set; } - [JsonExtensionData] - public IDictionary ExtensionData { get; set; } = new Dictionary(); + [JsonExtensionData] public IDictionary ExtensionData { get; set; } = new Dictionary(); } } diff --git a/src/Dap.Protocol/Requests/AttachResponse.cs b/src/Dap.Protocol/Requests/AttachResponse.cs index d4fd074e5..06339ab55 100644 --- a/src/Dap.Protocol/Requests/AttachResponse.cs +++ b/src/Dap.Protocol/Requests/AttachResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class AttachResponse { } - } diff --git a/src/Dap.Protocol/Requests/BreakpointLocationsArguments.cs b/src/Dap.Protocol/Requests/BreakpointLocationsArguments.cs index f675c6351..9f25abe63 100644 --- a/src/Dap.Protocol/Requests/BreakpointLocationsArguments.cs +++ b/src/Dap.Protocol/Requests/BreakpointLocationsArguments.cs @@ -6,7 +6,8 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { [Method(RequestNames.BreakpointLocations, Direction.ClientToServer)] - public class BreakpointLocationsArguments : IRequest { + public class BreakpointLocationsArguments : IRequest + { /// /// The source location of the breakpoints; either 'source.path' or 'source.reference' must be specified. /// @@ -35,4 +36,4 @@ public class BreakpointLocationsArguments : IRequest /// Sorted set of possible breakpoint locations. /// public Container Breakpoints { get; set; } } -} \ No newline at end of file +} diff --git a/src/Dap.Protocol/Requests/CompletionsArguments.cs b/src/Dap.Protocol/Requests/CompletionsArguments.cs index 2e2f846ab..b70998edf 100644 --- a/src/Dap.Protocol/Requests/CompletionsArguments.cs +++ b/src/Dap.Protocol/Requests/CompletionsArguments.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -10,7 +10,8 @@ public class CompletionsArguments : IRequest /// /// Returns completions in the scope of this stack frame. If not specified, the completions are returned for the global scope. /// - [Optional] public long? FrameId { get; set; } + [Optional] + public long? FrameId { get; set; } /// /// One or more source lines.Typically this is the text a user has typed into the debug console before he asked for completion. @@ -25,7 +26,7 @@ public class CompletionsArguments : IRequest /// /// An optional line for which to determine the completion proposals.If missing the first line of the text is assumed. /// - [Optional] public long? Line { get; set; } + [Optional] + public long? Line { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/CompletionsResponse.cs b/src/Dap.Protocol/Requests/CompletionsResponse.cs index a79ecf5ea..82ca7338f 100644 --- a/src/Dap.Protocol/Requests/CompletionsResponse.cs +++ b/src/Dap.Protocol/Requests/CompletionsResponse.cs @@ -9,5 +9,4 @@ public class CompletionsResponse /// public Container Targets { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/ConfigurationDoneArguments.cs b/src/Dap.Protocol/Requests/ConfigurationDoneArguments.cs index 784f78721..2c367764d 100644 --- a/src/Dap.Protocol/Requests/ConfigurationDoneArguments.cs +++ b/src/Dap.Protocol/Requests/ConfigurationDoneArguments.cs @@ -7,5 +7,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class ConfigurationDoneArguments : IRequest { } - } diff --git a/src/Dap.Protocol/Requests/ConfigurationDoneResponse.cs b/src/Dap.Protocol/Requests/ConfigurationDoneResponse.cs index 9314455a4..341cfa8a9 100644 --- a/src/Dap.Protocol/Requests/ConfigurationDoneResponse.cs +++ b/src/Dap.Protocol/Requests/ConfigurationDoneResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class ConfigurationDoneResponse { } - } diff --git a/src/Dap.Protocol/Requests/ContinueArguments.cs b/src/Dap.Protocol/Requests/ContinueArguments.cs index e77b8407d..eaa283a7f 100644 --- a/src/Dap.Protocol/Requests/ContinueArguments.cs +++ b/src/Dap.Protocol/Requests/ContinueArguments.cs @@ -1,5 +1,3 @@ -using System.Threading; -using System.Threading.Tasks; using MediatR; using OmniSharp.Extensions.JsonRpc; @@ -9,7 +7,8 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class ContinueArguments : IRequest { /// - /// Continue execution for the specified thread(if possible). If the backend cannot continue on a single thread but will continue on all threads, it should set the 'allThreadsContinued' attribute in the response to true. + /// Continue execution for the specified thread(if possible). If the backend cannot continue on a single thread but will continue on all threads, it should set the + /// 'allThreadsContinued' attribute in the response to true. /// public long ThreadId { get; set; } } diff --git a/src/Dap.Protocol/Requests/ContinueResponse.cs b/src/Dap.Protocol/Requests/ContinueResponse.cs index 0dcf54e06..833bf72c8 100644 --- a/src/Dap.Protocol/Requests/ContinueResponse.cs +++ b/src/Dap.Protocol/Requests/ContinueResponse.cs @@ -5,9 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class ContinueResponse { /// - /// If true, the 'continue' request has ignored the specified thread and continued all threads instead.If this attribute is missing a value of 'true' is assumed for backward compatibility. + /// If true, the 'continue' request has ignored the specified thread and continued all threads instead.If this attribute is missing a value of 'true' is assumed for backward + /// compatibility. /// - [Optional] public bool? AllThreadsContinued { get; set; } + [Optional] + public bool? AllThreadsContinued { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/DataBreakpointInfoArguments.cs b/src/Dap.Protocol/Requests/DataBreakpointInfoArguments.cs index 0f605b4e0..3491383cc 100644 --- a/src/Dap.Protocol/Requests/DataBreakpointInfoArguments.cs +++ b/src/Dap.Protocol/Requests/DataBreakpointInfoArguments.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -10,12 +10,12 @@ public class DataBreakpointInfoArguments : IRequest /// /// Reference to the Variable container if the data breakpoint is requested for a child of the container. /// - [Optional] public long? VariablesReference { get; set; } + [Optional] + public long? VariablesReference { get; set; } /// /// 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; set; } } - } diff --git a/src/Dap.Protocol/Requests/DataBreakpointInfoResponse.cs b/src/Dap.Protocol/Requests/DataBreakpointInfoResponse.cs index 16be64d43..9cb278216 100644 --- a/src/Dap.Protocol/Requests/DataBreakpointInfoResponse.cs +++ b/src/Dap.Protocol/Requests/DataBreakpointInfoResponse.cs @@ -18,12 +18,13 @@ public class DataBreakpointInfoResponse /// /// Optional attribute listing the available access types for a potential data breakpoint.A UI frontend could surface this information. /// - [Optional] public Container AccessTypes { get; set; } + [Optional] + public Container AccessTypes { get; set; } /// /// Optional attribute indicating that a potential data breakpoint could be persisted across sessions. /// - [Optional] public bool? CanPersist { get; set; } + [Optional] + public bool? CanPersist { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/DisassembleArguments.cs b/src/Dap.Protocol/Requests/DisassembleArguments.cs index dd6b43629..024809c17 100644 --- a/src/Dap.Protocol/Requests/DisassembleArguments.cs +++ b/src/Dap.Protocol/Requests/DisassembleArguments.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -15,23 +15,26 @@ public class DisassembleArguments : IRequest /// /// Optional offset(in bytes) to be applied to the reference location before disassembling.Can be negative. /// - [Optional] public long? Offset { get; set; } + [Optional] + public long? Offset { get; set; } /// /// Optional offset(in instructions) to be applied after the byte offset(if any) before disassembling.Can be negative. /// - [Optional] public long? InstructionOffset { get; set; } + [Optional] + public long? InstructionOffset { get; set; } /// - /// 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. + /// 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; set; } /// /// If true, the adapter should attempt to resolve memory addresses and other values to symbolic names. /// - [Optional] public bool? ResolveSymbols { get; set; } + [Optional] + public bool? ResolveSymbols { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/DisassembleResponse.cs b/src/Dap.Protocol/Requests/DisassembleResponse.cs index f67a38715..f1efbcb06 100644 --- a/src/Dap.Protocol/Requests/DisassembleResponse.cs +++ b/src/Dap.Protocol/Requests/DisassembleResponse.cs @@ -9,5 +9,4 @@ public class DisassembleResponse /// public Container Instructions { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/DisconnectArguments.cs b/src/Dap.Protocol/Requests/DisconnectArguments.cs index 96e385a90..5b81b1ac6 100644 --- a/src/Dap.Protocol/Requests/DisconnectArguments.cs +++ b/src/Dap.Protocol/Requests/DisconnectArguments.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -10,14 +10,15 @@ public class DisconnectArguments : IRequest /// /// A value of true indicates that this 'disconnect' request is part of a restart sequence. /// - [Optional] public bool? Restart { get; set; } + [Optional] + public bool? Restart { get; set; } /// /// Indicates whether the debuggee should be terminated when the debugger is disconnected. /// If unspecified, the debug adapter is free to do whatever it thinks is best. /// A client can only rely on this attribute being properly honored if a debug adapter returns true for the 'supportTerminateDebuggee' capability. /// - [Optional] public bool? TerminateDebuggee { get; set; } + [Optional] + public bool? TerminateDebuggee { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/DisconnectResponse.cs b/src/Dap.Protocol/Requests/DisconnectResponse.cs index d028981aa..2a58dee1d 100644 --- a/src/Dap.Protocol/Requests/DisconnectResponse.cs +++ b/src/Dap.Protocol/Requests/DisconnectResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class DisconnectResponse { } - } diff --git a/src/Dap.Protocol/Requests/EvaluateArguments.cs b/src/Dap.Protocol/Requests/EvaluateArguments.cs index ab0e9f9d4..7c18b4389 100644 --- a/src/Dap.Protocol/Requests/EvaluateArguments.cs +++ b/src/Dap.Protocol/Requests/EvaluateArguments.cs @@ -1,6 +1,6 @@ +using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; -using MediatR; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -16,7 +16,8 @@ public class EvaluateArguments : IRequest /// /// Evaluate the expression in the scope of this stack frame. If not specified, the expression is evaluated in the global scope. /// - [Optional] public long? FrameId { get; set; } + [Optional] + public long? FrameId { get; set; } /// /// The context in which the evaluate request is run. @@ -26,12 +27,13 @@ public class EvaluateArguments : IRequest /// 'hover': evaluate is run from a data hover. /// etc. /// - [Optional] public string Context { get; set; } + [Optional] + public string Context { get; set; } /// /// Specifies details on how to format the Evaluate result. /// - [Optional] public ValueFormat Format { get; set; } + [Optional] + public ValueFormat Format { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/EvaluateResponse.cs b/src/Dap.Protocol/Requests/EvaluateResponse.cs index cfc22c718..6bb44b4e3 100644 --- a/src/Dap.Protocol/Requests/EvaluateResponse.cs +++ b/src/Dap.Protocol/Requests/EvaluateResponse.cs @@ -13,12 +13,14 @@ public class EvaluateResponse /// /// The optional type of the evaluate result. /// - [Optional] public string Type { get; set; } + [Optional] + public string Type { get; set; } /// /// Properties of a evaluate result that can be used to determine how to render the result in the UI. /// - [Optional] public VariablePresentationHint PresentationHint { get; set; } + [Optional] + public VariablePresentationHint PresentationHint { get; set; } /// /// If variablesReference is > 0, the evaluate result is structured and its children can be retrieved by passing variablesReference to the VariablesRequest. @@ -29,18 +31,20 @@ public class EvaluateResponse /// The number of named child variables. /// The client can use this optional information to present the variables in a paged UI and fetch them in chunks. /// - [Optional] public long? NamedVariables { get; set; } + [Optional] + public long? NamedVariables { get; set; } /// /// The number of indexed child variables. /// The client can use this optional information to present the variables in a paged UI and fetch them in chunks. /// - [Optional] public long? IndexedVariables { get; set; } + [Optional] + public long? IndexedVariables { get; set; } /// /// 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; set; } + [Optional] + public string MemoryReference { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/ExceptionInfoResponse.cs b/src/Dap.Protocol/Requests/ExceptionInfoResponse.cs index fd4e986b7..4070dfcd5 100644 --- a/src/Dap.Protocol/Requests/ExceptionInfoResponse.cs +++ b/src/Dap.Protocol/Requests/ExceptionInfoResponse.cs @@ -13,7 +13,8 @@ public class ExceptionInfoResponse /// /// Descriptive text for the exception provided by the debug adapter. /// - [Optional] public string Description { get; set; } + [Optional] + public string Description { get; set; } /// /// Mode that caused the exception notification to be raised. @@ -23,7 +24,7 @@ public class ExceptionInfoResponse /// /// Detailed information about the exception. /// - [Optional] public ExceptionDetails Details { get; set; } + [Optional] + public ExceptionDetails Details { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/GotoArguments.cs b/src/Dap.Protocol/Requests/GotoArguments.cs index fa0814304..6475246de 100644 --- a/src/Dap.Protocol/Requests/GotoArguments.cs +++ b/src/Dap.Protocol/Requests/GotoArguments.cs @@ -16,5 +16,4 @@ public class GotoArguments : IRequest /// public long TargetId { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/GotoResponse.cs b/src/Dap.Protocol/Requests/GotoResponse.cs index 606c214f1..4faf9abf5 100644 --- a/src/Dap.Protocol/Requests/GotoResponse.cs +++ b/src/Dap.Protocol/Requests/GotoResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class GotoResponse { } - } diff --git a/src/Dap.Protocol/Requests/GotoTargetsArguments.cs b/src/Dap.Protocol/Requests/GotoTargetsArguments.cs index b7b6eb1ce..2d236bbbf 100644 --- a/src/Dap.Protocol/Requests/GotoTargetsArguments.cs +++ b/src/Dap.Protocol/Requests/GotoTargetsArguments.cs @@ -1,6 +1,6 @@ +using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; -using MediatR; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -21,7 +21,7 @@ public class GotoTargetsArguments : IRequest /// /// An optional column location for which the goto targets are determined. /// - [Optional] public long? Column { get; set; } + [Optional] + public long? Column { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/GotoTargetsResponse.cs b/src/Dap.Protocol/Requests/GotoTargetsResponse.cs index eece7e037..d6b57bf0f 100644 --- a/src/Dap.Protocol/Requests/GotoTargetsResponse.cs +++ b/src/Dap.Protocol/Requests/GotoTargetsResponse.cs @@ -9,5 +9,4 @@ public class GotoTargetsResponse /// public Container Targets { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/IAttachHandler.cs b/src/Dap.Protocol/Requests/IAttachHandler.cs index 6b1df0afe..539afbf07 100644 --- a/src/Dap.Protocol/Requests/IAttachHandler.cs +++ b/src/Dap.Protocol/Requests/IAttachHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Attach, Direction.ClientToServer)] - [GenerateHandlerMethods(AllowDerivedRequests = true), GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Attach, Direction.ClientToServer)] + [GenerateHandlerMethods(AllowDerivedRequests = true)] + [GenerateRequestMethods] public interface IAttachHandler : IJsonRpcRequestHandler where T : AttachRequestArguments { } diff --git a/src/Dap.Protocol/Requests/IBreakpointLocationsHandler.cs b/src/Dap.Protocol/Requests/IBreakpointLocationsHandler.cs index a175541de..ad2d83d8a 100644 --- a/src/Dap.Protocol/Requests/IBreakpointLocationsHandler.cs +++ b/src/Dap.Protocol/Requests/IBreakpointLocationsHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.BreakpointLocations, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.BreakpointLocations, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IBreakpointLocationsHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/ICancelHandler.cs b/src/Dap.Protocol/Requests/ICancelHandler.cs index 2de9af4f6..a90cf7eb0 100644 --- a/src/Dap.Protocol/Requests/ICancelHandler.cs +++ b/src/Dap.Protocol/Requests/ICancelHandler.cs @@ -9,8 +9,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests /// DAP is kind of silly.... /// Cancellation is for requests and progress tokens... hopefully if isn't ever expanded any further... because that would be fun. /// - [Parallel, Method(RequestNames.Cancel, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Cancel, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface ICancelHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/ICompletionsHandler.cs b/src/Dap.Protocol/Requests/ICompletionsHandler.cs index c700fc23f..ed6b41611 100644 --- a/src/Dap.Protocol/Requests/ICompletionsHandler.cs +++ b/src/Dap.Protocol/Requests/ICompletionsHandler.cs @@ -5,9 +5,13 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Completions, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] - public interface ICompletionsHandler : IJsonRpcRequestHandler { } + [Parallel] + [Method(RequestNames.Completions, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] + public interface ICompletionsHandler : IJsonRpcRequestHandler + { + } public abstract class CompletionsHandler : ICompletionsHandler { diff --git a/src/Dap.Protocol/Requests/IConfigurationDoneHandler.cs b/src/Dap.Protocol/Requests/IConfigurationDoneHandler.cs index 4f117e586..e8c7cc1ee 100644 --- a/src/Dap.Protocol/Requests/IConfigurationDoneHandler.cs +++ b/src/Dap.Protocol/Requests/IConfigurationDoneHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.ConfigurationDone, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.ConfigurationDone, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IConfigurationDoneHandler : IJsonRpcRequestHandler { @@ -14,7 +16,9 @@ public interface public abstract class ConfigurationDoneHandler : IConfigurationDoneHandler { - public abstract Task Handle(ConfigurationDoneArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + ConfigurationDoneArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/IContinueHandler.cs b/src/Dap.Protocol/Requests/IContinueHandler.cs index a682a180e..d610bbd8d 100644 --- a/src/Dap.Protocol/Requests/IContinueHandler.cs +++ b/src/Dap.Protocol/Requests/IContinueHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Continue, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Continue, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IContinueHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/IDataBreakpointInfoHandler.cs b/src/Dap.Protocol/Requests/IDataBreakpointInfoHandler.cs index 021d603a3..dddf32999 100644 --- a/src/Dap.Protocol/Requests/IDataBreakpointInfoHandler.cs +++ b/src/Dap.Protocol/Requests/IDataBreakpointInfoHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc; @@ -6,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.DataBreakpointInfo, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.DataBreakpointInfo, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IDataBreakpointInfoHandler : IJsonRpcRequestHandler { @@ -15,7 +16,9 @@ public interface public abstract class DataBreakpointInfoHandler : IDataBreakpointInfoHandler { - public abstract Task Handle(DataBreakpointInfoArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + DataBreakpointInfoArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/IDebugAdapterInitializeHandler.cs b/src/Dap.Protocol/Requests/IDebugAdapterInitializeHandler.cs index c1ac5de19..eb5298540 100644 --- a/src/Dap.Protocol/Requests/IDebugAdapterInitializeHandler.cs +++ b/src/Dap.Protocol/Requests/IDebugAdapterInitializeHandler.cs @@ -1,20 +1,23 @@ using System.Threading; using System.Threading.Tasks; -using OmniSharp.Extensions.DebugAdapter.Protocol.Client; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Initialize, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Initialize, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IDebugAdapterInitializeHandler : IJsonRpcRequestHandler { } public abstract class DebugAdapterInitializeHandler : IDebugAdapterInitializeHandler { - public abstract Task Handle(InitializeRequestArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + InitializeRequestArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/IDisassembleHandler.cs b/src/Dap.Protocol/Requests/IDisassembleHandler.cs index 31969f7c5..59bbbc0ed 100644 --- a/src/Dap.Protocol/Requests/IDisassembleHandler.cs +++ b/src/Dap.Protocol/Requests/IDisassembleHandler.cs @@ -5,15 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Disassemble, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Disassemble, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IDisassembleHandler : IJsonRpcRequestHandler { } public abstract class DisassembleHandler : IDisassembleHandler { - public abstract Task Handle(DisassembleArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + DisassembleArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/IDisconnectHandler.cs b/src/Dap.Protocol/Requests/IDisconnectHandler.cs index 73c41c5ec..3583e86df 100644 --- a/src/Dap.Protocol/Requests/IDisconnectHandler.cs +++ b/src/Dap.Protocol/Requests/IDisconnectHandler.cs @@ -5,15 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Disconnect, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Disconnect, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IDisconnectHandler : IJsonRpcRequestHandler { } public abstract class DisconnectHandler : IDisconnectHandler { - public abstract Task Handle(DisconnectArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + DisconnectArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/IEvaluateHandler.cs b/src/Dap.Protocol/Requests/IEvaluateHandler.cs index c87eb01a7..3cb7a9a97 100644 --- a/src/Dap.Protocol/Requests/IEvaluateHandler.cs +++ b/src/Dap.Protocol/Requests/IEvaluateHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Evaluate, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Evaluate, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IEvaluateHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/IExceptionInfoHandler.cs b/src/Dap.Protocol/Requests/IExceptionInfoHandler.cs index 7d6031005..fcb2044ac 100644 --- a/src/Dap.Protocol/Requests/IExceptionInfoHandler.cs +++ b/src/Dap.Protocol/Requests/IExceptionInfoHandler.cs @@ -5,15 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.ExceptionInfo, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.ExceptionInfo, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IExceptionInfoHandler : IJsonRpcRequestHandler { } public abstract class ExceptionInfoHandler : IExceptionInfoHandler { - public abstract Task Handle(ExceptionInfoArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + ExceptionInfoArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/IGotoHandler.cs b/src/Dap.Protocol/Requests/IGotoHandler.cs index 46d15be6c..e7b10f35f 100644 --- a/src/Dap.Protocol/Requests/IGotoHandler.cs +++ b/src/Dap.Protocol/Requests/IGotoHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Goto, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Goto, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IGotoHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/IGotoTargetsHandler.cs b/src/Dap.Protocol/Requests/IGotoTargetsHandler.cs index bd5d5f805..381429062 100644 --- a/src/Dap.Protocol/Requests/IGotoTargetsHandler.cs +++ b/src/Dap.Protocol/Requests/IGotoTargetsHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.GotoTargets, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.GotoTargets, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IGotoTargetsHandler : IJsonRpcRequestHandler { } @@ -14,7 +16,9 @@ public interface IGotoTargetsHandler : IJsonRpcRequestHandler Handle(GotoTargetsArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + GotoTargetsArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/ILaunchHandler.cs b/src/Dap.Protocol/Requests/ILaunchHandler.cs index 44b8a6e92..98a0afe0e 100644 --- a/src/Dap.Protocol/Requests/ILaunchHandler.cs +++ b/src/Dap.Protocol/Requests/ILaunchHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Launch, Direction.ClientToServer)] - [GenerateHandlerMethods(AllowDerivedRequests = true), GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Launch, Direction.ClientToServer)] + [GenerateHandlerMethods(AllowDerivedRequests = true)] + [GenerateRequestMethods] public interface ILaunchHandler : IJsonRpcRequestHandler where T : LaunchRequestArguments { } diff --git a/src/Dap.Protocol/Requests/ILoadedSourcesHandler.cs b/src/Dap.Protocol/Requests/ILoadedSourcesHandler.cs index 3c1795275..4810d3d29 100644 --- a/src/Dap.Protocol/Requests/ILoadedSourcesHandler.cs +++ b/src/Dap.Protocol/Requests/ILoadedSourcesHandler.cs @@ -5,15 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.LoadedSources, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.LoadedSources, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface ILoadedSourcesHandler : IJsonRpcRequestHandler { } public abstract class LoadedSourcesHandler : ILoadedSourcesHandler { - public abstract Task Handle(LoadedSourcesArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + LoadedSourcesArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/IModulesHandler.cs b/src/Dap.Protocol/Requests/IModulesHandler.cs index 2a0fdb3d0..a023f1325 100644 --- a/src/Dap.Protocol/Requests/IModulesHandler.cs +++ b/src/Dap.Protocol/Requests/IModulesHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Modules, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Modules, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IModulesHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/INextHandler.cs b/src/Dap.Protocol/Requests/INextHandler.cs index f55a74139..2e85d22eb 100644 --- a/src/Dap.Protocol/Requests/INextHandler.cs +++ b/src/Dap.Protocol/Requests/INextHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Next, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Next, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface INextHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/IPauseHandler.cs b/src/Dap.Protocol/Requests/IPauseHandler.cs index 52987cf03..e8625f2ba 100644 --- a/src/Dap.Protocol/Requests/IPauseHandler.cs +++ b/src/Dap.Protocol/Requests/IPauseHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Pause, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Pause, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IPauseHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/IReadMemoryHandler.cs b/src/Dap.Protocol/Requests/IReadMemoryHandler.cs index 485894446..5b0839761 100644 --- a/src/Dap.Protocol/Requests/IReadMemoryHandler.cs +++ b/src/Dap.Protocol/Requests/IReadMemoryHandler.cs @@ -5,15 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.ReadMemory, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.ReadMemory, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IReadMemoryHandler : IJsonRpcRequestHandler { } public abstract class ReadMemoryHandler : IReadMemoryHandler { - public abstract Task Handle(ReadMemoryArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + ReadMemoryArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/IRestartFrameHandler.cs b/src/Dap.Protocol/Requests/IRestartFrameHandler.cs index c3eff9da0..474415ab7 100644 --- a/src/Dap.Protocol/Requests/IRestartFrameHandler.cs +++ b/src/Dap.Protocol/Requests/IRestartFrameHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc; @@ -6,15 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.RestartFrame, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.RestartFrame, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IRestartFrameHandler : IJsonRpcRequestHandler { } public abstract class RestartFrameHandler : IRestartFrameHandler { - public abstract Task Handle(RestartFrameArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + RestartFrameArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/IRestartHandler.cs b/src/Dap.Protocol/Requests/IRestartHandler.cs index d96b3ec10..52e8d4d14 100644 --- a/src/Dap.Protocol/Requests/IRestartHandler.cs +++ b/src/Dap.Protocol/Requests/IRestartHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Restart, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Restart, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IRestartHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/IReverseContinueHandler.cs b/src/Dap.Protocol/Requests/IReverseContinueHandler.cs index 954708a9d..379d9a876 100644 --- a/src/Dap.Protocol/Requests/IReverseContinueHandler.cs +++ b/src/Dap.Protocol/Requests/IReverseContinueHandler.cs @@ -5,15 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.ReverseContinue, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.ReverseContinue, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IReverseContinueHandler : IJsonRpcRequestHandler { } public abstract class ReverseContinueHandler : IReverseContinueHandler { - public abstract Task Handle(ReverseContinueArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + ReverseContinueArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/IRunInTerminalHandler.cs b/src/Dap.Protocol/Requests/IRunInTerminalHandler.cs index 760175ecd..fed3be45d 100644 --- a/src/Dap.Protocol/Requests/IRunInTerminalHandler.cs +++ b/src/Dap.Protocol/Requests/IRunInTerminalHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.RunInTerminal, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.RunInTerminal, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IRunInTerminalHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/IScopesHandler.cs b/src/Dap.Protocol/Requests/IScopesHandler.cs index 901e508d5..cb1eaf6da 100644 --- a/src/Dap.Protocol/Requests/IScopesHandler.cs +++ b/src/Dap.Protocol/Requests/IScopesHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Scopes, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Scopes, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IScopesHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/ISetBreakpointsHandler.cs b/src/Dap.Protocol/Requests/ISetBreakpointsHandler.cs index 310f7b772..adecde255 100644 --- a/src/Dap.Protocol/Requests/ISetBreakpointsHandler.cs +++ b/src/Dap.Protocol/Requests/ISetBreakpointsHandler.cs @@ -5,15 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.SetBreakpoints, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.SetBreakpoints, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface ISetBreakpointsHandler : IJsonRpcRequestHandler { } public abstract class SetBreakpointsHandler : ISetBreakpointsHandler { - public abstract Task Handle(SetBreakpointsArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + SetBreakpointsArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/ISetDataBreakpointsHandler.cs b/src/Dap.Protocol/Requests/ISetDataBreakpointsHandler.cs index ab038e48d..f8d2e2f6d 100644 --- a/src/Dap.Protocol/Requests/ISetDataBreakpointsHandler.cs +++ b/src/Dap.Protocol/Requests/ISetDataBreakpointsHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.SetDataBreakpoints, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.SetDataBreakpoints, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface ISetDataBreakpointsHandler : IJsonRpcRequestHandler { @@ -14,7 +16,9 @@ public interface public abstract class SetDataBreakpointsHandler : ISetDataBreakpointsHandler { - public abstract Task Handle(SetDataBreakpointsArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + SetDataBreakpointsArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/ISetExceptionBreakpointsHandler.cs b/src/Dap.Protocol/Requests/ISetExceptionBreakpointsHandler.cs index 1fee0ea62..ccc486be5 100644 --- a/src/Dap.Protocol/Requests/ISetExceptionBreakpointsHandler.cs +++ b/src/Dap.Protocol/Requests/ISetExceptionBreakpointsHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.SetExceptionBreakpoints, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.SetExceptionBreakpoints, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface ISetExceptionBreakpointsHandler : IJsonRpcRequestHandler { @@ -14,7 +16,9 @@ public interface ISetExceptionBreakpointsHandler : IJsonRpcRequestHandler Handle(SetExceptionBreakpointsArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + SetExceptionBreakpointsArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/ISetExpressionHandler.cs b/src/Dap.Protocol/Requests/ISetExpressionHandler.cs index d67336c1c..680eae018 100644 --- a/src/Dap.Protocol/Requests/ISetExpressionHandler.cs +++ b/src/Dap.Protocol/Requests/ISetExpressionHandler.cs @@ -5,15 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.SetExpression, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.SetExpression, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface ISetExpressionHandler : IJsonRpcRequestHandler { } public abstract class SetExpressionHandler : ISetExpressionHandler { - public abstract Task Handle(SetExpressionArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + SetExpressionArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/ISetFunctionBreakpointsHandler.cs b/src/Dap.Protocol/Requests/ISetFunctionBreakpointsHandler.cs index c750b8ac8..f369ecd2f 100644 --- a/src/Dap.Protocol/Requests/ISetFunctionBreakpointsHandler.cs +++ b/src/Dap.Protocol/Requests/ISetFunctionBreakpointsHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.SetFunctionBreakpoints, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.SetFunctionBreakpoints, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface ISetFunctionBreakpointsHandler : IJsonRpcRequestHandler @@ -15,7 +17,9 @@ public interface public abstract class SetFunctionBreakpointsHandler : ISetFunctionBreakpointsHandler { - public abstract Task Handle(SetFunctionBreakpointsArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + SetFunctionBreakpointsArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/ISetInstructionBreakpointsHandler.cs b/src/Dap.Protocol/Requests/ISetInstructionBreakpointsHandler.cs index 9bdc2f10e..dcf6b8fdf 100644 --- a/src/Dap.Protocol/Requests/ISetInstructionBreakpointsHandler.cs +++ b/src/Dap.Protocol/Requests/ISetInstructionBreakpointsHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.SetInstructionBreakpoints, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.SetInstructionBreakpoints, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface ISetInstructionBreakpointsHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/ISetVariableHandler.cs b/src/Dap.Protocol/Requests/ISetVariableHandler.cs index 50acbc4dc..6614f4292 100644 --- a/src/Dap.Protocol/Requests/ISetVariableHandler.cs +++ b/src/Dap.Protocol/Requests/ISetVariableHandler.cs @@ -5,15 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.SetVariable, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.SetVariable, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface ISetVariableHandler : IJsonRpcRequestHandler { } public abstract class SetVariableHandler : ISetVariableHandler { - public abstract Task Handle(SetVariableArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + SetVariableArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/ISourceHandler.cs b/src/Dap.Protocol/Requests/ISourceHandler.cs index a24cd8916..fd657068a 100644 --- a/src/Dap.Protocol/Requests/ISourceHandler.cs +++ b/src/Dap.Protocol/Requests/ISourceHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Source, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Source, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface ISourceHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/IStackTraceHandler.cs b/src/Dap.Protocol/Requests/IStackTraceHandler.cs index 6939e09b0..28b0fb03f 100644 --- a/src/Dap.Protocol/Requests/IStackTraceHandler.cs +++ b/src/Dap.Protocol/Requests/IStackTraceHandler.cs @@ -5,15 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.StackTrace, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.StackTrace, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IStackTraceHandler : IJsonRpcRequestHandler { } public abstract class StackTraceHandler : IStackTraceHandler { - public abstract Task Handle(StackTraceArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + StackTraceArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/IStepBackHandler.cs b/src/Dap.Protocol/Requests/IStepBackHandler.cs index 3619ab306..0210d70ad 100644 --- a/src/Dap.Protocol/Requests/IStepBackHandler.cs +++ b/src/Dap.Protocol/Requests/IStepBackHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.StepBack, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.StepBack, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IStepBackHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/IStepInHandler.cs b/src/Dap.Protocol/Requests/IStepInHandler.cs index ea9892276..6f4c1fe08 100644 --- a/src/Dap.Protocol/Requests/IStepInHandler.cs +++ b/src/Dap.Protocol/Requests/IStepInHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.StepIn, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.StepIn, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IStepInHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/IStepInTargetsHandler.cs b/src/Dap.Protocol/Requests/IStepInTargetsHandler.cs index 8f65db0cd..bc0d67888 100644 --- a/src/Dap.Protocol/Requests/IStepInTargetsHandler.cs +++ b/src/Dap.Protocol/Requests/IStepInTargetsHandler.cs @@ -5,15 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.StepInTargets, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.StepInTargets, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IStepInTargetsHandler : IJsonRpcRequestHandler { } public abstract class StepInTargetsHandler : IStepInTargetsHandler { - public abstract Task Handle(StepInTargetsArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + StepInTargetsArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/IStepOutHandler.cs b/src/Dap.Protocol/Requests/IStepOutHandler.cs index 0c513f90e..252c40a2a 100644 --- a/src/Dap.Protocol/Requests/IStepOutHandler.cs +++ b/src/Dap.Protocol/Requests/IStepOutHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.StepOut, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.StepOut, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IStepOutHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/ITerminateHandler.cs b/src/Dap.Protocol/Requests/ITerminateHandler.cs index 914c92ea1..100c5ad9e 100644 --- a/src/Dap.Protocol/Requests/ITerminateHandler.cs +++ b/src/Dap.Protocol/Requests/ITerminateHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Terminate, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Terminate, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface ITerminateHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/ITerminateThreadsHandler.cs b/src/Dap.Protocol/Requests/ITerminateThreadsHandler.cs index 106b6b8a7..eb46155ef 100644 --- a/src/Dap.Protocol/Requests/ITerminateThreadsHandler.cs +++ b/src/Dap.Protocol/Requests/ITerminateThreadsHandler.cs @@ -5,15 +5,19 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.TerminateThreads, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.TerminateThreads, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface ITerminateThreadsHandler : IJsonRpcRequestHandler { } public abstract class TerminateThreadsHandler : ITerminateThreadsHandler { - public abstract Task Handle(TerminateThreadsArguments request, - CancellationToken cancellationToken); + public abstract Task Handle( + TerminateThreadsArguments request, + CancellationToken cancellationToken + ); } } diff --git a/src/Dap.Protocol/Requests/IThreadsHandler.cs b/src/Dap.Protocol/Requests/IThreadsHandler.cs index db70d9786..297a3be16 100644 --- a/src/Dap.Protocol/Requests/IThreadsHandler.cs +++ b/src/Dap.Protocol/Requests/IThreadsHandler.cs @@ -5,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Threads, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Threads, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IThreadsHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/IVariablesHandler.cs b/src/Dap.Protocol/Requests/IVariablesHandler.cs index 76d57ea36..98b1ae590 100644 --- a/src/Dap.Protocol/Requests/IVariablesHandler.cs +++ b/src/Dap.Protocol/Requests/IVariablesHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc; @@ -6,8 +5,10 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - [Parallel, Method(RequestNames.Variables, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods] + [Parallel] + [Method(RequestNames.Variables, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IVariablesHandler : IJsonRpcRequestHandler { } diff --git a/src/Dap.Protocol/Requests/InitializeRequestArguments.cs b/src/Dap.Protocol/Requests/InitializeRequestArguments.cs index 50a82160d..84c4287ed 100644 --- a/src/Dap.Protocol/Requests/InitializeRequestArguments.cs +++ b/src/Dap.Protocol/Requests/InitializeRequestArguments.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -11,13 +11,15 @@ public class InitializeRequestArguments : IRequest, IInitial /// The ID of the(frontend) client using this adapter. /// - [Optional] public string ClientId { get; set; } + [Optional] + public string ClientId { get; set; } /// /// The human readable name of the(frontend) client using this adapter. /// - [Optional] public string ClientName { get; set; } + [Optional] + public string ClientName { get; set; } /// /// The ID of the debug adapter. @@ -28,48 +30,56 @@ public class InitializeRequestArguments : IRequest, IInitial /// The ISO-639 locale of the(frontend) client using this adapter, e.g.en-US or de-CH. /// - [Optional] public string Locale { get; set; } + [Optional] + public string Locale { get; set; } /// /// If true all line numbers are 1-based(default). /// - [Optional] public bool? LinesStartAt1 { get; set; } + [Optional] + public bool? LinesStartAt1 { get; set; } /// /// If true all column numbers are 1-based(default). /// - [Optional] public bool? ColumnsStartAt1 { get; set; } + [Optional] + public bool? ColumnsStartAt1 { get; set; } /// /// Determines in what format paths are specified.The default is 'path', which is the native format. /// Values: 'path', 'uri', etc. /// - [Optional] public string PathFormat { get; set; } + [Optional] + public string PathFormat { get; set; } /// /// Client supports the optional type attribute for variables. /// - [Optional] public bool? SupportsVariableType { get; set; } + [Optional] + public bool? SupportsVariableType { get; set; } /// /// Client supports the paging of variables. /// - [Optional] public bool? SupportsVariablePaging { get; set; } + [Optional] + public bool? SupportsVariablePaging { get; set; } /// /// Client supports the runInTerminal request. /// - [Optional] public bool? SupportsRunInTerminalRequest { get; set; } + [Optional] + public bool? SupportsRunInTerminalRequest { get; set; } /// /// Client supports memory references. /// - [Optional] public bool? SupportsMemoryReferences { get; set; } + [Optional] + public bool? SupportsMemoryReferences { get; set; } /// /// Client supports progress reporting. /// - [Optional] public bool? SupportsProgressReporting { get; set; } + [Optional] + public bool? SupportsProgressReporting { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/InitializeResponse.cs b/src/Dap.Protocol/Requests/InitializeResponse.cs index 14deaaf4e..0606368e8 100644 --- a/src/Dap.Protocol/Requests/InitializeResponse.cs +++ b/src/Dap.Protocol/Requests/InitializeResponse.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests { - public class InitializeResponse : Capabilities {} + public class InitializeResponse : Capabilities + { + } } diff --git a/src/Dap.Protocol/Requests/LaunchRequestArguments.cs b/src/Dap.Protocol/Requests/LaunchRequestArguments.cs index 4891c6e19..8476000e7 100644 --- a/src/Dap.Protocol/Requests/LaunchRequestArguments.cs +++ b/src/Dap.Protocol/Requests/LaunchRequestArguments.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using Newtonsoft.Json.Linq; -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -25,7 +25,6 @@ public class LaunchRequestArguments : IRequest [JsonProperty(PropertyName = "__restart")] public JToken Restart { get; set; } - [JsonExtensionData] - public IDictionary ExtensionData { get; set; } = new Dictionary(); + [JsonExtensionData] public IDictionary ExtensionData { get; set; } = new Dictionary(); } } diff --git a/src/Dap.Protocol/Requests/LaunchResponse.cs b/src/Dap.Protocol/Requests/LaunchResponse.cs index 134489d56..d9440bc23 100644 --- a/src/Dap.Protocol/Requests/LaunchResponse.cs +++ b/src/Dap.Protocol/Requests/LaunchResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class LaunchResponse { } - } diff --git a/src/Dap.Protocol/Requests/LoadedSourcesArguments.cs b/src/Dap.Protocol/Requests/LoadedSourcesArguments.cs index 1d08762b1..bdbde448a 100644 --- a/src/Dap.Protocol/Requests/LoadedSourcesArguments.cs +++ b/src/Dap.Protocol/Requests/LoadedSourcesArguments.cs @@ -7,5 +7,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class LoadedSourcesArguments : IRequest { } - } diff --git a/src/Dap.Protocol/Requests/LoadedSourcesResponse.cs b/src/Dap.Protocol/Requests/LoadedSourcesResponse.cs index 1160715c5..437020110 100644 --- a/src/Dap.Protocol/Requests/LoadedSourcesResponse.cs +++ b/src/Dap.Protocol/Requests/LoadedSourcesResponse.cs @@ -9,5 +9,4 @@ public class LoadedSourcesResponse /// public Container Sources { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/ModulesArguments.cs b/src/Dap.Protocol/Requests/ModulesArguments.cs index 5c54d0403..f33bd9eda 100644 --- a/src/Dap.Protocol/Requests/ModulesArguments.cs +++ b/src/Dap.Protocol/Requests/ModulesArguments.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -10,12 +10,13 @@ public class ModulesArguments : IRequest /// /// The index of the first module to return; if omitted modules start at 0. /// - [Optional] public long? StartModule { get; set; } + [Optional] + public long? StartModule { get; set; } /// /// The number of modules to return. If moduleCount is not specified or 0, all modules are returned. /// - [Optional] public long? ModuleCount { get; set; } + [Optional] + public long? ModuleCount { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/ModulesResponse.cs b/src/Dap.Protocol/Requests/ModulesResponse.cs index a535b266b..f9d11943b 100644 --- a/src/Dap.Protocol/Requests/ModulesResponse.cs +++ b/src/Dap.Protocol/Requests/ModulesResponse.cs @@ -13,7 +13,7 @@ public class ModulesResponse /// /// The total number of modules available. /// - [Optional] public long? TotalModules { get; set; } + [Optional] + public long? TotalModules { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/NextResponse.cs b/src/Dap.Protocol/Requests/NextResponse.cs index 71aa9839a..7596c3f22 100644 --- a/src/Dap.Protocol/Requests/NextResponse.cs +++ b/src/Dap.Protocol/Requests/NextResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class NextResponse { } - } diff --git a/src/Dap.Protocol/Requests/PauseArguments.cs b/src/Dap.Protocol/Requests/PauseArguments.cs index 3a5ff40bf..2501fbebd 100644 --- a/src/Dap.Protocol/Requests/PauseArguments.cs +++ b/src/Dap.Protocol/Requests/PauseArguments.cs @@ -11,5 +11,4 @@ public class PauseArguments : IRequest /// public long ThreadId { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/PauseResponse.cs b/src/Dap.Protocol/Requests/PauseResponse.cs index 5fd71fc6b..8a270ea42 100644 --- a/src/Dap.Protocol/Requests/PauseResponse.cs +++ b/src/Dap.Protocol/Requests/PauseResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class PauseResponse { } - } diff --git a/src/Dap.Protocol/Requests/ReadMemoryArguments.cs b/src/Dap.Protocol/Requests/ReadMemoryArguments.cs index 9665098e6..c00072de3 100644 --- a/src/Dap.Protocol/Requests/ReadMemoryArguments.cs +++ b/src/Dap.Protocol/Requests/ReadMemoryArguments.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -16,12 +16,12 @@ public class ReadMemoryArguments : IRequest /// Optional offset(in bytes) to be applied to the reference location before reading data.Can be negative. /// - [Optional] public long? Offset { get; set; } + [Optional] + public long? Offset { get; set; } /// /// Number of bytes to read at the specified location and offset. /// public long Count { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/ReadMemoryResponse.cs b/src/Dap.Protocol/Requests/ReadMemoryResponse.cs index ecd5a70b5..088711596 100644 --- a/src/Dap.Protocol/Requests/ReadMemoryResponse.cs +++ b/src/Dap.Protocol/Requests/ReadMemoryResponse.cs @@ -10,14 +10,16 @@ public class ReadMemoryResponse public string Address { get; set; } /// - /// 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. + /// 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] public long? UnreadableBytes { get; set; } + [Optional] + public long? UnreadableBytes { get; set; } /// /// The bytes read from memory, encoded using base64. /// - [Optional] public string Data { get; set; } + [Optional] + public string Data { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/RequestNames.cs b/src/Dap.Protocol/Requests/RequestNames.cs index 8cde9591f..4ab071834 100644 --- a/src/Dap.Protocol/Requests/RequestNames.cs +++ b/src/Dap.Protocol/Requests/RequestNames.cs @@ -46,5 +46,4 @@ public static class RequestNames public const string RunInTerminal = "runInTerminal"; public const string Cancel = "cancel"; } - } diff --git a/src/Dap.Protocol/Requests/RestartArguments.cs b/src/Dap.Protocol/Requests/RestartArguments.cs index 75faebbcf..bb5f67042 100644 --- a/src/Dap.Protocol/Requests/RestartArguments.cs +++ b/src/Dap.Protocol/Requests/RestartArguments.cs @@ -7,5 +7,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class RestartArguments : IRequest { } - } diff --git a/src/Dap.Protocol/Requests/RestartFrameArguments.cs b/src/Dap.Protocol/Requests/RestartFrameArguments.cs index 302e6c8fe..58c181677 100644 --- a/src/Dap.Protocol/Requests/RestartFrameArguments.cs +++ b/src/Dap.Protocol/Requests/RestartFrameArguments.cs @@ -11,5 +11,4 @@ public class RestartFrameArguments : IRequest /// public long FrameId { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/RestartFrameResponse.cs b/src/Dap.Protocol/Requests/RestartFrameResponse.cs index b227a6bc3..45bbe22b8 100644 --- a/src/Dap.Protocol/Requests/RestartFrameResponse.cs +++ b/src/Dap.Protocol/Requests/RestartFrameResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class RestartFrameResponse { } - } diff --git a/src/Dap.Protocol/Requests/RestartResponse.cs b/src/Dap.Protocol/Requests/RestartResponse.cs index 64515d622..5ff989df7 100644 --- a/src/Dap.Protocol/Requests/RestartResponse.cs +++ b/src/Dap.Protocol/Requests/RestartResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class RestartResponse { } - } diff --git a/src/Dap.Protocol/Requests/ReverseContinueArguments.cs b/src/Dap.Protocol/Requests/ReverseContinueArguments.cs index 863843f6d..5b08987ea 100644 --- a/src/Dap.Protocol/Requests/ReverseContinueArguments.cs +++ b/src/Dap.Protocol/Requests/ReverseContinueArguments.cs @@ -11,5 +11,4 @@ public class ReverseContinueArguments : IRequest /// public long ThreadId { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/ReverseContinueResponse.cs b/src/Dap.Protocol/Requests/ReverseContinueResponse.cs index e7a13baaf..575b7df83 100644 --- a/src/Dap.Protocol/Requests/ReverseContinueResponse.cs +++ b/src/Dap.Protocol/Requests/ReverseContinueResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class ReverseContinueResponse { } - } diff --git a/src/Dap.Protocol/Requests/RunInTerminalArguments.cs b/src/Dap.Protocol/Requests/RunInTerminalArguments.cs index 5d7482678..593cd06ac 100644 --- a/src/Dap.Protocol/Requests/RunInTerminalArguments.cs +++ b/src/Dap.Protocol/Requests/RunInTerminalArguments.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; +using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; -using MediatR; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -12,12 +12,14 @@ public class RunInTerminalArguments : IRequest /// /// What kind of terminal to launch. /// - [Optional] public RunInTerminalArgumentsKind? Kind { get; set; } + [Optional] + public RunInTerminalArgumentsKind? Kind { get; set; } /// /// Optional title of the terminal. /// - [Optional] public string Title { get; set; } + [Optional] + public string Title { get; set; } /// /// Working directory of the command. @@ -32,7 +34,7 @@ public class RunInTerminalArguments : IRequest /// /// Environment key-value pairs that are added to or removed from the default environment. /// - [Optional] public IDictionary Env { get; set; } + [Optional] + public IDictionary Env { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/RunInTerminalArgumentsKind.cs b/src/Dap.Protocol/Requests/RunInTerminalArgumentsKind.cs index 3688f2a19..0c9261d14 100644 --- a/src/Dap.Protocol/Requests/RunInTerminalArgumentsKind.cs +++ b/src/Dap.Protocol/Requests/RunInTerminalArgumentsKind.cs @@ -9,5 +9,4 @@ public enum RunInTerminalArgumentsKind Integrated, External } - } diff --git a/src/Dap.Protocol/Requests/RunInTerminalResponse.cs b/src/Dap.Protocol/Requests/RunInTerminalResponse.cs index c8343355c..1abad903b 100644 --- a/src/Dap.Protocol/Requests/RunInTerminalResponse.cs +++ b/src/Dap.Protocol/Requests/RunInTerminalResponse.cs @@ -7,12 +7,13 @@ public class RunInTerminalResponse /// /// The process ID. /// - [Optional] public long? ProcessId { get; set; } + [Optional] + public long? ProcessId { get; set; } /// /// The process ID of the terminal shell. /// - [Optional] public long? ShellProcessId { get; set; } + [Optional] + public long? ShellProcessId { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/ScopesArguments.cs b/src/Dap.Protocol/Requests/ScopesArguments.cs index def15c81e..4a619febc 100644 --- a/src/Dap.Protocol/Requests/ScopesArguments.cs +++ b/src/Dap.Protocol/Requests/ScopesArguments.cs @@ -11,5 +11,4 @@ public class ScopesArguments : IRequest /// public long FrameId { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/ScopesResponse.cs b/src/Dap.Protocol/Requests/ScopesResponse.cs index d398fb6a8..378a2aee6 100644 --- a/src/Dap.Protocol/Requests/ScopesResponse.cs +++ b/src/Dap.Protocol/Requests/ScopesResponse.cs @@ -9,5 +9,4 @@ public class ScopesResponse /// public Container Scopes { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/SetBreakpointsArguments.cs b/src/Dap.Protocol/Requests/SetBreakpointsArguments.cs index 71c788786..9d7bc4ae4 100644 --- a/src/Dap.Protocol/Requests/SetBreakpointsArguments.cs +++ b/src/Dap.Protocol/Requests/SetBreakpointsArguments.cs @@ -1,7 +1,7 @@ using System; +using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; -using MediatR; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -17,18 +17,20 @@ public class SetBreakpointsArguments : IRequest /// /// The code locations of the breakpoints. /// - [Optional] public Container Breakpoints { get; set; } + [Optional] + public Container Breakpoints { get; set; } /// /// Deprecated: The code locations of the breakpoints. /// [Obsolete("Deprecated")] - [Optional] public Container Lines { get; set; } + [Optional] + public Container Lines { get; set; } /// /// A value of true indicates that the underlying source has been modified which results in new breakpoint locations. /// - [Optional] public bool? SourceModified { get; set; } + [Optional] + public bool? SourceModified { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/SetBreakpointsResponse.cs b/src/Dap.Protocol/Requests/SetBreakpointsResponse.cs index d782d5f8f..0aec70084 100644 --- a/src/Dap.Protocol/Requests/SetBreakpointsResponse.cs +++ b/src/Dap.Protocol/Requests/SetBreakpointsResponse.cs @@ -9,5 +9,4 @@ public class SetBreakpointsResponse /// public Container Breakpoints { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/SetDataBreakpointsArguments.cs b/src/Dap.Protocol/Requests/SetDataBreakpointsArguments.cs index 0bc9599cb..c0bfc5422 100644 --- a/src/Dap.Protocol/Requests/SetDataBreakpointsArguments.cs +++ b/src/Dap.Protocol/Requests/SetDataBreakpointsArguments.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests diff --git a/src/Dap.Protocol/Requests/SetExceptionBreakpointsArguments.cs b/src/Dap.Protocol/Requests/SetExceptionBreakpointsArguments.cs index 80a423a66..e5897beb1 100644 --- a/src/Dap.Protocol/Requests/SetExceptionBreakpointsArguments.cs +++ b/src/Dap.Protocol/Requests/SetExceptionBreakpointsArguments.cs @@ -1,6 +1,6 @@ +using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; -using MediatR; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -16,7 +16,7 @@ public class SetExceptionBreakpointsArguments : IRequest /// Configuration options for selected exceptions. /// - [Optional] public Container ExceptionOptions { get; set; } + [Optional] + public Container ExceptionOptions { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/SetExceptionBreakpointsResponse.cs b/src/Dap.Protocol/Requests/SetExceptionBreakpointsResponse.cs index d8b845115..8aa1b870e 100644 --- a/src/Dap.Protocol/Requests/SetExceptionBreakpointsResponse.cs +++ b/src/Dap.Protocol/Requests/SetExceptionBreakpointsResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class SetExceptionBreakpointsResponse { } - } diff --git a/src/Dap.Protocol/Requests/SetExpressionArguments.cs b/src/Dap.Protocol/Requests/SetExpressionArguments.cs index 3d9753f12..993fdd991 100644 --- a/src/Dap.Protocol/Requests/SetExpressionArguments.cs +++ b/src/Dap.Protocol/Requests/SetExpressionArguments.cs @@ -1,6 +1,6 @@ +using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; -using MediatR; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -21,12 +21,13 @@ public class SetExpressionArguments : IRequest /// /// Evaluate the expressions in the scope of this stack frame. If not specified, the expressions are evaluated in the global scope. /// - [Optional] public long? FrameId { get; set; } + [Optional] + public long? FrameId { get; set; } /// /// Specifies how the resulting value should be formatted. /// - [Optional] public ValueFormat Format { get; set; } + [Optional] + public ValueFormat Format { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/SetExpressionResponse.cs b/src/Dap.Protocol/Requests/SetExpressionResponse.cs index b34fa7edd..1fa2accb6 100644 --- a/src/Dap.Protocol/Requests/SetExpressionResponse.cs +++ b/src/Dap.Protocol/Requests/SetExpressionResponse.cs @@ -13,29 +13,33 @@ public class SetExpressionResponse /// /// The optional type of the value. /// - [Optional] public string Type { get; set; } + [Optional] + public string Type { get; set; } /// /// Properties of a value that can be used to determine how to render the result in the UI. /// - [Optional] public VariablePresentationHint PresentationHint { get; set; } + [Optional] + public VariablePresentationHint PresentationHint { get; set; } /// /// If variablesReference is > 0, the value is structured and its children can be retrieved by passing variablesReference to the VariablesRequest. /// - [Optional] public long? VariablesReference { get; set; } + [Optional] + public long? VariablesReference { get; set; } /// /// The number of named child variables. /// The client can use this optional information to present the variables in a paged UI and fetch them in chunks. /// - [Optional] public long? NamedVariables { get; set; } + [Optional] + public long? NamedVariables { get; set; } /// /// The number of indexed child variables. /// The client can use this optional information to present the variables in a paged UI and fetch them in chunks. /// - [Optional] public long? IndexedVariables { get; set; } + [Optional] + public long? IndexedVariables { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/SetFunctionBreakpointsArguments.cs b/src/Dap.Protocol/Requests/SetFunctionBreakpointsArguments.cs index 2b1d570cf..0181958af 100644 --- a/src/Dap.Protocol/Requests/SetFunctionBreakpointsArguments.cs +++ b/src/Dap.Protocol/Requests/SetFunctionBreakpointsArguments.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -12,5 +12,4 @@ public class SetFunctionBreakpointsArguments : IRequest public Container Breakpoints { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/SetFunctionBreakpointsResponse.cs b/src/Dap.Protocol/Requests/SetFunctionBreakpointsResponse.cs index fabfb66bd..539bf8037 100644 --- a/src/Dap.Protocol/Requests/SetFunctionBreakpointsResponse.cs +++ b/src/Dap.Protocol/Requests/SetFunctionBreakpointsResponse.cs @@ -9,5 +9,4 @@ public class SetFunctionBreakpointsResponse /// public Container Breakpoints { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/SetVariableArguments.cs b/src/Dap.Protocol/Requests/SetVariableArguments.cs index f2dfea434..c2060db5a 100644 --- a/src/Dap.Protocol/Requests/SetVariableArguments.cs +++ b/src/Dap.Protocol/Requests/SetVariableArguments.cs @@ -1,6 +1,6 @@ +using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; -using MediatR; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -26,7 +26,7 @@ public class SetVariableArguments : IRequest /// /// Specifies details on how to format the response value. /// - [Optional] public ValueFormat Format { get; set; } + [Optional] + public ValueFormat Format { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/SetVariableResponse.cs b/src/Dap.Protocol/Requests/SetVariableResponse.cs index 657f9eada..20f428756 100644 --- a/src/Dap.Protocol/Requests/SetVariableResponse.cs +++ b/src/Dap.Protocol/Requests/SetVariableResponse.cs @@ -12,24 +12,27 @@ public class SetVariableResponse /// /// The type of the new value.Typically shown in the UI when hovering over the value. /// - [Optional] public string Type { get; set; } + [Optional] + public string Type { get; set; } /// /// If variablesReference is > 0, the new value is structured and its children can be retrieved by passing variablesReference to the VariablesRequest. /// - [Optional] public long? VariablesReference { get; set; } + [Optional] + public long? VariablesReference { get; set; } /// /// The number of named child variables. /// The client can use this optional information to present the variables in a paged UI and fetch them in chunks. /// - [Optional] public long? NamedVariables { get; set; } + [Optional] + public long? NamedVariables { get; set; } /// /// The number of indexed child variables. /// The client can use this optional information to present the variables in a paged UI and fetch them in chunks. /// - [Optional] public long? IndexedVariables { get; set; } + [Optional] + public long? IndexedVariables { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/SourceArguments.cs b/src/Dap.Protocol/Requests/SourceArguments.cs index 5059b67e2..cad1472bb 100644 --- a/src/Dap.Protocol/Requests/SourceArguments.cs +++ b/src/Dap.Protocol/Requests/SourceArguments.cs @@ -1,6 +1,6 @@ +using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; -using MediatR; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -11,12 +11,12 @@ public class SourceArguments : IRequest /// /// Specifies the source content to load.Either source.path or source.sourceReference must be specified. /// - [Optional] public Source Source { get; set; } + [Optional] + public Source Source { get; set; } /// /// 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; set; } } - } diff --git a/src/Dap.Protocol/Requests/SourceResponse.cs b/src/Dap.Protocol/Requests/SourceResponse.cs index b38600ff0..2ebc8b1e0 100644 --- a/src/Dap.Protocol/Requests/SourceResponse.cs +++ b/src/Dap.Protocol/Requests/SourceResponse.cs @@ -12,7 +12,7 @@ public class SourceResponse /// /// Optional content type(mime type) of the source. /// - [Optional] public string MimeType { get; set; } + [Optional] + public string MimeType { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/StackTraceArguments.cs b/src/Dap.Protocol/Requests/StackTraceArguments.cs index d30ebf188..d5c933de9 100644 --- a/src/Dap.Protocol/Requests/StackTraceArguments.cs +++ b/src/Dap.Protocol/Requests/StackTraceArguments.cs @@ -1,6 +1,6 @@ +using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; -using MediatR; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -16,17 +16,19 @@ public class StackTraceArguments : IRequest /// /// The index of the first frame to return; if omitted frames start at 0. /// - [Optional] public long? StartFrame { get; set; } + [Optional] + public long? StartFrame { get; set; } /// /// The maximum number of frames to return. If levels is not specified or 0, all frames are returned. /// - [Optional] public long? Levels { get; set; } + [Optional] + public long? Levels { get; set; } /// /// Specifies details on how to format the stack frames. /// - [Optional] public StackFrameFormat Format { get; set; } + [Optional] + public StackFrameFormat Format { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/StackTraceResponse.cs b/src/Dap.Protocol/Requests/StackTraceResponse.cs index c6e28ade5..beb226583 100644 --- a/src/Dap.Protocol/Requests/StackTraceResponse.cs +++ b/src/Dap.Protocol/Requests/StackTraceResponse.cs @@ -14,8 +14,7 @@ public class StackTraceResponse /// /// The total number of frames available. /// - [Optional] public long? TotalFrames { get; set; } - + [Optional] + public long? TotalFrames { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/StepBackArguments.cs b/src/Dap.Protocol/Requests/StepBackArguments.cs index 1db30a979..33190390a 100644 --- a/src/Dap.Protocol/Requests/StepBackArguments.cs +++ b/src/Dap.Protocol/Requests/StepBackArguments.cs @@ -19,5 +19,4 @@ public class StepBackArguments : IRequest [Optional] public SteppingGranularity Granularity { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/StepBackResponse.cs b/src/Dap.Protocol/Requests/StepBackResponse.cs index 5f9c87b09..d41731d19 100644 --- a/src/Dap.Protocol/Requests/StepBackResponse.cs +++ b/src/Dap.Protocol/Requests/StepBackResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class StepBackResponse { } - } diff --git a/src/Dap.Protocol/Requests/StepInArguments.cs b/src/Dap.Protocol/Requests/StepInArguments.cs index 1f9f9b99d..06fab8c77 100644 --- a/src/Dap.Protocol/Requests/StepInArguments.cs +++ b/src/Dap.Protocol/Requests/StepInArguments.cs @@ -1,6 +1,6 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -16,7 +16,8 @@ public class StepInArguments : IRequest /// /// Optional id of the target to step into. /// - [Optional] public long? TargetId { get; set; } + [Optional] + public long? TargetId { get; set; } /// /// Optional granularity to step. If no granularity is specified, a granularity of 'statement' is assumed. @@ -24,5 +25,4 @@ public class StepInArguments : IRequest [Optional] public SteppingGranularity Granularity { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/StepInResponse.cs b/src/Dap.Protocol/Requests/StepInResponse.cs index ff17478da..d062eb23b 100644 --- a/src/Dap.Protocol/Requests/StepInResponse.cs +++ b/src/Dap.Protocol/Requests/StepInResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class StepInResponse { } - } diff --git a/src/Dap.Protocol/Requests/StepInTargetsArguments.cs b/src/Dap.Protocol/Requests/StepInTargetsArguments.cs index 30c7ec67c..85f9d46cc 100644 --- a/src/Dap.Protocol/Requests/StepInTargetsArguments.cs +++ b/src/Dap.Protocol/Requests/StepInTargetsArguments.cs @@ -11,5 +11,4 @@ public class StepInTargetsArguments : IRequest /// public long FrameId { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/StepInTargetsResponse.cs b/src/Dap.Protocol/Requests/StepInTargetsResponse.cs index a24832ebf..6aa8eec14 100644 --- a/src/Dap.Protocol/Requests/StepInTargetsResponse.cs +++ b/src/Dap.Protocol/Requests/StepInTargetsResponse.cs @@ -9,5 +9,4 @@ public class StepInTargetsResponse /// public Container Targets { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/StepOutArguments.cs b/src/Dap.Protocol/Requests/StepOutArguments.cs index b05740326..3b951c974 100644 --- a/src/Dap.Protocol/Requests/StepOutArguments.cs +++ b/src/Dap.Protocol/Requests/StepOutArguments.cs @@ -19,5 +19,4 @@ public class StepOutArguments : IRequest [Optional] public SteppingGranularity Granularity { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/StepOutResponse.cs b/src/Dap.Protocol/Requests/StepOutResponse.cs index 3927a42ce..a1b96f2e4 100644 --- a/src/Dap.Protocol/Requests/StepOutResponse.cs +++ b/src/Dap.Protocol/Requests/StepOutResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class StepOutResponse { } - } diff --git a/src/Dap.Protocol/Requests/TerminateArguments.cs b/src/Dap.Protocol/Requests/TerminateArguments.cs index 5d26bcc56..790d19fcd 100644 --- a/src/Dap.Protocol/Requests/TerminateArguments.cs +++ b/src/Dap.Protocol/Requests/TerminateArguments.cs @@ -1,5 +1,5 @@ -using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using MediatR; +using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -10,6 +10,7 @@ public class TerminateArguments : IRequest /// /// A value of true indicates that this 'terminate' request is part of a restart sequence. /// - [Optional] public bool? Restart { get; set; } + [Optional] + public bool? Restart { get; set; } } } diff --git a/src/Dap.Protocol/Requests/TerminateResponse.cs b/src/Dap.Protocol/Requests/TerminateResponse.cs index bbf545bd6..b93134a25 100644 --- a/src/Dap.Protocol/Requests/TerminateResponse.cs +++ b/src/Dap.Protocol/Requests/TerminateResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class TerminateResponse { } - } diff --git a/src/Dap.Protocol/Requests/TerminateThreadsArguments.cs b/src/Dap.Protocol/Requests/TerminateThreadsArguments.cs index c41b4b3a3..c27e09050 100644 --- a/src/Dap.Protocol/Requests/TerminateThreadsArguments.cs +++ b/src/Dap.Protocol/Requests/TerminateThreadsArguments.cs @@ -1,6 +1,6 @@ +using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; -using MediatR; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -11,7 +11,7 @@ public class TerminateThreadsArguments : IRequest /// /// Ids of threads to be terminated. /// - [Optional] public Container ThreadIds { get; set; } + [Optional] + public Container ThreadIds { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/TerminateThreadsResponse.cs b/src/Dap.Protocol/Requests/TerminateThreadsResponse.cs index 77d587086..b764253a8 100644 --- a/src/Dap.Protocol/Requests/TerminateThreadsResponse.cs +++ b/src/Dap.Protocol/Requests/TerminateThreadsResponse.cs @@ -3,5 +3,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class TerminateThreadsResponse { } - } diff --git a/src/Dap.Protocol/Requests/ThreadsArguments.cs b/src/Dap.Protocol/Requests/ThreadsArguments.cs index 9c743f615..573a369df 100644 --- a/src/Dap.Protocol/Requests/ThreadsArguments.cs +++ b/src/Dap.Protocol/Requests/ThreadsArguments.cs @@ -7,5 +7,4 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests public class ThreadsArguments : IRequest { } - } diff --git a/src/Dap.Protocol/Requests/ThreadsResponse.cs b/src/Dap.Protocol/Requests/ThreadsResponse.cs index 5ee7b872a..ac67605a2 100644 --- a/src/Dap.Protocol/Requests/ThreadsResponse.cs +++ b/src/Dap.Protocol/Requests/ThreadsResponse.cs @@ -9,5 +9,4 @@ public class ThreadsResponse /// public Container Threads { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/VariablesArguments.cs b/src/Dap.Protocol/Requests/VariablesArguments.cs index 4bad868e9..9962a8428 100644 --- a/src/Dap.Protocol/Requests/VariablesArguments.cs +++ b/src/Dap.Protocol/Requests/VariablesArguments.cs @@ -1,6 +1,6 @@ +using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; -using MediatR; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Requests @@ -16,22 +16,25 @@ public class VariablesArguments : IRequest /// /// Optional filter to limit the child variables to either named or indexed.If ommited, both types are fetched. /// - [Optional] public VariablesArgumentsFilter? Filter { get; set; } + [Optional] + public VariablesArgumentsFilter? Filter { get; set; } /// /// The index of the first variable to return; if omitted children start at 0. /// - [Optional] public long? Start { get; set; } + [Optional] + public long? Start { get; set; } /// /// The number of variables to return. If count is missing or 0, all variables are returned. /// - [Optional] public long? Count { get; set; } + [Optional] + public long? Count { get; set; } /// /// Specifies details on how to format the Variable values. /// - [Optional] public ValueFormat Format { get; set; } + [Optional] + public ValueFormat Format { get; set; } } - } diff --git a/src/Dap.Protocol/Requests/VariablesArgumentsFilter.cs b/src/Dap.Protocol/Requests/VariablesArgumentsFilter.cs index 5d9b5bae2..bd96ab3cd 100644 --- a/src/Dap.Protocol/Requests/VariablesArgumentsFilter.cs +++ b/src/Dap.Protocol/Requests/VariablesArgumentsFilter.cs @@ -8,5 +8,4 @@ public enum VariablesArgumentsFilter { Indexed, Named } - } diff --git a/src/Dap.Protocol/Requests/VariablesResponse.cs b/src/Dap.Protocol/Requests/VariablesResponse.cs index 699d3da49..92e7f7727 100644 --- a/src/Dap.Protocol/Requests/VariablesResponse.cs +++ b/src/Dap.Protocol/Requests/VariablesResponse.cs @@ -9,5 +9,4 @@ public class VariablesResponse /// public Container Variables { get; set; } } - } diff --git a/src/Dap.Protocol/Serialization/ContractResolver.cs b/src/Dap.Protocol/Serialization/ContractResolver.cs index 248d45188..edf3fb36a 100644 --- a/src/Dap.Protocol/Serialization/ContractResolver.cs +++ b/src/Dap.Protocol/Serialization/ContractResolver.cs @@ -5,12 +5,9 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Serialization { - class ContractResolver : DefaultContractResolver + internal class ContractResolver : DefaultContractResolver { - public ContractResolver() - { - NamingStrategy = new CamelCaseNamingStrategy(true, false, true); - } + public ContractResolver() => NamingStrategy = new CamelCaseNamingStrategy(true, false, true); protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { diff --git a/src/Dap.Protocol/Serialization/ISerializer.cs b/src/Dap.Protocol/Serialization/ISerializer.cs index 2b6629b21..86d1fe795 100644 --- a/src/Dap.Protocol/Serialization/ISerializer.cs +++ b/src/Dap.Protocol/Serialization/ISerializer.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Serialization { - public interface ISerializer : OmniSharp.Extensions.JsonRpc.ISerializer{} + public interface ISerializer : JsonRpc.ISerializer + { + } } diff --git a/src/Dap.Protocol/Serialization/NumberStringConverter.cs b/src/Dap.Protocol/Serialization/NumberStringConverter.cs index a7bb07a5c..5858627d0 100644 --- a/src/Dap.Protocol/Serialization/NumberStringConverter.cs +++ b/src/Dap.Protocol/Serialization/NumberStringConverter.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Serialization { - class NumberStringConverter : JsonConverter + internal class NumberStringConverter : JsonConverter { public override void WriteJson(JsonWriter writer, NumberString value, JsonSerializer serializer) { @@ -17,12 +17,12 @@ public override NumberString ReadJson(JsonReader reader, Type objectType, Number { if (reader.TokenType == JsonToken.Integer) { - return new NumberString((long)reader.Value); + return new NumberString((long) reader.Value); } if (reader.TokenType == JsonToken.String) { - return new NumberString((string)reader.Value); + return new NumberString((string) reader.Value); } return new NumberString(); diff --git a/src/Dap.Protocol/Serialization/OptionalAttribute.cs b/src/Dap.Protocol/Serialization/OptionalAttribute.cs index 8b1a1c3bc..800fb25a0 100644 --- a/src/Dap.Protocol/Serialization/OptionalAttribute.cs +++ b/src/Dap.Protocol/Serialization/OptionalAttribute.cs @@ -3,5 +3,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Serialization { [AttributeUsage(AttributeTargets.Property)] - class OptionalAttribute : Attribute { } + internal class OptionalAttribute : Attribute + { + } } diff --git a/src/Dap.Protocol/Server/IDebugAdapterServer.cs b/src/Dap.Protocol/Server/IDebugAdapterServer.cs index 14c0c071c..4c8600616 100644 --- a/src/Dap.Protocol/Server/IDebugAdapterServer.cs +++ b/src/Dap.Protocol/Server/IDebugAdapterServer.cs @@ -1,8 +1,6 @@ using System; using System.Threading; using System.Threading.Tasks; -using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; -using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Server { diff --git a/src/Dap.Protocol/Server/IOnDebugAdapterServerInitialize.cs b/src/Dap.Protocol/Server/IOnDebugAdapterServerInitialize.cs index aa7518098..857a20776 100644 --- a/src/Dap.Protocol/Server/IOnDebugAdapterServerInitialize.cs +++ b/src/Dap.Protocol/Server/IOnDebugAdapterServerInitialize.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Server { /// /// Gives your class or handler an opportunity to interact with - /// the before it is processed by the server + /// the before it is processed by the server /// public interface IOnDebugAdapterServerInitialize : IEventingHandler { diff --git a/src/Dap.Protocol/Server/IOnDebugAdapterServerInitialized.cs b/src/Dap.Protocol/Server/IOnDebugAdapterServerInitialized.cs index 9ab033a9a..afb12d147 100644 --- a/src/Dap.Protocol/Server/IOnDebugAdapterServerInitialized.cs +++ b/src/Dap.Protocol/Server/IOnDebugAdapterServerInitialized.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Server { /// /// Gives your class or handler an opportunity to interact with - /// the and after it is processed by the server but before it is sent to the client + /// the and after it is processed by the server but before it is sent to the client /// public interface IOnDebugAdapterServerInitialized : IEventingHandler { diff --git a/src/Dap.Protocol/Server/IOnDebugAdapterServerStarted.cs b/src/Dap.Protocol/Server/IOnDebugAdapterServerStarted.cs index 8d29ddbe1..54a1e6c60 100644 --- a/src/Dap.Protocol/Server/IOnDebugAdapterServerStarted.cs +++ b/src/Dap.Protocol/Server/IOnDebugAdapterServerStarted.cs @@ -6,7 +6,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Server { /// /// Gives your class or handler an opportunity to interact with - /// the after the connection has been established. + /// the after the connection has been established. /// public interface IOnDebugAdapterServerStarted : IEventingHandler { diff --git a/src/Dap.Protocol/Server/OnDebugAdapterServerInitializeDelegate.cs b/src/Dap.Protocol/Server/OnDebugAdapterServerInitializeDelegate.cs index 486f42616..f3c658ee3 100644 --- a/src/Dap.Protocol/Server/OnDebugAdapterServerInitializeDelegate.cs +++ b/src/Dap.Protocol/Server/OnDebugAdapterServerInitializeDelegate.cs @@ -6,7 +6,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Server { /// /// Gives your class or handler an opportunity to interact with - /// the before it is processed by the server + /// the before it is processed by the server /// public delegate Task OnDebugAdapterServerInitializeDelegate(IDebugAdapterServer server, InitializeRequestArguments request, CancellationToken cancellationToken); } diff --git a/src/Dap.Protocol/Server/OnDebugAdapterServerInitializedDelegate.cs b/src/Dap.Protocol/Server/OnDebugAdapterServerInitializedDelegate.cs index a11cbffbd..b7634c5ee 100644 --- a/src/Dap.Protocol/Server/OnDebugAdapterServerInitializedDelegate.cs +++ b/src/Dap.Protocol/Server/OnDebugAdapterServerInitializedDelegate.cs @@ -6,7 +6,9 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Server { /// /// Gives your class or handler an opportunity to interact with - /// the and after it is processed by the server but before it is sent to the client + /// the and after it is processed by the server but before it is sent to the client /// - public delegate Task OnDebugAdapterServerInitializedDelegate(IDebugAdapterServer server, InitializeRequestArguments request, InitializeResponse response, CancellationToken cancellationToken); + public delegate Task OnDebugAdapterServerInitializedDelegate( + IDebugAdapterServer server, InitializeRequestArguments request, InitializeResponse response, CancellationToken cancellationToken + ); } diff --git a/src/Dap.Protocol/Server/OnDebugAdapterServerStartedDelegate.cs b/src/Dap.Protocol/Server/OnDebugAdapterServerStartedDelegate.cs index 9fc00c604..72b8ebe53 100644 --- a/src/Dap.Protocol/Server/OnDebugAdapterServerStartedDelegate.cs +++ b/src/Dap.Protocol/Server/OnDebugAdapterServerStartedDelegate.cs @@ -5,7 +5,7 @@ namespace OmniSharp.Extensions.DebugAdapter.Protocol.Server { /// /// Gives your class or handler an opportunity to interact with - /// the after the connection has been established. + /// the after the connection has been established. /// public delegate Task OnDebugAdapterServerStartedDelegate(IDebugAdapterServer server, CancellationToken cancellationToken); } diff --git a/src/Dap.Server/DebugAdapterServer.cs b/src/Dap.Server/DebugAdapterServer.cs index 9d1514ae3..35938caaa 100644 --- a/src/Dap.Server/DebugAdapterServer.cs +++ b/src/Dap.Server/DebugAdapterServer.cs @@ -2,14 +2,12 @@ using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; -using System.Reactive.Linq; using System.Reactive.Subjects; using System.Reactive.Threading.Tasks; using System.Threading; using System.Threading.Tasks; using DryIoc; using MediatR; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.DebugAdapter.Protocol.Events; @@ -18,8 +16,6 @@ using OmniSharp.Extensions.DebugAdapter.Protocol.Server; using OmniSharp.Extensions.DebugAdapter.Shared; using OmniSharp.Extensions.JsonRpc; -using IOutputHandler = OmniSharp.Extensions.JsonRpc.IOutputHandler; -using OutputHandler = OmniSharp.Extensions.JsonRpc.OutputHandler; namespace OmniSharp.Extensions.DebugAdapter.Server { @@ -40,11 +36,11 @@ public class DebugAdapterServer : JsonRpcServerBase, IDebugAdapterServer, IDebug private readonly ISubject _initializeComplete = new AsyncSubject(); private readonly Capabilities _capabilities; private bool _started; - private int? _concurrency; + private readonly int? _concurrency; internal static IContainer CreateContainer(DebugAdapterServerOptions options, IServiceProvider outerServiceProvider) => JsonRpcServerContainer.Create(outerServiceProvider) - .AddDebugAdapterServerInternals(options, outerServiceProvider); + .AddDebugAdapterServerInternals(options, outerServiceProvider); public static DebugAdapterServer Create(DebugAdapterServerOptions options) => Create(options, null); public static DebugAdapterServer Create(Action optionsAction) => Create(optionsAction, null); @@ -100,7 +96,8 @@ internal DebugAdapterServer( IDebugAdapterServerProgressManager progressManager, IEnumerable initializeHandlers, IEnumerable initializedHandlers, - IEnumerable startedHandlers) : base(collection, responseRouter) + IEnumerable startedHandlers + ) : base(collection, responseRouter) { _capabilities = capabilities; _receiver = receiver; @@ -165,8 +162,10 @@ await DebugAdapterEventingHelper.Run( } } - async Task IRequestHandler.Handle(InitializeRequestArguments request, - CancellationToken cancellationToken) + async Task IRequestHandler.Handle( + InitializeRequestArguments request, + CancellationToken cancellationToken + ) { ClientSettings = request; @@ -181,7 +180,7 @@ await DebugAdapterEventingHelper.Run( _receiver.Initialized(); - var response = new InitializeResponse() { + var response = new InitializeResponse { AdditionalModuleColumns = _capabilities.AdditionalModuleColumns, ExceptionBreakpointFilters = _capabilities.ExceptionBreakpointFilters, SupportedChecksumAlgorithms = _capabilities.SupportedChecksumAlgorithms, diff --git a/src/Dap.Server/DebugAdapterServerOptions.cs b/src/Dap.Server/DebugAdapterServerOptions.cs index 3c82232ed..12097495c 100644 --- a/src/Dap.Server/DebugAdapterServerOptions.cs +++ b/src/Dap.Server/DebugAdapterServerOptions.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; @@ -14,52 +13,110 @@ public class DebugAdapterServerOptions : DebugAdapterRpcOptionsBase.AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options) => AddHandler(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => AddHandler(method, handlerFunc, options); + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options) => + AddHandler(method, handler, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry. + AddHandler(string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => AddHandler(method, handlerFunc, options); + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.AddHandlers(params IJsonRpcHandler[] handlers) => AddHandlers(handlers); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => AddHandler(handlerFunc, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptions options) => AddHandler(handler, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => + AddHandler(handlerFunc, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptions options) => + AddHandler(handler, options); + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerOptions options) => AddHandler(options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerOptions options) => AddHandler(method, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerOptions options) => + AddHandler(method, options); + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.AddHandler(Type type, JsonRpcHandlerOptions options) => AddHandler(type, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, Type type, JsonRpcHandlerOptions options) => AddHandler(method, type, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnJsonRequest(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnJsonRequest(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, Type type, JsonRpcHandlerOptions options) => + AddHandler(method, type, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnJsonRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnJsonRequest(method, handler, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnJsonRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnJsonRequest(method, handler, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); + + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnNotification( + string method, Action handler, JsonRpcHandlerOptions options + ) => OnNotification(method, handler, options); IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Func handler, - JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification( + string method, Func handler, + JsonRpcHandlerOptions options + ) => OnJsonNotification(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Func handler, - JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification( + string method, Func handler, + JsonRpcHandlerOptions options + ) => OnJsonNotification(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Action handler, - JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification( + string method, Action handler, + JsonRpcHandlerOptions options + ) => OnJsonNotification(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, - JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnNotification( + string method, Action handler, + JsonRpcHandlerOptions options + ) => OnNotification(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, - JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnNotification( + string method, Func handler, + JsonRpcHandlerOptions options + ) => OnNotification(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, - JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnNotification( + string method, Func handler, + JsonRpcHandlerOptions options + ) => OnNotification(method, handler, options); IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); - IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, - JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnNotification( + string method, Func handler, + JsonRpcHandlerOptions options + ) => OnNotification(method, handler, options); IDebugAdapterServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); diff --git a/src/Dap.Server/DebugAdapterServerOptionsExtensions.cs b/src/Dap.Server/DebugAdapterServerOptionsExtensions.cs index 1611c8919..89aa784bb 100644 --- a/src/Dap.Server/DebugAdapterServerOptionsExtensions.cs +++ b/src/Dap.Server/DebugAdapterServerOptionsExtensions.cs @@ -2,7 +2,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.DebugAdapter.Protocol.Server; using OmniSharp.Extensions.JsonRpc; diff --git a/src/Dap.Server/DebugAdapterServerProgressManager.cs b/src/Dap.Server/DebugAdapterServerProgressManager.cs index 180e3da58..1e923aa10 100644 --- a/src/Dap.Server/DebugAdapterServerProgressManager.cs +++ b/src/Dap.Server/DebugAdapterServerProgressManager.cs @@ -41,7 +41,7 @@ public IProgressObserver Create(ProgressStartEvent begin, Func new ProgressEndEvent() { + onError ??= error => new ProgressEndEvent { Message = error.ToString() }; diff --git a/src/Dap.Server/DebugAdapterServerResolver.cs b/src/Dap.Server/DebugAdapterServerResolver.cs index 64e7fe168..eed83d272 100644 --- a/src/Dap.Server/DebugAdapterServerResolver.cs +++ b/src/Dap.Server/DebugAdapterServerResolver.cs @@ -35,4 +35,4 @@ public void Dispose() foreach (var item in _servers.Values) item.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Dap.Server/DebugAdapterServerServiceCollectionExtensions.cs b/src/Dap.Server/DebugAdapterServerServiceCollectionExtensions.cs index 2aa184950..2d9457ded 100644 --- a/src/Dap.Server/DebugAdapterServerServiceCollectionExtensions.cs +++ b/src/Dap.Server/DebugAdapterServerServiceCollectionExtensions.cs @@ -23,7 +23,7 @@ internal static IContainer AddDebugAdapterServerInternals(this IContainer contai } else { - container.RegisterDelegate(_ => new OnUnhandledExceptionHandler(e => { }), reuse: Reuse.Singleton); + container.RegisterDelegate(_ => new OnUnhandledExceptionHandler(e => { }), Reuse.Singleton); } container.RegisterInstance>(new ValueOptionsFactory(options)); @@ -32,11 +32,14 @@ internal static IContainer AddDebugAdapterServerInternals(this IContainer contai container.RegisterInstance(options.RequestProcessIdentifier); container.RegisterMany(nonPublicServiceTypes: true, reuse: Reuse.Singleton); - container.RegisterMany(serviceTypeCondition: type => type == typeof(IDebugAdapterServer) || type == typeof(DebugAdapterServer), reuse: Reuse.Singleton); + container.RegisterMany( + serviceTypeCondition: type => type == typeof(IDebugAdapterServer) || type == typeof(DebugAdapterServer), reuse: Reuse.Singleton + ); // container. var providedConfiguration = options.Services.FirstOrDefault(z => z.ServiceType == typeof(IConfiguration) && z.ImplementationInstance is IConfiguration); - container.RegisterDelegate(_ => { + container.RegisterDelegate( + _ => { var builder = new ConfigurationBuilder(); if (outerServiceProvider != null) { @@ -54,15 +57,14 @@ internal static IContainer AddDebugAdapterServerInternals(this IContainer contai return builder.Build(); }, - reuse: Reuse.Singleton); + Reuse.Singleton + ); return container; } - public static IServiceCollection AddDebugAdapterServer(this IServiceCollection services, Action configureOptions = null) - { - return AddDebugAdapterServer(services, Options.DefaultName, configureOptions); - } + public static IServiceCollection AddDebugAdapterServer(this IServiceCollection services, Action configureOptions = null) => + AddDebugAdapterServer(services, Options.DefaultName, configureOptions); public static IServiceCollection AddDebugAdapterServer(this IServiceCollection services, string name, Action configureOptions = null) { @@ -72,15 +74,19 @@ public static IServiceCollection AddDebugAdapterServer(this IServiceCollection s { services.RemoveAll(); services.RemoveAll(); - services.AddSingleton(_ => - throw new NotSupportedException("DebugAdapterServer has been registered multiple times, you must use DebugAdapterServer instead")); - services.AddSingleton(_ => - throw new NotSupportedException("DebugAdapterServer has been registered multiple times, you must use DebugAdapterServer instead")); + services.AddSingleton( + _ => + throw new NotSupportedException("DebugAdapterServer has been registered multiple times, you must use DebugAdapterServer instead") + ); + services.AddSingleton( + _ => + throw new NotSupportedException("DebugAdapterServer has been registered multiple times, you must use DebugAdapterServer instead") + ); } services - .AddOptions() - .AddLogging(); + .AddOptions() + .AddLogging(); services.TryAddSingleton(); services.TryAddSingleton(_ => _.GetRequiredService().Get(name)); services.TryAddSingleton(_ => _.GetRequiredService().Get(name)); @@ -93,4 +99,4 @@ public static IServiceCollection AddDebugAdapterServer(this IServiceCollection s return services; } } -} \ No newline at end of file +} diff --git a/src/Dap.Server/ProgressObserver.cs b/src/Dap.Server/ProgressObserver.cs index 7414d4474..18aa1efc7 100644 --- a/src/Dap.Server/ProgressObserver.cs +++ b/src/Dap.Server/ProgressObserver.cs @@ -9,9 +9,8 @@ namespace OmniSharp.Extensions.DebugAdapter.Server { - class ProgressObserver : IProgressObserver + internal class ProgressObserver : IProgressObserver { - private readonly ProgressToken _progressToken; private readonly IResponseRouter _router; private readonly Func _onError; private readonly Func _onComplete; @@ -22,13 +21,14 @@ public ProgressObserver( ProgressStartEvent begin, Func onError, Func onComplete, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { - _progressToken = begin.ProgressId; + ProgressId = begin.ProgressId; _router = router; _onError = onError; _onComplete = onComplete; - _disposable = new CompositeDisposable {Disposable.Create(OnCompleted)}; + _disposable = new CompositeDisposable { Disposable.Create(OnCompleted) }; cancellationToken.Register(Dispose); _router.SendNotification(begin); } @@ -36,10 +36,10 @@ public ProgressObserver( public void OnCompleted() { if (_disposable.IsDisposed) return; - var @event = _onComplete?.Invoke() ?? new ProgressEndEvent() {Message = "", ProgressId = _progressToken}; + var @event = _onComplete?.Invoke() ?? new ProgressEndEvent { Message = "", ProgressId = ProgressId }; if (EqualityComparer.Default.Equals(@event.ProgressId, default)) { - @event.ProgressId = _progressToken; + @event.ProgressId = ProgressId; } _router.SendNotification(@event); @@ -48,10 +48,10 @@ public void OnCompleted() void IObserver.OnError(Exception error) { if (_disposable.IsDisposed) return; - var @event = _onError?.Invoke(error) ?? new ProgressEndEvent() {Message = error.ToString(), ProgressId = _progressToken}; + var @event = _onError?.Invoke(error) ?? new ProgressEndEvent { Message = error.ToString(), ProgressId = ProgressId }; if (EqualityComparer.Default.Equals(@event.ProgressId, default)) { - @event.ProgressId = _progressToken; + @event.ProgressId = ProgressId; } _router.SendNotification(@event); @@ -62,22 +62,22 @@ public void OnNext(ProgressUpdateEvent value) if (_disposable.IsDisposed) return; if (EqualityComparer.Default.Equals(value.ProgressId, default)) { - value.ProgressId = _progressToken; + value.ProgressId = ProgressId; } _router.SendNotification(value); } - public ProgressToken ProgressId => _progressToken; + public ProgressToken ProgressId { get; } - public void OnNext(string message, double? percentage) - { - OnNext(new ProgressUpdateEvent() { - ProgressId = _progressToken, - Message = message, - Percentage = percentage - }); - } + public void OnNext(string message, double? percentage) => + OnNext( + new ProgressUpdateEvent { + ProgressId = ProgressId, + Message = message, + Percentage = percentage + } + ); public void Dispose() => _disposable?.Dispose(); } diff --git a/src/Dap.Shared/DapResponseRouter.cs b/src/Dap.Shared/DapResponseRouter.cs index e282d43cd..702dfe18e 100644 --- a/src/Dap.Shared/DapResponseRouter.cs +++ b/src/Dap.Shared/DapResponseRouter.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Concurrent; -using System.Linq; -using System.Reflection; using System.Threading; using System.Threading.Tasks; using MediatR; @@ -29,40 +27,29 @@ public DapResponseRouter(IOutputHandler outputHandler, ISerializer serializer) Serializer = serializer; } - public void SendNotification(string method) - { - OutputHandler.Send(new OutgoingNotification() { - Method = method - }); - } + public void SendNotification(string method) => + OutputHandler.Send( + new OutgoingNotification { + Method = method + } + ); - public void SendNotification(string method, T @params) - { - OutputHandler.Send(new OutgoingNotification() { - Method = method, - Params = @params - }); - } + public void SendNotification(string method, T @params) => + OutputHandler.Send( + 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) - { - return SendRequest(GetMethodName(@params.GetType()), @params).Returning(cancellationToken); - } + public Task SendRequest(IRequest @params, CancellationToken cancellationToken) => + SendRequest(GetMethodName(@params.GetType()), @params).Returning(cancellationToken); - public IResponseRouterReturns SendRequest(string method) - { - return new ResponseRouterReturnsImpl(this, method, new object()); - } + public IResponseRouterReturns SendRequest(string method) => new ResponseRouterReturnsImpl(this, method, new object()); - public IResponseRouterReturns SendRequest(string method, T @params) - { - return new ResponseRouterReturnsImpl(this, method, @params); - } + public IResponseRouterReturns SendRequest(string method, T @params) => new ResponseRouterReturnsImpl(this, method, @params); public (string method, TaskCompletionSource pendingTask) GetRequest(long id) { @@ -87,7 +74,7 @@ private string GetMethodName(Type type) return methodName; } - class ResponseRouterReturnsImpl : IResponseRouterReturns + private class ResponseRouterReturnsImpl : IResponseRouterReturns { private readonly DapResponseRouter _router; private readonly string _method; @@ -104,21 +91,25 @@ public async Task Returning(CancellationToken cancellation { var nextId = _router.Serializer.GetNextId(); var tcs = new TaskCompletionSource(); - _router.Requests.TryAdd(nextId, (_method, tcs)); + _router.Requests.TryAdd(nextId, ( _method, tcs )); cancellationToken.ThrowIfCancellationRequested(); - _router.OutputHandler.Send(new OutgoingRequest() { - Method = _method, - Params = _params, - Id = nextId - }); + _router.OutputHandler.Send( + new OutgoingRequest { + Method = _method, + Params = _params, + Id = nextId + } + ); if (_method != RequestNames.Cancel) { - cancellationToken.Register(() => { - if (tcs.Task.IsCompleted) return; - _router.SendRequest(RequestNames.Cancel, new { requestId = nextId }).Returning(CancellationToken.None); - }); + cancellationToken.Register( + () => { + if (tcs.Task.IsCompleted) return; + _router.SendRequest(RequestNames.Cancel, new { requestId = nextId }).Returning(CancellationToken.None); + } + ); } try @@ -137,10 +128,7 @@ public async Task Returning(CancellationToken cancellation } } - public async Task ReturningVoid(CancellationToken cancellationToken) - { - await Returning(cancellationToken); - } + public async Task ReturningVoid(CancellationToken cancellationToken) => await Returning(cancellationToken); } } } diff --git a/src/Dap.Shared/DebugAdapterEventingHelper.cs b/src/Dap.Shared/DebugAdapterEventingHelper.cs index 146a56d3c..60176311f 100644 --- a/src/Dap.Shared/DebugAdapterEventingHelper.cs +++ b/src/Dap.Shared/DebugAdapterEventingHelper.cs @@ -20,21 +20,21 @@ CancellationToken cancellationToken ) { var events = delegates.Select(z => Observable.FromAsync(ct => executeDelegate(z, ct))) - .Concat(handlers.Select(z => Observable.FromAsync(ct => executeHandler(z, ct)))) - .ToObservable(); + .Concat(handlers.Select(z => Observable.FromAsync(ct => executeHandler(z, ct)))) + .ToObservable(); if (concurrency.HasValue) { return events.Merge(concurrency.Value) - .LastOrDefaultAsync() - .ToTask(cancellationToken); + .LastOrDefaultAsync() + .ToTask(cancellationToken); } return events - .Merge() - .LastOrDefaultAsync() - .ToTask(cancellationToken); + .Merge() + .LastOrDefaultAsync() + .ToTask(cancellationToken); } } } diff --git a/src/Dap.Shared/DebugAdapterHandlerCollection.cs b/src/Dap.Shared/DebugAdapterHandlerCollection.cs index 74f5c082e..6a8fb2185 100644 --- a/src/Dap.Shared/DebugAdapterHandlerCollection.cs +++ b/src/Dap.Shared/DebugAdapterHandlerCollection.cs @@ -12,34 +12,31 @@ namespace OmniSharp.Extensions.DebugAdapter.Shared { - class DebugAdapterHandlerCollection : IEnumerable, IHandlersManager + internal class DebugAdapterHandlerCollection : IEnumerable, IHandlersManager { - private ImmutableHashSet _descriptors = ImmutableHashSet.Empty; + private ImmutableHashSet _descriptors = ImmutableHashSet.Empty; private readonly IServiceProvider _serviceProvider; public IEnumerable Descriptors => _descriptors; - public DebugAdapterHandlerCollection(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } + public DebugAdapterHandlerCollection(IServiceProvider serviceProvider) => _serviceProvider = serviceProvider; - public IEnumerator GetEnumerator() - { - return _descriptors.GetEnumerator(); - } + public IEnumerator GetEnumerator() => _descriptors.GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IDisposable Add(IJsonRpcHandler handler, JsonRpcHandlerOptions options) => AddHandler(handler, options); public IDisposable Add(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options) => AddHandler(method, handler, options); public IDisposable Add(JsonRpcHandlerFactory factory, JsonRpcHandlerOptions options) => AddHandler(factory(_serviceProvider), options); public IDisposable Add(string method, JsonRpcHandlerFactory factory, JsonRpcHandlerOptions options) => AddHandler(method, factory(_serviceProvider), options); - public IDisposable Add(Type handlerType, JsonRpcHandlerOptions options) => AddHandler(ActivatorUtilities.CreateInstance(_serviceProvider, handlerType) as IJsonRpcHandler, options); - public IDisposable Add(string method, Type handlerType, JsonRpcHandlerOptions options) => AddHandler(method, ActivatorUtilities.CreateInstance(_serviceProvider, handlerType) as IJsonRpcHandler, options); + + public IDisposable Add(Type handlerType, JsonRpcHandlerOptions options) => AddHandler( + ActivatorUtilities.CreateInstance(_serviceProvider, handlerType) as IJsonRpcHandler, options + ); + + public IDisposable Add(string method, Type handlerType, JsonRpcHandlerOptions options) => AddHandler( + method, ActivatorUtilities.CreateInstance(_serviceProvider, handlerType) as IJsonRpcHandler, options + ); IDisposable IHandlersManager.AddLink(string sourceMethod, string destinationMethod) { @@ -49,9 +46,10 @@ IDisposable IHandlersManager.AddLink(string sourceMethod, string destinationMeth destinationMethod, source.HandlerType, source.Handler, - source.RequestProcessType.HasValue ? new JsonRpcHandlerOptions() {RequestProcessType = source.RequestProcessType.Value} : null, + source.RequestProcessType.HasValue ? new JsonRpcHandlerOptions { RequestProcessType = source.RequestProcessType.Value } : null, source.TypeDescriptor, - source.HandlerType); + source.HandlerType + ); Interlocked.Exchange(ref _descriptors, _descriptors.Add(descriptor)); return descriptor; @@ -64,6 +62,7 @@ public IDisposable Add(params IJsonRpcHandler[] handlers) { cd.Add(AddHandler(handler, null)); } + return cd; } @@ -74,6 +73,7 @@ public IDisposable Add(params JsonRpcHandlerFactory[] handlerFactories) { cd.Add(AddHandler(handlerFactory(_serviceProvider), null)); } + return cd; } @@ -84,21 +84,15 @@ public IDisposable Add(params Type[] handlerTypes) { cd.Add(AddHandler(ActivatorUtilities.CreateInstance(_serviceProvider, handlerType) as IJsonRpcHandler, null)); } - return cd; + return cd; } - class EqualityComparer : IEqualityComparer<(string method, Type implementedInterface)> + private class EqualityComparer : IEqualityComparer<(string method, Type implementedInterface)> { - public bool Equals((string method, Type implementedInterface) x, (string method, Type implementedInterface) y) - { - return x.method?.Equals(y.method) == true; - } + public bool Equals((string method, Type implementedInterface) x, (string method, Type implementedInterface) y) => x.method?.Equals(y.method) == true; - public int GetHashCode((string method, Type implementedInterface) obj) - { - return obj.method?.GetHashCode() ?? 0; - } + public int GetHashCode((string method, Type implementedInterface) obj) => obj.method?.GetHashCode() ?? 0; } private IDisposable AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options) @@ -112,10 +106,10 @@ private CompositeDisposable AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOp { var cd = new CompositeDisposable(); foreach (var (method, implementedInterface) in handler.GetType().GetTypeInfo() - .ImplementedInterfaces - .Select(x => (method: HandlerTypeDescriptorHelper.GetMethodName(x), implementedInterface: x)) - .Distinct(new EqualityComparer()) - .Where(x => !string.IsNullOrWhiteSpace(x.method)) + .ImplementedInterfaces + .Select(x => ( method: HandlerTypeDescriptorHelper.GetMethodName(x), implementedInterface: x )) + .Distinct(new EqualityComparer()) + .Where(x => !string.IsNullOrWhiteSpace(x.method)) ) { var descriptor = GetDescriptor(method, implementedInterface, handler, options); @@ -134,9 +128,11 @@ private HandlerDescriptor GetDescriptor(string method, Type handlerType, IJsonRp return GetDescriptor(method, handlerType, handler, options, typeDescriptor, @interface); } - private HandlerDescriptor GetDescriptor(string method, Type handlerType, IJsonRpcHandler handler, JsonRpcHandlerOptions options, + private HandlerDescriptor GetDescriptor( + string method, Type handlerType, IJsonRpcHandler handler, JsonRpcHandlerOptions options, IHandlerTypeDescriptor typeDescriptor, - Type @interface) + Type @interface + ) { Type @params = null; Type response = null; @@ -144,7 +140,7 @@ private HandlerDescriptor GetDescriptor(string method, Type handlerType, IJsonRp { @params = @interface.GetTypeInfo().GetGenericArguments()[0]; var requestInterface = @params.GetInterfaces() - .FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IRequest<>)); + .FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IRequest<>)); if (requestInterface != null) { response = requestInterface.GetGenericArguments()[0]; @@ -155,9 +151,9 @@ private HandlerDescriptor GetDescriptor(string method, Type handlerType, IJsonRp options?.RequestProcessType ?? typeDescriptor?.RequestProcessType ?? handlerType.GetCustomAttributes(true) - .Concat(@interface.GetCustomAttributes(true)) - .OfType() - .FirstOrDefault()?.Type; + .Concat(@interface.GetCustomAttributes(true)) + .OfType() + .FirstOrDefault()?.Type; var descriptor = new HandlerDescriptor( method, @@ -176,19 +172,15 @@ private HandlerDescriptor GetDescriptor(string method, Type handlerType, IJsonRp } Interlocked.Exchange(ref _descriptors, descriptors.ToImmutable()); - }); + } + ); return descriptor; } - public bool ContainsHandler(Type type) - { - return ContainsHandler(type.GetTypeInfo()); - } + public bool ContainsHandler(Type type) => ContainsHandler(type.GetTypeInfo()); - public bool ContainsHandler(TypeInfo typeInfo) - { - return this.Any(z => z.HandlerType.GetTypeInfo().IsAssignableFrom(typeInfo) || z.ImplementationType.GetTypeInfo().IsAssignableFrom(typeInfo)); - } + public bool ContainsHandler(TypeInfo typeInfo) => + this.Any(z => z.HandlerType.GetTypeInfo().IsAssignableFrom(typeInfo) || z.ImplementationType.GetTypeInfo().IsAssignableFrom(typeInfo)); } } diff --git a/src/Dap.Shared/DebugAdapterProtocolServiceCollectionExtensions.cs b/src/Dap.Shared/DebugAdapterProtocolServiceCollectionExtensions.cs index 7d89b4444..47c2557de 100644 --- a/src/Dap.Shared/DebugAdapterProtocolServiceCollectionExtensions.cs +++ b/src/Dap.Shared/DebugAdapterProtocolServiceCollectionExtensions.cs @@ -20,13 +20,15 @@ internal static IContainer AddDebugAdapterProtocolInternals(this IContainer c container.RegisterInstance(options.RequestProcessIdentifier); container.RegisterMany(nonPublicServiceTypes: true, reuse: Reuse.Singleton); container.RegisterMany(nonPublicServiceTypes: true, reuse: Reuse.Singleton); - container.RegisterMany(reuse: Reuse.Singleton); + container.RegisterMany(Reuse.Singleton); container.RegisterMany(nonPublicServiceTypes: true, reuse: Reuse.Singleton); - container.RegisterInitializer((manager, context) => { - var descriptions = context.Resolve(); - descriptions.Populate(context, manager); - }); - container.RegisterMany(reuse: Reuse.Singleton); + container.RegisterInitializer( + (manager, context) => { + var descriptions = context.Resolve(); + descriptions.Populate(context, manager); + } + ); + container.RegisterMany(Reuse.Singleton); return container; } diff --git a/src/Dap.Shared/DebugAdapterRequestRouter.cs b/src/Dap.Shared/DebugAdapterRequestRouter.cs index d66f2b14f..8b9e939bc 100644 --- a/src/Dap.Shared/DebugAdapterRequestRouter.cs +++ b/src/Dap.Shared/DebugAdapterRequestRouter.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Server; -using Request = OmniSharp.Extensions.JsonRpc.Server.Request; namespace OmniSharp.Extensions.DebugAdapter.Shared { @@ -12,30 +11,19 @@ internal class DebugAdapterRequestRouter : RequestRouterBase { private readonly DebugAdapterHandlerCollection _collection; - public DebugAdapterRequestRouter(DebugAdapterHandlerCollection collection, ISerializer serializer, IServiceScopeFactory serviceScopeFactory, ILogger logger) - : base(serializer, serviceScopeFactory, logger) - { + public DebugAdapterRequestRouter( + DebugAdapterHandlerCollection collection, ISerializer serializer, IServiceScopeFactory serviceScopeFactory, ILogger logger + ) + : base(serializer, serviceScopeFactory, logger) => _collection = collection; - } - public IDisposable Add(IJsonRpcHandler handler) - { - return _collection.Add(handler); - } + public IDisposable Add(IJsonRpcHandler handler) => _collection.Add(handler); - private IRequestDescriptor FindDescriptor(IMethodWithParams instance) - { - return new RequestDescriptor( _collection.Where(x => x.Method == instance.Method)); - } + private IRequestDescriptor FindDescriptor(IMethodWithParams instance) => + new RequestDescriptor(_collection.Where(x => x.Method == instance.Method)); - public override IRequestDescriptor GetDescriptors(Notification notification) - { - return FindDescriptor(notification); - } + public override IRequestDescriptor GetDescriptors(Notification notification) => FindDescriptor(notification); - public override IRequestDescriptor GetDescriptors(Request request) - { - return FindDescriptor(request); - } + public override IRequestDescriptor GetDescriptors(Request request) => FindDescriptor(request); } } diff --git a/src/Dap.Shared/HandlerDescriptor.cs b/src/Dap.Shared/HandlerDescriptor.cs index 20e11beb5..56c99764f 100644 --- a/src/Dap.Shared/HandlerDescriptor.cs +++ b/src/Dap.Shared/HandlerDescriptor.cs @@ -2,7 +2,6 @@ using System.Diagnostics; using System.Linq; using MediatR; -using Microsoft.Extensions.DependencyInjection; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Shared @@ -12,8 +11,10 @@ internal class HandlerDescriptor : IHandlerDescriptor, IDisposable { private readonly Action _disposeAction; - public HandlerDescriptor(string method, IHandlerTypeDescriptor typeDescriptor, IJsonRpcHandler handler, Type handlerInterface, Type @params, Type response, - RequestProcessType? requestProcessType, Action disposeAction) + public HandlerDescriptor( + string method, IHandlerTypeDescriptor typeDescriptor, IJsonRpcHandler handler, Type handlerInterface, Type @params, Type response, + RequestProcessType? requestProcessType, Action disposeAction + ) { _disposeAction = disposeAction; Handler = handler; @@ -23,9 +24,10 @@ public HandlerDescriptor(string method, IHandlerTypeDescriptor typeDescriptor, I HandlerType = handlerInterface; Params = @params; Response = response; - HasReturnType = HandlerType.GetInterfaces().Any(@interface => - @interface.IsGenericType && - typeof(IRequestHandler<,>).IsAssignableFrom(@interface.GetGenericTypeDefinition()) + HasReturnType = HandlerType.GetInterfaces().Any( + @interface => + @interface.IsGenericType && + typeof(IRequestHandler<,>).IsAssignableFrom(@interface.GetGenericTypeDefinition()) ); IsDelegatingHandler = @params?.IsGenericType == true && @@ -35,8 +37,11 @@ public HandlerDescriptor(string method, IHandlerTypeDescriptor typeDescriptor, I ); IsNotification = typeof(IJsonRpcNotificationHandler).IsAssignableFrom(handlerInterface) || handlerInterface - .GetInterfaces().Any(z => - z.IsGenericType && typeof(IJsonRpcNotificationHandler<>).IsAssignableFrom(z.GetGenericTypeDefinition())); + .GetInterfaces().Any( + z => + z.IsGenericType && typeof(IJsonRpcNotificationHandler<>) + .IsAssignableFrom(z.GetGenericTypeDefinition()) + ); IsRequest = !IsNotification; RequestProcessType = requestProcessType; } @@ -54,9 +59,6 @@ public HandlerDescriptor(string method, IHandlerTypeDescriptor typeDescriptor, I public bool IsDelegatingHandler { get; } public RequestProcessType? RequestProcessType { get; } - public void Dispose() - { - _disposeAction(); - } + public void Dispose() => _disposeAction(); } } diff --git a/src/Dap.Testing/DebugAdapterProtocolTestBase.cs b/src/Dap.Testing/DebugAdapterProtocolTestBase.cs index 3a7377d8b..1acfa03c0 100644 --- a/src/Dap.Testing/DebugAdapterProtocolTestBase.cs +++ b/src/Dap.Testing/DebugAdapterProtocolTestBase.cs @@ -5,10 +5,8 @@ using System.Threading.Tasks; using MediatR; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using OmniSharp.Extensions.DebugAdapter.Client; -using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.DebugAdapter.Protocol.Client; using OmniSharp.Extensions.DebugAdapter.Protocol.Server; using OmniSharp.Extensions.DebugAdapter.Server; @@ -28,58 +26,62 @@ public DebugAdapterProtocolTestBase(JsonRpcTestOptions testOptions) : base(testO { } - protected virtual void ConfigureClientInputOutput(PipeReader serverOutput, PipeWriter clientInput, DebugAdapterClientOptions options) - { + protected virtual void ConfigureClientInputOutput(PipeReader serverOutput, PipeWriter clientInput, DebugAdapterClientOptions options) => options.WithInput(serverOutput).WithOutput(clientInput); - } - protected virtual void ConfigureServerInputOutput(PipeReader clientOutput, PipeWriter serverInput, DebugAdapterServerOptions options) - { + protected virtual void ConfigureServerInputOutput(PipeReader clientOutput, PipeWriter serverInput, DebugAdapterServerOptions options) => options.WithInput(clientOutput).WithOutput(serverInput); - } protected virtual async Task<(IDebugAdapterClient client, IDebugAdapterServer server)> Initialize( Action clientOptionsAction, - Action serverOptionsAction) + Action serverOptionsAction + ) { var clientPipe = new Pipe(TestOptions.DefaultPipeOptions); var serverPipe = new Pipe(TestOptions.DefaultPipeOptions); - _client = DebugAdapterClient.Create(options => { - options - .WithLoggerFactory(TestOptions.ClientLoggerFactory) - .ConfigureLogging(x => { - x.SetMinimumLevel(LogLevel.Trace); - x.Services.AddSingleton(TestOptions.ClientLoggerFactory); - }) - .Services - .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) - .AddSingleton(ClientEvents as IRequestSettler); - ConfigureClientInputOutput(serverPipe.Reader, clientPipe.Writer, options); - clientOptionsAction(options); - }); + _client = DebugAdapterClient.Create( + options => { + options + .WithLoggerFactory(TestOptions.ClientLoggerFactory) + .ConfigureLogging( + x => { + x.SetMinimumLevel(LogLevel.Trace); + x.Services.AddSingleton(TestOptions.ClientLoggerFactory); + } + ) + .Services + .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) + .AddSingleton(ClientEvents as IRequestSettler); + ConfigureClientInputOutput(serverPipe.Reader, clientPipe.Writer, options); + clientOptionsAction(options); + } + ); - _server = DebugAdapterServer.Create(options => { - options - .WithLoggerFactory(TestOptions.ServerLoggerFactory) - .ConfigureLogging(x => { - x.SetMinimumLevel(LogLevel.Trace); - x.Services.AddSingleton(TestOptions.ServerLoggerFactory); - }) - .Services - .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) - .AddSingleton(ServerEvents as IRequestSettler); - ConfigureServerInputOutput(clientPipe.Reader, serverPipe.Writer, options); - serverOptionsAction(options); - }); + _server = DebugAdapterServer.Create( + options => { + options + .WithLoggerFactory(TestOptions.ServerLoggerFactory) + .ConfigureLogging( + x => { + x.SetMinimumLevel(LogLevel.Trace); + x.Services.AddSingleton(TestOptions.ServerLoggerFactory); + } + ) + .Services + .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) + .AddSingleton(ServerEvents as IRequestSettler); + ConfigureServerInputOutput(clientPipe.Reader, serverPipe.Writer, options); + serverOptionsAction(options); + } + ); Disposable.Add(_client); Disposable.Add(_server); - return await ObservableEx.ForkJoin( - Observable.FromAsync(_client.Initialize), + return await Observable.FromAsync(_client.Initialize).ForkJoin( Observable.FromAsync(_server.Initialize), - (a, b) => (_client, _server) + (a, b) => ( _client, _server ) ).ToTask(CancellationToken); } } diff --git a/src/Dap.Testing/DebugAdapterServerTestBase.cs b/src/Dap.Testing/DebugAdapterServerTestBase.cs index aadd3d72c..77fe8fee2 100644 --- a/src/Dap.Testing/DebugAdapterServerTestBase.cs +++ b/src/Dap.Testing/DebugAdapterServerTestBase.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OmniSharp.Extensions.DebugAdapter.Client; -using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.DebugAdapter.Protocol.Client; using OmniSharp.Extensions.JsonRpc.Testing; @@ -26,20 +25,24 @@ public DebugAdapterServerTestBase(JsonRpcTestOptions jsonRpcTestOptions) : base( protected virtual async Task InitializeClient(Action clientOptionsAction = null) { - _client = DebugAdapterClient.Create(options => { - var (reader, writer) = SetupServer(); - options - .WithInput(reader) - .WithOutput(writer) - .ConfigureLogging(x => { - x.SetMinimumLevel(LogLevel.Trace); - x.Services.AddSingleton(TestOptions.ClientLoggerFactory); - }) - .Services - .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) - .AddSingleton(Events as IRequestSettler); - clientOptionsAction?.Invoke(options); - }); + _client = DebugAdapterClient.Create( + options => { + var (reader, writer) = SetupServer(); + options + .WithInput(reader) + .WithOutput(writer) + .ConfigureLogging( + x => { + x.SetMinimumLevel(LogLevel.Trace); + x.Services.AddSingleton(TestOptions.ClientLoggerFactory); + } + ) + .Services + .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) + .AddSingleton(Events as IRequestSettler); + clientOptionsAction?.Invoke(options); + } + ); Disposable.Add(_client); diff --git a/src/JsonRpc.Generators/GenerateHandlerMethodsGenerator.cs b/src/JsonRpc.Generators/GenerateHandlerMethodsGenerator.cs index 54b3cdec5..d617ce98a 100644 --- a/src/JsonRpc.Generators/GenerateHandlerMethodsGenerator.cs +++ b/src/JsonRpc.Generators/GenerateHandlerMethodsGenerator.cs @@ -1,6 +1,4 @@ using System; -using System.Buffers; -using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -18,20 +16,17 @@ public class GenerateHandlerMethodsGenerator : IRichCodeGenerator { private readonly AttributeData _attributeData; - public GenerateHandlerMethodsGenerator(AttributeData attributeData) - { - _attributeData = attributeData; - } + public GenerateHandlerMethodsGenerator(AttributeData attributeData) => _attributeData = attributeData; public Task GenerateRichAsync(TransformationContext context, IProgress progress, CancellationToken cancellationToken) { - if (!(context.ProcessingNode is InterfaceDeclarationSyntax handlerInterface)) + if (!( context.ProcessingNode is InterfaceDeclarationSyntax handlerInterface )) { return Task.FromResult(new RichGenerationResult()); } var methods = new List(); - var additionalUsings = new HashSet() { + var additionalUsings = new HashSet { "System", "System.Collections.Generic", "System.Threading", @@ -59,55 +54,75 @@ public Task GenerateRichAsync(TransformationContext contex } var existingUsings = context.CompilationUnitUsings - .Join(additionalUsings, z => z.Name.ToFullString(), z => z, (a, b) => b) + .Join(additionalUsings, z => z.Name.ToFullString(), z => z, (a, b) => b) ; var newUsings = additionalUsings - .Except(existingUsings) - .Select(z => UsingDirective(IdentifierName(z))) + .Except(existingUsings) + .Select(z => UsingDirective(IdentifierName(z))) ; - var attributes = List(new[] { - AttributeList(SeparatedList(new[] { - Attribute(ParseName("System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute")), - Attribute(ParseName("System.Runtime.CompilerServices.CompilerGeneratedAttribute")), - })) - }); - - return Task.FromResult(new RichGenerationResult() { - Usings = List(newUsings), - Members = List(new[] { - NamespaceDeclaration(ParseName(symbol.ContainingNamespace.ToDisplayString())) - - .WithMembers(List(new MemberDeclarationSyntax[] { - ClassDeclaration(className) - .WithAttributeLists(attributes) - .WithModifiers(TokenList( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.PartialKeyword) - )) - .WithMembers(List(methods)) - .NormalizeWhitespace() - })) - }) - }); + var attributes = List( + new[] { + AttributeList( + SeparatedList( + new[] { + Attribute(ParseName("System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute")), + Attribute(ParseName("System.Runtime.CompilerServices.CompilerGeneratedAttribute")), + } + ) + ) + } + ); + + return Task.FromResult( + new RichGenerationResult { + Usings = List(newUsings), + Members = List( + new[] { + NamespaceDeclaration(ParseName(symbol.ContainingNamespace.ToDisplayString())) + .WithMembers( + List( + new MemberDeclarationSyntax[] { + ClassDeclaration(className) + .WithAttributeLists(attributes) + .WithModifiers( + TokenList( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword), + Token(SyntaxKind.PartialKeyword) + ) + ) + .WithMembers(List(methods)) + .NormalizeWhitespace() + } + ) + ) + } + ) + } + ); } - IEnumerable HandleNotifications( + private IEnumerable HandleNotifications( InterfaceDeclarationSyntax handlerInterface, INamedTypeSymbol interfaceType, INamedTypeSymbol requestType, NameSyntax registryType, - HashSet additionalUsings) + HashSet additionalUsings + ) { var methodName = GetOnMethodName(interfaceType, _attributeData); - var parameters = ParameterList(SeparatedList(new[] { - Parameter(Identifier("registry")) - .WithType(registryType) - .WithModifiers(TokenList(Token(SyntaxKind.ThisKeyword))) - })); + var parameters = ParameterList( + SeparatedList( + new[] { + Parameter(Identifier("registry")) + .WithType(registryType) + .WithModifiers(TokenList(Token(SyntaxKind.ThisKeyword))) + } + ) + ); var capability = GetCapability(interfaceType); var registrationOptions = GetRegistrationOptions(interfaceType); @@ -117,19 +132,25 @@ IEnumerable HandleNotifications( if (registrationOptions == null) { var method = MethodDeclaration(registryType, methodName) - .WithModifiers(TokenList( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword)) - ) - .WithExpressionBody(GetNotificationHandlerExpression(GetMethodName(handlerInterface))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + .WithModifiers( + TokenList( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword) + ) + ) + .WithExpressionBody(GetNotificationHandlerExpression(GetMethodName(handlerInterface))) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); MemberDeclarationSyntax MakeAction(TypeSyntax syntax) { return method - .WithParameterList(parameters.AddParameters(Parameter(Identifier("handler")) - .WithType(syntax))) - .NormalizeWhitespace(); + .WithParameterList( + parameters.AddParameters( + Parameter(Identifier("handler")) + .WithType(syntax) + ) + ) + .NormalizeWhitespace(); } yield return MakeAction(CreateAction(false, requestType)); @@ -147,21 +168,30 @@ MemberDeclarationSyntax MakeAction(TypeSyntax syntax) else { var method = MethodDeclaration(registryType, methodName) - .WithModifiers(TokenList( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword)) - ) - .WithBody(GetNotificationRegistrationHandlerExpression(GetMethodName(handlerInterface), requestType, registrationOptions)); + .WithModifiers( + TokenList( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword) + ) + ) + .WithBody(GetNotificationRegistrationHandlerExpression(GetMethodName(handlerInterface), requestType, registrationOptions)); var registrationParameter = Parameter(Identifier("registrationOptions")) - .WithType(IdentifierName(registrationOptions.Name)); + .WithType(IdentifierName(registrationOptions.Name)); MemberDeclarationSyntax MakeAction(TypeSyntax syntax) { return method - .WithParameterList(parameters.WithParameters(SeparatedList(parameters.Parameters.Concat( - new[] {Parameter(Identifier("handler")).WithType(syntax), registrationParameter})))) - .NormalizeWhitespace(); + .WithParameterList( + parameters.WithParameters( + SeparatedList( + parameters.Parameters.Concat( + new[] { Parameter(Identifier("handler")).WithType(syntax), registrationParameter } + ) + ) + ) + ) + .NormalizeWhitespace(); } yield return MakeAction(CreateAction(false, requestType)); @@ -171,20 +201,22 @@ MemberDeclarationSyntax MakeAction(TypeSyntax syntax) if (capability != null) { method = method.WithBody( - GetNotificationRegistrationHandlerExpression(GetMethodName(handlerInterface), requestType, registrationOptions, capability)); + GetNotificationRegistrationHandlerExpression(GetMethodName(handlerInterface), requestType, registrationOptions, capability) + ); yield return MakeAction(CreateAction(requestType, capability)); yield return MakeAction(CreateAsyncAction(requestType, capability)); } } } - IEnumerable HandleRequest( + private IEnumerable HandleRequest( InterfaceDeclarationSyntax handlerInterface, INamedTypeSymbol interfaceType, INamedTypeSymbol requestType, INamedTypeSymbol responseType, NameSyntax registryType, - HashSet additionalUsings) + HashSet additionalUsings + ) { var methodName = GetOnMethodName(interfaceType, _attributeData); @@ -197,34 +229,44 @@ IEnumerable HandleRequest( if (partialItems != null) additionalUsings.Add(partialItems.ContainingNamespace.ToDisplayString()); if (partialItem != null) additionalUsings.Add(partialItem.ContainingNamespace.ToDisplayString()); - var parameters = ParameterList(SeparatedList(new[] { - Parameter(Identifier("registry")) - .WithType(registryType) - .WithModifiers(TokenList(Token(SyntaxKind.ThisKeyword))) - })); + var parameters = ParameterList( + SeparatedList( + new[] { + Parameter(Identifier("registry")) + .WithType(registryType) + .WithModifiers(TokenList(Token(SyntaxKind.ThisKeyword))) + } + ) + ); var allowDerivedRequests = _attributeData.NamedArguments - .Where(z => z.Key == "AllowDerivedRequests") - .Select(z => z.Value.Value) - .FirstOrDefault() is bool b && b; + .Where(z => z.Key == "AllowDerivedRequests") + .Select(z => z.Value.Value) + .FirstOrDefault() is bool b && b; if (registrationOptions == null) { var method = MethodDeclaration(registryType, methodName) - .WithModifiers(TokenList( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword)) - ) - .WithExpressionBody(GetRequestHandlerExpression(GetMethodName(handlerInterface))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + .WithModifiers( + TokenList( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword) + ) + ) + .WithExpressionBody(GetRequestHandlerExpression(GetMethodName(handlerInterface))) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); MemberDeclarationSyntax MakeAction(TypeSyntax syntax) { return method - .WithParameterList(parameters.AddParameters(Parameter(Identifier("handler")) - .WithType(syntax))) - .NormalizeWhitespace(); + .WithParameterList( + parameters.AddParameters( + Parameter(Identifier("handler")) + .WithType(syntax) + ) + ) + .NormalizeWhitespace(); } yield return MakeAction(CreateAsyncFunc(responseType, false, requestType)); @@ -235,13 +277,23 @@ MemberDeclarationSyntax MakeAction(TypeSyntax syntax) MemberDeclarationSyntax MakeDerivedAction(TypeSyntax syntax) { return method - .WithParameterList(parameters.WithParameters(SeparatedList(parameters.Parameters.Concat( - new[] {Parameter(Identifier("handler")).WithType(syntax)})))) - .WithTypeParameterList(TypeParameterList(SingletonSeparatedList(TypeParameter(Identifier("T"))))) - .WithConstraintClauses(SingletonList(TypeParameterConstraintClause(IdentifierName("T")) - .WithConstraints(SingletonSeparatedList(TypeConstraint(ResolveTypeName(requestType))))) - ) - .NormalizeWhitespace(); + .WithParameterList( + parameters.WithParameters( + SeparatedList( + parameters.Parameters.Concat( + new[] { Parameter(Identifier("handler")).WithType(syntax) } + ) + ) + ) + ) + .WithTypeParameterList(TypeParameterList(SingletonSeparatedList(TypeParameter(Identifier("T"))))) + .WithConstraintClauses( + SingletonList( + TypeParameterConstraintClause(IdentifierName("T")) + .WithConstraints(SingletonSeparatedList(TypeConstraint(ResolveTypeName(requestType)))) + ) + ) + .NormalizeWhitespace(); } yield return MakeDerivedAction(CreateDerivedAsyncFunc(responseType, false)); @@ -251,7 +303,7 @@ MemberDeclarationSyntax MakeDerivedAction(TypeSyntax syntax) if (partialItems != null) { var partialTypeSyntax = ResolveTypeName(partialItems); - var partialItemsSyntax = GenericName("IEnumerable").WithTypeArgumentList(TypeArgumentList(SeparatedList(new[] {partialTypeSyntax}))); + var partialItemsSyntax = GenericName("IEnumerable").WithTypeArgumentList(TypeArgumentList(SeparatedList(new[] { partialTypeSyntax }))); method = method.WithExpressionBody(GetPartialResultsHandlerExpression(GetMethodName(handlerInterface), requestType, partialTypeSyntax, responseType)); @@ -259,8 +311,12 @@ MemberDeclarationSyntax MakeDerivedAction(TypeSyntax syntax) yield return MakeAction(CreatePartialAction(requestType, partialItemsSyntax, false)); if (capability != null) { - method = method.WithExpressionBody(GetPartialResultsCapabilityHandlerExpression(GetMethodName(handlerInterface), requestType, responseType, - partialTypeSyntax, capability)); + method = method.WithExpressionBody( + GetPartialResultsCapabilityHandlerExpression( + GetMethodName(handlerInterface), requestType, responseType, + partialTypeSyntax, capability + ) + ); yield return MakeAction(CreatePartialAction(requestType, partialItemsSyntax, capability)); } } @@ -283,32 +339,42 @@ MemberDeclarationSyntax MakeDerivedAction(TypeSyntax syntax) if (capability != null) { method = method.WithExpressionBody( - GetRequestCapabilityHandlerExpression(GetMethodName(handlerInterface), requestType, responseType, capability)); + GetRequestCapabilityHandlerExpression(GetMethodName(handlerInterface), requestType, responseType, capability) + ); yield return MakeAction(CreateAsyncFunc(responseType, requestType, capability)); } } else { var method = MethodDeclaration(registryType, methodName) - .WithModifiers(TokenList( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword)) - ) - .WithBody(GetRequestRegistrationHandlerExpression(GetMethodName(handlerInterface), requestType, responseType, registrationOptions)); + .WithModifiers( + TokenList( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword) + ) + ) + .WithBody(GetRequestRegistrationHandlerExpression(GetMethodName(handlerInterface), requestType, responseType, registrationOptions)); if (responseType.Name == "Unit") { method = method.WithBody(GetVoidRequestRegistrationHandlerExpression(GetMethodName(handlerInterface), requestType, registrationOptions)); } var registrationParameter = Parameter(Identifier("registrationOptions")) - .WithType(IdentifierName(registrationOptions.Name)); + .WithType(IdentifierName(registrationOptions.Name)); MemberDeclarationSyntax MakeAction(TypeSyntax syntax) { return method - .WithParameterList(parameters.WithParameters(SeparatedList(parameters.Parameters.Concat( - new[] {Parameter(Identifier("handler")).WithType(syntax), registrationParameter})))) - .NormalizeWhitespace(); + .WithParameterList( + parameters.WithParameters( + SeparatedList( + parameters.Parameters.Concat( + new[] { Parameter(Identifier("handler")).WithType(syntax), registrationParameter } + ) + ) + ) + ) + .NormalizeWhitespace(); } yield return MakeAction(CreateAsyncFunc(responseType, false, requestType)); @@ -319,13 +385,23 @@ MemberDeclarationSyntax MakeAction(TypeSyntax syntax) MemberDeclarationSyntax MakeDerivedAction(TypeSyntax syntax) { return method - .WithParameterList(parameters.WithParameters(SeparatedList(parameters.Parameters.Concat( - new[] {Parameter(Identifier("handler")).WithType(syntax), registrationParameter})))) - .WithTypeParameterList(TypeParameterList(SingletonSeparatedList(TypeParameter(Identifier("T"))))) - .WithConstraintClauses(SingletonList(TypeParameterConstraintClause(IdentifierName("T")) - .WithConstraints(SingletonSeparatedList(TypeConstraint(ResolveTypeName(requestType))))) - ) - .NormalizeWhitespace(); + .WithParameterList( + parameters.WithParameters( + SeparatedList( + parameters.Parameters.Concat( + new[] { Parameter(Identifier("handler")).WithType(syntax), registrationParameter } + ) + ) + ) + ) + .WithTypeParameterList(TypeParameterList(SingletonSeparatedList(TypeParameter(Identifier("T"))))) + .WithConstraintClauses( + SingletonList( + TypeParameterConstraintClause(IdentifierName("T")) + .WithConstraints(SingletonSeparatedList(TypeConstraint(ResolveTypeName(requestType)))) + ) + ) + .NormalizeWhitespace(); } yield return MakeDerivedAction(CreateDerivedAsyncFunc(responseType, false)); @@ -335,17 +411,25 @@ MemberDeclarationSyntax MakeDerivedAction(TypeSyntax syntax) if (partialItems != null) { var partialTypeSyntax = ResolveTypeName(partialItems); - var partialItemsSyntax = GenericName("IEnumerable").WithTypeArgumentList(TypeArgumentList(SeparatedList(new[] {partialTypeSyntax}))); + var partialItemsSyntax = GenericName("IEnumerable").WithTypeArgumentList(TypeArgumentList(SeparatedList(new[] { partialTypeSyntax }))); - method = method.WithBody(GetPartialResultsRegistrationHandlerExpression(GetMethodName(handlerInterface), requestType, responseType, partialTypeSyntax, - registrationOptions)); + method = method.WithBody( + GetPartialResultsRegistrationHandlerExpression( + GetMethodName(handlerInterface), requestType, responseType, partialTypeSyntax, + registrationOptions + ) + ); yield return MakeAction(CreatePartialAction(requestType, partialItemsSyntax, true)); yield return MakeAction(CreatePartialAction(requestType, partialItemsSyntax, false)); if (capability != null) { - method = method.WithBody(GetPartialResultsRegistrationHandlerExpression(GetMethodName(handlerInterface), requestType, responseType, partialTypeSyntax, - registrationOptions, capability)); + method = method.WithBody( + GetPartialResultsRegistrationHandlerExpression( + GetMethodName(handlerInterface), requestType, responseType, partialTypeSyntax, + registrationOptions, capability + ) + ); yield return MakeAction(CreatePartialAction(requestType, partialItemsSyntax, capability)); } } @@ -360,8 +444,12 @@ MemberDeclarationSyntax MakeDerivedAction(TypeSyntax syntax) yield return MakeAction(CreatePartialAction(requestType, partialTypeSyntax, false)); if (capability != null) { - method = method.WithBody(GetPartialResultRegistrationHandlerExpression(GetMethodName(handlerInterface), requestType, responseType, registrationOptions, - capability)); + method = method.WithBody( + GetPartialResultRegistrationHandlerExpression( + GetMethodName(handlerInterface), requestType, responseType, registrationOptions, + capability + ) + ); yield return MakeAction(CreatePartialAction(requestType, partialTypeSyntax, capability)); } } @@ -369,7 +457,8 @@ MemberDeclarationSyntax MakeDerivedAction(TypeSyntax syntax) if (capability != null) { method = method.WithBody( - GetRequestRegistrationHandlerExpression(GetMethodName(handlerInterface), requestType, responseType, registrationOptions, capability)); + GetRequestRegistrationHandlerExpression(GetMethodName(handlerInterface), requestType, responseType, registrationOptions, capability) + ); if (responseType.Name == "Unit") { method = method.WithBody(GetVoidRequestRegistrationHandlerExpression(GetMethodName(handlerInterface), requestType, registrationOptions, capability)); @@ -380,18 +469,19 @@ MemberDeclarationSyntax MakeDerivedAction(TypeSyntax syntax) } } - static IEnumerable GetRegistries( + private static IEnumerable GetRegistries( AttributeData attributeData, InterfaceDeclarationSyntax interfaceSyntax, INamedTypeSymbol interfaceType, TransformationContext context, IProgress progress, - HashSet additionalUsings) + HashSet additionalUsings + ) { if (attributeData.ConstructorArguments[0].Values.Length > 0) { return attributeData.ConstructorArguments[0].Values.Select(z => z.Value).OfType() - .Select(ResolveTypeName); + .Select(ResolveTypeName); } if (interfaceType.ContainingNamespace.ToDisplayString().StartsWith("OmniSharp.Extensions.LanguageServer.Protocol")) @@ -411,20 +501,20 @@ static IEnumerable GetRegistries( ClientToServer = 0b0010, Bidirectional = 0b0011 */ - var maskedDirection = (0b0011 & direction); + var maskedDirection = 0b0011 & direction; if (maskedDirection == 1) { additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Client"); additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities"); - return new[] {LanguageProtocolServerToClient}; + return new[] { LanguageProtocolServerToClient }; } if (maskedDirection == 2) { additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Server"); - return new[] {LanguageProtocolClientToServer}; + return new[] { LanguageProtocolClientToServer }; } if (maskedDirection == 3) @@ -432,7 +522,7 @@ static IEnumerable GetRegistries( additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Client"); additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities"); additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Server"); - return new[] {LanguageProtocolClientToServer, LanguageProtocolServerToClient}; + return new[] { LanguageProtocolClientToServer, LanguageProtocolServerToClient }; } } @@ -453,24 +543,24 @@ static IEnumerable GetRegistries( ClientToServer = 0b0010, Bidirectional = 0b0011 */ - var maskedDirection = (0b0011 & direction); + var maskedDirection = 0b0011 & direction; additionalUsings.Add("OmniSharp.Extensions.DebugAdapter.Protocol"); additionalUsings.Add("OmniSharp.Extensions.DebugAdapter.Protocol.Client"); additionalUsings.Add("OmniSharp.Extensions.DebugAdapter.Protocol.Server"); if (maskedDirection == 1) { - return new[] {DebugProtocolServerToClient}; + return new[] { DebugProtocolServerToClient }; } if (maskedDirection == 2) { - return new[] {DebugProtocolClientToServer}; + return new[] { DebugProtocolClientToServer }; } if (maskedDirection == 3) { - return new[] {DebugProtocolClientToServer, DebugProtocolServerToClient}; + return new[] { DebugProtocolClientToServer, DebugProtocolServerToClient }; } } diff --git a/src/JsonRpc.Generators/GenerateRequestMethodsGenerator.cs b/src/JsonRpc.Generators/GenerateRequestMethodsGenerator.cs index 9ba5ead07..33d062ce6 100644 --- a/src/JsonRpc.Generators/GenerateRequestMethodsGenerator.cs +++ b/src/JsonRpc.Generators/GenerateRequestMethodsGenerator.cs @@ -16,25 +16,20 @@ public class GenerateRequestMethodsGenerator : IRichCodeGenerator { private readonly AttributeData _attributeData; - public GenerateRequestMethodsGenerator(AttributeData attributeData) - { - _attributeData = attributeData; - } + public GenerateRequestMethodsGenerator(AttributeData attributeData) => _attributeData = attributeData; - public Task> GenerateAsync(TransformationContext context, IProgress progress, CancellationToken cancellationToken) - { + public Task> GenerateAsync(TransformationContext context, IProgress progress, CancellationToken cancellationToken) => throw new NotImplementedException(); - } public Task GenerateRichAsync(TransformationContext context, IProgress progress, CancellationToken cancellationToken) { - if (!(context.ProcessingNode is InterfaceDeclarationSyntax handlerInterface)) + if (!( context.ProcessingNode is InterfaceDeclarationSyntax handlerInterface )) { return Task.FromResult(new RichGenerationResult()); } var methods = new List(); - var additionalUsings = new HashSet() { + var additionalUsings = new HashSet { "System", "System.Collections.Generic", "System.Threading", @@ -50,8 +45,12 @@ public Task GenerateRichAsync(TransformationContext contex if (_attributeData.ConstructorArguments[0].Values.Length == 0 && !symbol.ContainingNamespace.ToDisplayString().StartsWith("OmniSharp.Extensions.DebugAdapter.Protocol")) { - progress.Report(Diagnostic.Create(GeneratorDiagnostics.NoResponseRouterProvided, handlerInterface.Identifier.GetLocation(), symbol.Name, - string.Join(", ", registries.Select(z => z.ToFullString())))); + progress.Report( + Diagnostic.Create( + GeneratorDiagnostics.NoResponseRouterProvided, handlerInterface.Identifier.GetLocation(), symbol.Name, + string.Join(", ", registries.Select(z => z.ToFullString())) + ) + ); } foreach (var registry in registries) @@ -71,42 +70,58 @@ public Task GenerateRichAsync(TransformationContext contex } - var attributes = List(new[] { - AttributeList(SeparatedList(new[] { - Attribute(ParseName("System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute")), - Attribute(ParseName("System.Runtime.CompilerServices.CompilerGeneratedAttribute")), - })) - }); + var attributes = List( + new[] { + AttributeList( + SeparatedList( + new[] { + Attribute(ParseName("System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute")), + Attribute(ParseName("System.Runtime.CompilerServices.CompilerGeneratedAttribute")), + } + ) + ) + } + ); if (symbol.GetAttributes().Any(z => z.AttributeClass.Name == "GenerateRequestMethodsAttribute")) { attributes = List(); } var existingUsings = context.CompilationUnitUsings - .Join(additionalUsings, z => z.Name.ToFullString(), z => z, (a, b) => b) + .Join(additionalUsings, z => z.Name.ToFullString(), z => z, (a, b) => b) ; var newUsings = additionalUsings - .Except(existingUsings) - .Select(z => UsingDirective(IdentifierName(z))) + .Except(existingUsings) + .Select(z => UsingDirective(IdentifierName(z))) ; - return Task.FromResult(new RichGenerationResult() { - Usings = List(newUsings), - Members = List(new[] { - NamespaceDeclaration(ParseName(symbol.ContainingNamespace.ToDisplayString())) - .WithMembers(List(new MemberDeclarationSyntax[] { - ClassDeclaration(className) - .WithAttributeLists(attributes) - .WithModifiers(TokenList( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.PartialKeyword) - )) - .WithMembers(List(methods)) - .NormalizeWhitespace() - })) - }) - }); + return Task.FromResult( + new RichGenerationResult { + Usings = List(newUsings), + Members = List( + new[] { + NamespaceDeclaration(ParseName(symbol.ContainingNamespace.ToDisplayString())) + .WithMembers( + List( + new MemberDeclarationSyntax[] { + ClassDeclaration(className) + .WithAttributeLists(attributes) + .WithModifiers( + TokenList( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword), + Token(SyntaxKind.PartialKeyword) + ) + ) + .WithMembers(List(methods)) + .NormalizeWhitespace() + } + ) + ) + } + ) + } + ); } public static IEnumerable GetProxies( @@ -115,12 +130,13 @@ public static IEnumerable GetProxies( INamedTypeSymbol interfaceType, TransformationContext context, IProgress progress, - HashSet additionalUsings) + HashSet additionalUsings + ) { if (attributeData.ConstructorArguments[0].Values.Length > 0) { return attributeData.ConstructorArguments[0].Values.Select(z => z.Value).OfType() - .Select(ResolveTypeName); + .Select(ResolveTypeName); } if (interfaceType.ContainingNamespace.ToDisplayString().StartsWith("OmniSharp.Extensions.LanguageServer.Protocol")) @@ -140,25 +156,25 @@ public static IEnumerable GetProxies( ClientToServer = 0b0010, Bidirectional = 0b0011 */ - var maskedDirection = (0b0011 & direction); + var maskedDirection = 0b0011 & direction; if (maskedDirection == 1) { additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Server"); - return new[] {LanguageProtocolServerToClient}; + return new[] { LanguageProtocolServerToClient }; } if (maskedDirection == 2) { additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Client"); - return new[] {LanguageProtocolClientToServer}; + return new[] { LanguageProtocolClientToServer }; } if (maskedDirection == 3) { additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Server"); additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Client"); - return new[] {LanguageProtocolClientToServer, LanguageProtocolServerToClient}; + return new[] { LanguageProtocolClientToServer, LanguageProtocolServerToClient }; } } @@ -179,22 +195,22 @@ public static IEnumerable GetProxies( ClientToServer = 0b0010, Bidirectional = 0b0011 */ - var maskedDirection = (0b0011 & direction); + var maskedDirection = 0b0011 & direction; additionalUsings.Add("OmniSharp.Extensions.DebugAdapter.Protocol"); if (maskedDirection == 1) { - return new[] {DebugProtocolServerToClient}; + return new[] { DebugProtocolServerToClient }; } if (maskedDirection == 2) { - return new[] {DebugProtocolClientToServer}; + return new[] { DebugProtocolClientToServer }; } if (maskedDirection == 3) { - return new[] {DebugProtocolClientToServer, DebugProtocolServerToClient}; + return new[] { DebugProtocolClientToServer, DebugProtocolServerToClient }; } } @@ -213,80 +229,101 @@ public static IEnumerable GetProxies( private static NameSyntax DebugProtocolClientToServer { get; } = ParseName("IDebugAdapterClient"); - IEnumerable HandleNotifications( + private IEnumerable HandleNotifications( InterfaceDeclarationSyntax handlerInterface, INamedTypeSymbol interfaceType, INamedTypeSymbol requestType, NameSyntax registryType, - HashSet additionalUsings) + HashSet additionalUsings + ) { var methodName = GetSendMethodName(interfaceType, _attributeData); var method = MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), methodName) - .WithModifiers(TokenList( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword)) - ) - .WithExpressionBody(GetNotificationInvokeExpression()) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + .WithModifiers( + TokenList( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword) + ) + ) + .WithExpressionBody(GetNotificationInvokeExpression()) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); yield return method - .WithParameterList( - ParameterList(SeparatedList(new[] { - Parameter(Identifier("mediator")) - .WithType(registryType) - .WithModifiers(TokenList(Token(SyntaxKind.ThisKeyword))), - Parameter(Identifier("@params")) - .WithType(IdentifierName(requestType.Name)) - }))) - .NormalizeWhitespace(); + .WithParameterList( + ParameterList( + SeparatedList( + new[] { + Parameter(Identifier("mediator")) + .WithType(registryType) + .WithModifiers(TokenList(Token(SyntaxKind.ThisKeyword))), + Parameter(Identifier("@params")) + .WithType(IdentifierName(requestType.Name)) + } + ) + ) + ) + .NormalizeWhitespace(); } - IEnumerable HandleRequests( + private IEnumerable HandleRequests( InterfaceDeclarationSyntax handlerInterface, INamedTypeSymbol interfaceType, INamedTypeSymbol requestType, INamedTypeSymbol responseType, NameSyntax registryType, - HashSet additionalUsings) + HashSet additionalUsings + ) { var methodName = GetSendMethodName(interfaceType, _attributeData); - var parameterList = ParameterList(SeparatedList(new[] { - Parameter(Identifier("mediator")) - .WithType(registryType) - .WithModifiers(TokenList(Token(SyntaxKind.ThisKeyword))), - Parameter(Identifier("@params")) - .WithType(IdentifierName(requestType.Name)), - Parameter(Identifier("cancellationToken")) - .WithType(IdentifierName("CancellationToken")) - .WithDefault(EqualsValueClause( - LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword))) - ) - })); + var parameterList = ParameterList( + SeparatedList( + new[] { + Parameter(Identifier("mediator")) + .WithType(registryType) + .WithModifiers(TokenList(Token(SyntaxKind.ThisKeyword))), + Parameter(Identifier("@params")) + .WithType(IdentifierName(requestType.Name)), + Parameter(Identifier("cancellationToken")) + .WithType(IdentifierName("CancellationToken")) + .WithDefault( + EqualsValueClause( + LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)) + ) + ) + } + ) + ); var partialItem = GetPartialItem(requestType); if (partialItem != null) { additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Progress"); var partialTypeSyntax = ResolveTypeName(partialItem); yield return MethodDeclaration( - GenericName( - Identifier("IRequestProgressObservable")) - .WithTypeArgumentList( - TypeArgumentList( - SeparatedList( - new TypeSyntax[] { - partialTypeSyntax, - ResolveTypeName(responseType) - }))), - Identifier(methodName) - ) - .WithModifiers(TokenList( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword)) - ) - .WithParameterList(parameterList) - .WithExpressionBody(GetPartialInvokeExpression(ResolveTypeName(responseType))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .NormalizeWhitespace(); + GenericName( + Identifier("IRequestProgressObservable") + ) + .WithTypeArgumentList( + TypeArgumentList( + SeparatedList( + new TypeSyntax[] { + partialTypeSyntax, + ResolveTypeName(responseType) + } + ) + ) + ), + Identifier(methodName) + ) + .WithModifiers( + TokenList( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword) + ) + ) + .WithParameterList(parameterList) + .WithExpressionBody(GetPartialInvokeExpression(ResolveTypeName(responseType))) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .NormalizeWhitespace(); yield break; } @@ -295,44 +332,52 @@ IEnumerable HandleRequests( { additionalUsings.Add("OmniSharp.Extensions.LanguageServer.Protocol.Progress"); var partialTypeSyntax = ResolveTypeName(partialItems); - var partialItemsSyntax = GenericName("IEnumerable").WithTypeArgumentList(TypeArgumentList(SeparatedList(new[] {partialTypeSyntax}))); + var partialItemsSyntax = GenericName("IEnumerable").WithTypeArgumentList(TypeArgumentList(SeparatedList(new[] { partialTypeSyntax }))); yield return MethodDeclaration( - GenericName( - Identifier("IRequestProgressObservable")) - .WithTypeArgumentList( - TypeArgumentList( - SeparatedList( - new TypeSyntax[] { - partialItemsSyntax, - ResolveTypeName(responseType) - }))), - Identifier(methodName) - ) - .WithModifiers(TokenList( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword)) - ) - .WithParameterList(parameterList) - .WithExpressionBody(GetPartialInvokeExpression(ResolveTypeName(responseType))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .NormalizeWhitespace(); - ; + GenericName( + Identifier("IRequestProgressObservable") + ) + .WithTypeArgumentList( + TypeArgumentList( + SeparatedList( + new TypeSyntax[] { + partialItemsSyntax, + ResolveTypeName(responseType) + } + ) + ) + ), + Identifier(methodName) + ) + .WithModifiers( + TokenList( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword) + ) + ) + .WithParameterList(parameterList) + .WithExpressionBody(GetPartialInvokeExpression(ResolveTypeName(responseType))) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .NormalizeWhitespace(); + ; yield break; } var responseSyntax = responseType.Name == "Unit" ? IdentifierName("Task") as NameSyntax - : GenericName("Task").WithTypeArgumentList(TypeArgumentList(SeparatedList(new[] {ResolveTypeName(responseType)}))); - yield return MethodDeclaration(responseSyntax, methodName) - .WithModifiers(TokenList( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword)) - ) - .WithParameterList(parameterList) - .WithExpressionBody(GetRequestInvokeExpression()) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .NormalizeWhitespace(); + : GenericName("Task").WithTypeArgumentList(TypeArgumentList(SeparatedList(new[] { ResolveTypeName(responseType) }))); + yield return MethodDeclaration(responseSyntax, methodName) + .WithModifiers( + TokenList( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword) + ) + ) + .WithParameterList(parameterList) + .WithExpressionBody(GetRequestInvokeExpression()) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .NormalizeWhitespace(); } } } diff --git a/src/JsonRpc.Generators/GeneratorDiagnostics.cs b/src/JsonRpc.Generators/GeneratorDiagnostics.cs index e00ef03e1..76b4f835a 100644 --- a/src/JsonRpc.Generators/GeneratorDiagnostics.cs +++ b/src/JsonRpc.Generators/GeneratorDiagnostics.cs @@ -2,15 +2,21 @@ namespace OmniSharp.Extensions.JsonRpc.Generators { - static class GeneratorDiagnostics + internal static class GeneratorDiagnostics { - public static DiagnosticDescriptor MissingDirection { get; } = new DiagnosticDescriptor("LSP1000", "Missing Direction", - "No direction defined for Language Server Protocol Handler", "JsonRPC", DiagnosticSeverity.Warning, true); + public static DiagnosticDescriptor MissingDirection { get; } = new DiagnosticDescriptor( + "LSP1000", "Missing Direction", + "No direction defined for Language Server Protocol Handler", "JsonRPC", DiagnosticSeverity.Warning, true + ); - public static DiagnosticDescriptor NoHandlerRegistryProvided { get; } = new DiagnosticDescriptor("JRPC1000", "No Handler Registry Provided", - "No Handler Registry Provided for handler {0}.", "JsonRPC", DiagnosticSeverity.Warning, true); + public static DiagnosticDescriptor NoHandlerRegistryProvided { get; } = new DiagnosticDescriptor( + "JRPC1000", "No Handler Registry Provided", + "No Handler Registry Provided for handler {0}.", "JsonRPC", DiagnosticSeverity.Warning, true + ); - public static DiagnosticDescriptor NoResponseRouterProvided { get; } = new DiagnosticDescriptor("JRPC1001", "No Response Router Provided", - "No Response Router Provided for handler {0}, defaulting to {1}.", "JsonRPC", DiagnosticSeverity.Warning, true); + public static DiagnosticDescriptor NoResponseRouterProvided { get; } = new DiagnosticDescriptor( + "JRPC1001", "No Response Router Provided", + "No Response Router Provided for handler {0}, defaulting to {1}.", "JsonRPC", DiagnosticSeverity.Warning, true + ); } } diff --git a/src/JsonRpc.Generators/Helpers.cs b/src/JsonRpc.Generators/Helpers.cs index 35f43eeec..0574e369a 100644 --- a/src/JsonRpc.Generators/Helpers.cs +++ b/src/JsonRpc.Generators/Helpers.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; -using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -11,23 +10,17 @@ namespace OmniSharp.Extensions.JsonRpc.Generators { - static class Helpers + internal static class Helpers { - public static bool IsNotification(INamedTypeSymbol symbol) - { - return symbol.AllInterfaces.Any(z => z.Name == "IJsonRpcNotificationHandler"); - } + public static bool IsNotification(INamedTypeSymbol symbol) => symbol.AllInterfaces.Any(z => z.Name == "IJsonRpcNotificationHandler"); - public static bool IsRequest(INamedTypeSymbol symbol) - { - return symbol.AllInterfaces.Any(z => z.Name == "IJsonRpcRequestHandler"); - } + public static bool IsRequest(INamedTypeSymbol symbol) => symbol.AllInterfaces.Any(z => z.Name == "IJsonRpcRequestHandler"); public static ExpressionSyntax GetMethodName(InterfaceDeclarationSyntax interfaceSyntax) { var methodAttribute = interfaceSyntax.AttributeLists - .SelectMany(z => z.Attributes) - .First(z => z.Name.ToString() == "MethodAttribute" || z.Name.ToString() == "Method"); + .SelectMany(z => z.Attributes) + .First(z => z.Name.ToString() == "MethodAttribute" || z.Name.ToString() == "Method"); return methodAttribute.ArgumentList.Arguments[0].Expression; } @@ -40,10 +33,12 @@ public static INamedTypeSymbol GetRequestType(INamedTypeSymbol symbol) { return typeParameterSymbol.ConstraintTypes.OfType().FirstOrDefault(); } + if (arg is INamedTypeSymbol namedTypeSymbol) { return namedTypeSymbol; } + throw new NotSupportedException("Request Type is not supported!"); } @@ -56,28 +51,28 @@ public static INamedTypeSymbol GetResponseType(INamedTypeSymbol symbol) public static INamedTypeSymbol? GetCapability(INamedTypeSymbol symbol) { var handlerInterface = symbol.AllInterfaces - .FirstOrDefault(z => z.Name == "ICapability" && z.TypeArguments.Length == 1); + .FirstOrDefault(z => z.Name == "ICapability" && z.TypeArguments.Length == 1); return handlerInterface?.TypeArguments[0] as INamedTypeSymbol; } public static INamedTypeSymbol? GetRegistrationOptions(INamedTypeSymbol symbol) { var handlerInterface = symbol.AllInterfaces - .FirstOrDefault(z => z.Name == "IRegistration" && z.TypeArguments.Length == 1); + .FirstOrDefault(z => z.Name == "IRegistration" && z.TypeArguments.Length == 1); return handlerInterface?.TypeArguments[0] as INamedTypeSymbol; } public static INamedTypeSymbol? GetPartialItems(INamedTypeSymbol symbol) { var handlerInterface = symbol.AllInterfaces - .FirstOrDefault(z => z.Name == "IPartialItems" && z.TypeArguments.Length == 1); + .FirstOrDefault(z => z.Name == "IPartialItems" && z.TypeArguments.Length == 1); return handlerInterface?.TypeArguments[0] as INamedTypeSymbol; } public static INamedTypeSymbol? GetPartialItem(INamedTypeSymbol symbol) { var handlerInterface = symbol.AllInterfaces - .FirstOrDefault(z => z.Name == "IPartialItem" && z.TypeArguments.Length == 1); + .FirstOrDefault(z => z.Name == "IPartialItem" && z.TypeArguments.Length == 1); return handlerInterface?.TypeArguments[0] as INamedTypeSymbol; } @@ -90,7 +85,7 @@ public static GenericNameSyntax CreateAction(bool withCancellationToken, params } return GenericName(Identifier("Action")) - .WithTypeArgumentList(TypeArgumentList(SeparatedList(typeArguments))); + .WithTypeArgumentList(TypeArgumentList(SeparatedList(typeArguments))); } public static NameSyntax ResolveTypeName(ITypeSymbol symbol) @@ -132,18 +127,26 @@ public static GenericNameSyntax CreateAsyncFunc(ITypeSymbol? responseType, bool } else { - typeArguments.Add(GenericName(Identifier("Task"), TypeArgumentList(SeparatedList(new TypeSyntax[] { - ResolveTypeName(responseType) - })))); + typeArguments.Add( + GenericName( + Identifier("Task"), TypeArgumentList( + SeparatedList( + new TypeSyntax[] { + ResolveTypeName(responseType) + } + ) + ) + ) + ); } return GenericName(Identifier("Func")) - .WithTypeArgumentList(TypeArgumentList(SeparatedList(typeArguments))); + .WithTypeArgumentList(TypeArgumentList(SeparatedList(typeArguments))); } public static GenericNameSyntax CreateDerivedAsyncFunc(ITypeSymbol? responseType, bool withCancellationToken) { - var typeArguments = new List() { + var typeArguments = new List { IdentifierName("T") }; if (withCancellationToken) @@ -157,20 +160,28 @@ public static GenericNameSyntax CreateDerivedAsyncFunc(ITypeSymbol? responseType } else { - typeArguments.Add(GenericName(Identifier("Task"), TypeArgumentList(SeparatedList(new TypeSyntax[] { - ResolveTypeName(responseType) - })))); + typeArguments.Add( + GenericName( + Identifier("Task"), TypeArgumentList( + SeparatedList( + new TypeSyntax[] { + ResolveTypeName(responseType) + } + ) + ) + ) + ); } return GenericName(Identifier("Func")) - .WithTypeArgumentList(TypeArgumentList(SeparatedList(typeArguments))); + .WithTypeArgumentList(TypeArgumentList(SeparatedList(typeArguments))); } public static GenericNameSyntax CreatePartialAction(ITypeSymbol requestType, NameSyntax partialType, bool withCancellationToken, params ITypeSymbol[] types) { - var typeArguments = new List() { + var typeArguments = new List { ResolveTypeName(requestType), - GenericName("IObserver").WithTypeArgumentList(TypeArgumentList(SeparatedList(new TypeSyntax[] {partialType}))), + GenericName("IObserver").WithTypeArgumentList(TypeArgumentList(SeparatedList(new TypeSyntax[] { partialType }))), }; typeArguments.AddRange(types.Select(ResolveTypeName)); if (withCancellationToken) @@ -179,54 +190,75 @@ public static GenericNameSyntax CreatePartialAction(ITypeSymbol requestType, Nam } return GenericName(Identifier("Action")) - .WithTypeArgumentList(TypeArgumentList(SeparatedList(typeArguments))); + .WithTypeArgumentList(TypeArgumentList(SeparatedList(typeArguments))); } public static GenericNameSyntax CreatePartialAction(ITypeSymbol requestType, NameSyntax partialType, params ITypeSymbol[] types) => CreatePartialAction(requestType, partialType, true, types); - private static ExpressionStatementSyntax EnsureRegistrationOptionsIsSet(NameSyntax registrationOptionsName, TypeSyntax registrationOptionsType) - { - return ExpressionStatement(AssignmentExpression( - SyntaxKind.CoalesceAssignmentExpression, - registrationOptionsName, - ObjectCreationExpression(registrationOptionsType) - .WithArgumentList(ArgumentList()))); - } + private static ExpressionStatementSyntax EnsureRegistrationOptionsIsSet(NameSyntax registrationOptionsName, TypeSyntax registrationOptionsType) => + ExpressionStatement( + AssignmentExpression( + SyntaxKind.CoalesceAssignmentExpression, + registrationOptionsName, + ObjectCreationExpression(registrationOptionsType) + .WithArgumentList(ArgumentList()) + ) + ); private static InvocationExpressionSyntax AddHandler(params ArgumentSyntax[] arguments) => InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName("registry"), - IdentifierName("AddHandler"))) - .WithArgumentList(ArgumentList(SeparatedList(arguments))); + IdentifierName("AddHandler") + ) + ) + .WithArgumentList(ArgumentList(SeparatedList(arguments))); private static ArgumentListSyntax GetHandlerArgumentList() => - ArgumentList(SeparatedList(new[] { - Argument(IdentifierName("handler")) - })); + ArgumentList( + SeparatedList( + new[] { + Argument(IdentifierName("handler")) + } + ) + ); private static ArgumentListSyntax GetRegistrationHandlerArgumentList(NameSyntax registrationOptionsName) => - ArgumentList(SeparatedList(new[] { - Argument(IdentifierName("handler")), - Argument(registrationOptionsName) - })); + ArgumentList( + SeparatedList( + new[] { + Argument(IdentifierName("handler")), + Argument(registrationOptionsName) + } + ) + ); private static ArgumentListSyntax GetPartialResultArgumentList(NameSyntax responseName) => ArgumentList( SeparatedList( new[] { Argument(IdentifierName("handler")), - Argument(InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("_"), - GenericName(Identifier("GetService")) - .WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList(IdentifierName("IProgressManager")))) - ))), - Argument(SimpleLambdaExpression(Parameter(Identifier("values")), - ObjectCreationExpression(responseName) - .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("values"))))))) - })); + Argument( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("_"), + GenericName(Identifier("GetService")) + .WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList(IdentifierName("IProgressManager")))) + ) + ) + ), + Argument( + SimpleLambdaExpression( + Parameter(Identifier("values")), + ObjectCreationExpression(responseName) + .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("values"))))) + ) + ) + } + ) + ); private static ArgumentListSyntax GetPartialResultRegistrationArgumentList(NameSyntax registrationOptionsName, NameSyntax responseName) => ArgumentList( @@ -234,32 +266,52 @@ private static ArgumentListSyntax GetPartialResultRegistrationArgumentList(NameS new[] { Argument(IdentifierName("handler")), Argument(registrationOptionsName), - Argument(InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("_"), - GenericName(Identifier("GetService")) - .WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList(IdentifierName("IProgressManager")))) - ))), - Argument(SimpleLambdaExpression(Parameter(Identifier("values")), - ObjectCreationExpression(responseName) - .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("values"))))))) - })); + Argument( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("_"), + GenericName(Identifier("GetService")) + .WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList(IdentifierName("IProgressManager")))) + ) + ) + ), + Argument( + SimpleLambdaExpression( + Parameter(Identifier("values")), + ObjectCreationExpression(responseName) + .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("values"))))) + ) + ) + } + ) + ); private static ArgumentListSyntax GetPartialItemsArgumentList(NameSyntax responseName) => ArgumentList( SeparatedList( new[] { Argument(IdentifierName("handler")), - Argument(InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("_"), - GenericName(Identifier("GetService")) - .WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList(IdentifierName("IProgressManager")))) - ))), - Argument(SimpleLambdaExpression(Parameter(Identifier("values")), - ObjectCreationExpression(responseName) - .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("values"))))))) - })); + Argument( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("_"), + GenericName(Identifier("GetService")) + .WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList(IdentifierName("IProgressManager")))) + ) + ) + ), + Argument( + SimpleLambdaExpression( + Parameter(Identifier("values")), + ObjectCreationExpression(responseName) + .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("values"))))) + ) + ) + } + ) + ); private static ArgumentListSyntax GetPartialItemsRegistrationArgumentList(NameSyntax registrationOptionsName, NameSyntax responseName) => ArgumentList( @@ -267,26 +319,34 @@ private static ArgumentListSyntax GetPartialItemsRegistrationArgumentList(NameSy new[] { Argument(IdentifierName("handler")), Argument(registrationOptionsName), - Argument(InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("_"), - GenericName(Identifier("GetService")) - .WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList(IdentifierName("IProgressManager")))) - ))), - Argument(SimpleLambdaExpression(Parameter(Identifier("values")), - ObjectCreationExpression(responseName) - .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("values"))))))) - })); - - private static ObjectCreationExpressionSyntax CreateHandlerArgument(NameSyntax className, string innerClassName, params TypeSyntax[] genericArguments) - { - return ObjectCreationExpression( + Argument( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("_"), + GenericName(Identifier("GetService")) + .WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList(IdentifierName("IProgressManager")))) + ) + ) + ), + Argument( + SimpleLambdaExpression( + Parameter(Identifier("values")), + ObjectCreationExpression(responseName) + .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("values"))))) + ) + ) + } + ) + ); + + private static ObjectCreationExpressionSyntax CreateHandlerArgument(NameSyntax className, string innerClassName, params TypeSyntax[] genericArguments) => + ObjectCreationExpression( QualifiedName( className, GenericName(innerClassName).WithTypeArgumentList(TypeArgumentList(SeparatedList(genericArguments))) ) ); - } public static ArrowExpressionClauseSyntax GetNotificationCapabilityHandlerExpression(ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol capability) { @@ -302,7 +362,8 @@ public static ArrowExpressionClauseSyntax GetNotificationCapabilityHandlerExpres requestName, capabilityName ) - .WithArgumentList(GetHandlerArgumentList())) + .WithArgumentList(GetHandlerArgumentList()) + ) ) ); } @@ -323,14 +384,17 @@ public static BlockSyntax GetNotificationRegistrationHandlerExpression(Expressio requestName, registrationOptionsName ) - .WithArgumentList(GetRegistrationHandlerArgumentList(IdentifierName("registrationOptions")))) + .WithArgumentList(GetRegistrationHandlerArgumentList(IdentifierName("registrationOptions"))) + ) ) ) ); } - public static BlockSyntax GetNotificationRegistrationHandlerExpression(ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol registrationOptions, - ITypeSymbol capability) + public static BlockSyntax GetNotificationRegistrationHandlerExpression( + ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol registrationOptions, + ITypeSymbol capability + ) { var requestName = ResolveTypeName(requestType); var registrationOptionsName = ResolveTypeName(registrationOptions); @@ -348,14 +412,17 @@ public static BlockSyntax GetNotificationRegistrationHandlerExpression(Expressio capabilityName, registrationOptionsName ) - .WithArgumentList(GetRegistrationHandlerArgumentList(IdentifierName("registrationOptions")))) + .WithArgumentList(GetRegistrationHandlerArgumentList(IdentifierName("registrationOptions"))) + ) ) ) ); } - public static ArrowExpressionClauseSyntax GetRequestCapabilityHandlerExpression(ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, - ITypeSymbol capability) + public static ArrowExpressionClauseSyntax GetRequestCapabilityHandlerExpression( + ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, + ITypeSymbol capability + ) { var requestName = ResolveTypeName(requestType); var responseName = ResolveTypeName(responseType); @@ -371,13 +438,16 @@ public static ArrowExpressionClauseSyntax GetRequestCapabilityHandlerExpression( responseName, capabilityName ) - .WithArgumentList(GetHandlerArgumentList())) + .WithArgumentList(GetHandlerArgumentList()) + ) ) ); } - public static BlockSyntax GetRequestRegistrationHandlerExpression(ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, - ITypeSymbol registrationOptions) + public static BlockSyntax GetRequestRegistrationHandlerExpression( + ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, + ITypeSymbol registrationOptions + ) { var requestName = ResolveTypeName(requestType); var responseName = ResolveTypeName(responseType); @@ -395,7 +465,8 @@ public static BlockSyntax GetRequestRegistrationHandlerExpression(ExpressionSynt responseName, registrationOptionsName ) - .WithArgumentList(GetRegistrationHandlerArgumentList(IdentifierName("registrationOptions")))) + .WithArgumentList(GetRegistrationHandlerArgumentList(IdentifierName("registrationOptions"))) + ) ) ) ); @@ -417,15 +488,18 @@ public static BlockSyntax GetVoidRequestRegistrationHandlerExpression(Expression requestName, registrationOptionsName ) - .WithArgumentList(GetRegistrationHandlerArgumentList(IdentifierName("registrationOptions")))) + .WithArgumentList(GetRegistrationHandlerArgumentList(IdentifierName("registrationOptions"))) + ) ) ) ); } - public static BlockSyntax GetRequestRegistrationHandlerExpression(ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, + public static BlockSyntax GetRequestRegistrationHandlerExpression( + ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, ITypeSymbol registrationOptions, - ITypeSymbol capability) + ITypeSymbol capability + ) { var requestName = ResolveTypeName(requestType); var responseName = ResolveTypeName(responseType); @@ -445,14 +519,17 @@ public static BlockSyntax GetRequestRegistrationHandlerExpression(ExpressionSynt capabilityName, registrationOptionsName ) - .WithArgumentList(GetRegistrationHandlerArgumentList(IdentifierName("registrationOptions")))) + .WithArgumentList(GetRegistrationHandlerArgumentList(IdentifierName("registrationOptions"))) + ) ) ) ); } - public static BlockSyntax GetVoidRequestRegistrationHandlerExpression(ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol registrationOptions, - ITypeSymbol capability) + public static BlockSyntax GetVoidRequestRegistrationHandlerExpression( + ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol registrationOptions, + ITypeSymbol capability + ) { var requestName = ResolveTypeName(requestType); var registrationOptionsName = ResolveTypeName(registrationOptions); @@ -470,7 +547,8 @@ public static BlockSyntax GetVoidRequestRegistrationHandlerExpression(Expression capabilityName, registrationOptionsName ) - .WithArgumentList(GetRegistrationHandlerArgumentList(IdentifierName("registrationOptions")))) + .WithArgumentList(GetRegistrationHandlerArgumentList(IdentifierName("registrationOptions"))) + ) ) ) ); @@ -490,7 +568,8 @@ public static ArrowExpressionClauseSyntax GetRequestHandlerExpression(Expression requestName, responseName ) - .WithArgumentList(GetHandlerArgumentList())) + .WithArgumentList(GetHandlerArgumentList()) + ) ) ); } @@ -507,13 +586,16 @@ public static ArrowExpressionClauseSyntax GetRequestHandlerExpression(Expression "Request", requestName ) - .WithArgumentList(GetHandlerArgumentList())) + .WithArgumentList(GetHandlerArgumentList()) + ) ) ); } - public static ArrowExpressionClauseSyntax GetPartialResultCapabilityHandlerExpression(ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, - ITypeSymbol capability) + public static ArrowExpressionClauseSyntax GetPartialResultCapabilityHandlerExpression( + ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, + ITypeSymbol capability + ) { var requestName = ResolveTypeName(requestType); var responseName = ResolveTypeName(responseType); @@ -529,13 +611,16 @@ public static ArrowExpressionClauseSyntax GetPartialResultCapabilityHandlerExpre responseName, capabilityName ) - .WithArgumentList(GetPartialResultArgumentList(responseName))) + .WithArgumentList(GetPartialResultArgumentList(responseName)) + ) ) ); } - public static BlockSyntax GetPartialResultRegistrationHandlerExpression(ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, - ITypeSymbol registrationOptions) + public static BlockSyntax GetPartialResultRegistrationHandlerExpression( + ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, + ITypeSymbol registrationOptions + ) { var requestName = ResolveTypeName(requestType); var responseName = ResolveTypeName(responseType); @@ -553,15 +638,18 @@ public static BlockSyntax GetPartialResultRegistrationHandlerExpression(Expressi responseName, registrationOptionsName ) - .WithArgumentList(GetPartialResultRegistrationArgumentList(IdentifierName("registrationOptions"), responseName))) + .WithArgumentList(GetPartialResultRegistrationArgumentList(IdentifierName("registrationOptions"), responseName)) + ) ) ) ); } - public static BlockSyntax GetPartialResultRegistrationHandlerExpression(ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, + public static BlockSyntax GetPartialResultRegistrationHandlerExpression( + ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, ITypeSymbol registrationOptions, - ITypeSymbol capability) + ITypeSymbol capability + ) { var requestName = ResolveTypeName(requestType); var responseName = ResolveTypeName(responseType); @@ -581,7 +669,8 @@ public static BlockSyntax GetPartialResultRegistrationHandlerExpression(Expressi capabilityName, registrationOptionsName ) - .WithArgumentList(GetPartialResultRegistrationArgumentList(IdentifierName("registrationOptions"), responseName))) + .WithArgumentList(GetPartialResultRegistrationArgumentList(IdentifierName("registrationOptions"), responseName)) + ) ) ) ); @@ -601,13 +690,16 @@ public static ArrowExpressionClauseSyntax GetPartialResultHandlerExpression(Expr requestName, responseName ) - .WithArgumentList(GetPartialResultArgumentList(responseName))) + .WithArgumentList(GetPartialResultArgumentList(responseName)) + ) ) ); } - public static ArrowExpressionClauseSyntax GetPartialResultsCapabilityHandlerExpression(ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, - NameSyntax itemName, ITypeSymbol capability) + public static ArrowExpressionClauseSyntax GetPartialResultsCapabilityHandlerExpression( + ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, + NameSyntax itemName, ITypeSymbol capability + ) { var requestName = ResolveTypeName(requestType); var responseName = ResolveTypeName(responseType); @@ -618,7 +710,8 @@ public static ArrowExpressionClauseSyntax GetPartialResultsCapabilityHandlerExpr Argument( SimpleLambdaExpression( Parameter( - Identifier("_")), + Identifier("_") + ), CreateHandlerArgument( IdentifierName("LanguageProtocolDelegatingHandlers"), "PartialResultsCapability", @@ -627,14 +720,17 @@ public static ArrowExpressionClauseSyntax GetPartialResultsCapabilityHandlerExpr itemName, capabilityName ) - .WithArgumentList(GetPartialItemsArgumentList(responseName))) + .WithArgumentList(GetPartialItemsArgumentList(responseName)) + ) ) ) ); } - public static BlockSyntax GetPartialResultsRegistrationHandlerExpression(ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, - NameSyntax itemName, ITypeSymbol registrationOptions) + public static BlockSyntax GetPartialResultsRegistrationHandlerExpression( + ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, + NameSyntax itemName, ITypeSymbol registrationOptions + ) { var requestName = ResolveTypeName(requestType); var responseName = ResolveTypeName(responseType); @@ -647,7 +743,8 @@ public static BlockSyntax GetPartialResultsRegistrationHandlerExpression(Express Argument( SimpleLambdaExpression( Parameter( - Identifier("_")), + Identifier("_") + ), CreateHandlerArgument( IdentifierName("LanguageProtocolDelegatingHandlers"), "PartialResults", @@ -656,15 +753,19 @@ public static BlockSyntax GetPartialResultsRegistrationHandlerExpression(Express itemName, registrationOptionsName ) - .WithArgumentList(GetPartialItemsRegistrationArgumentList(IdentifierName("registrationOptions"), responseName))) + .WithArgumentList(GetPartialItemsRegistrationArgumentList(IdentifierName("registrationOptions"), responseName)) + ) ) - )) + ) + ) ); } - public static BlockSyntax GetPartialResultsRegistrationHandlerExpression(ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, + public static BlockSyntax GetPartialResultsRegistrationHandlerExpression( + ExpressionSyntax nameExpression, ITypeSymbol requestType, ITypeSymbol responseType, NameSyntax itemName, ITypeSymbol registrationOptions, - ITypeSymbol capability) + ITypeSymbol capability + ) { var requestName = ResolveTypeName(requestType); var responseName = ResolveTypeName(responseType); @@ -678,7 +779,8 @@ public static BlockSyntax GetPartialResultsRegistrationHandlerExpression(Express Argument( SimpleLambdaExpression( Parameter( - Identifier("_")), + Identifier("_") + ), CreateHandlerArgument( IdentifierName("LanguageProtocolDelegatingHandlers"), "PartialResults", @@ -688,14 +790,18 @@ public static BlockSyntax GetPartialResultsRegistrationHandlerExpression(Express capabilityName, registrationOptionsName ) - .WithArgumentList(GetPartialItemsRegistrationArgumentList(IdentifierName("registrationOptions"), responseName))) + .WithArgumentList(GetPartialItemsRegistrationArgumentList(IdentifierName("registrationOptions"), responseName)) + ) ) - )) + ) + ) ); } - public static ArrowExpressionClauseSyntax GetPartialResultsHandlerExpression(ExpressionSyntax nameExpression, ITypeSymbol requestType, NameSyntax itemName, - ITypeSymbol responseType) + public static ArrowExpressionClauseSyntax GetPartialResultsHandlerExpression( + ExpressionSyntax nameExpression, ITypeSymbol requestType, NameSyntax itemName, + ITypeSymbol responseType + ) { var requestName = ResolveTypeName(requestType); var responseName = ResolveTypeName(responseType); @@ -705,7 +811,8 @@ public static ArrowExpressionClauseSyntax GetPartialResultsHandlerExpression(Exp Argument( SimpleLambdaExpression( Parameter( - Identifier("_")), + Identifier("_") + ), CreateHandlerArgument( IdentifierName("LanguageProtocolDelegatingHandlers"), "PartialResults", @@ -713,130 +820,163 @@ public static ArrowExpressionClauseSyntax GetPartialResultsHandlerExpression(Exp responseName, itemName ) - .WithArgumentList(GetPartialItemsArgumentList(responseName))) + .WithArgumentList(GetPartialItemsArgumentList(responseName)) + ) ) ) ); } - public static ArrowExpressionClauseSyntax GetNotificationHandlerExpression(ExpressionSyntax nameExpression) - { - return ArrowExpressionClause( - InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("registry"), - IdentifierName("AddHandler") - )) - .WithArgumentList(ArgumentList(SeparatedList(new SyntaxNodeOrToken[] { - Argument(nameExpression), - Token(SyntaxKind.CommaToken), - Argument(InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("NotificationHandler"), - IdentifierName("For") - )) - .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("handler")))))) - }))) + public static ArrowExpressionClauseSyntax GetNotificationHandlerExpression(ExpressionSyntax nameExpression) => + ArrowExpressionClause( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("registry"), + IdentifierName("AddHandler") + ) + ) + .WithArgumentList( + ArgumentList( + SeparatedList( + new SyntaxNodeOrToken[] { + Argument(nameExpression), + Token(SyntaxKind.CommaToken), + Argument( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("NotificationHandler"), + IdentifierName("For") + ) + ) + .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("handler"))))) + ) + } + ) + ) + ) ); - } - public static ArrowExpressionClauseSyntax GetRequestHandlerExpression(ExpressionSyntax nameExpression) - { - return ArrowExpressionClause( - InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("registry"), - IdentifierName("AddHandler") - )) - .WithArgumentList(ArgumentList(SeparatedList(new SyntaxNodeOrToken[] { - Argument(nameExpression), - Token(SyntaxKind.CommaToken), - Argument(InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("RequestHandler"), - IdentifierName("For") - )) - .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("handler")))))) - }))) + public static ArrowExpressionClauseSyntax GetRequestHandlerExpression(ExpressionSyntax nameExpression) => + ArrowExpressionClause( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("registry"), + IdentifierName("AddHandler") + ) + ) + .WithArgumentList( + ArgumentList( + SeparatedList( + new SyntaxNodeOrToken[] { + Argument(nameExpression), + Token(SyntaxKind.CommaToken), + Argument( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("RequestHandler"), + IdentifierName("For") + ) + ) + .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("handler"))))) + ) + } + ) + ) + ) ); - } - public static ArrowExpressionClauseSyntax GetNotificationInvokeExpression() - { - return ArrowExpressionClause( + public static ArrowExpressionClauseSyntax GetNotificationInvokeExpression() => + ArrowExpressionClause( InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName("mediator"), - IdentifierName("SendNotification"))) - .WithArgumentList( + IdentifierName("SendNotification") + ) + ) + .WithArgumentList( ArgumentList( - SeparatedList(new[] { - Argument(IdentifierName(@"@params")) - })) + SeparatedList( + new[] { + Argument(IdentifierName(@"@params")) + } + ) + ) ) ); - } - public static ArrowExpressionClauseSyntax GetRequestInvokeExpression() - { - return ArrowExpressionClause( + public static ArrowExpressionClauseSyntax GetRequestInvokeExpression() => + ArrowExpressionClause( InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName("mediator"), - IdentifierName("SendRequest"))) - .WithArgumentList( + IdentifierName("SendRequest") + ) + ) + .WithArgumentList( ArgumentList( - SeparatedList(new[] { - Argument(IdentifierName(@"@params")), - Argument(IdentifierName("cancellationToken")) - })) + SeparatedList( + new[] { + Argument(IdentifierName(@"@params")), + Argument(IdentifierName("cancellationToken")) + } + ) + ) ) ); - } - public static ArrowExpressionClauseSyntax GetPartialInvokeExpression(NameSyntax responseType) - { - return ArrowExpressionClause( + public static ArrowExpressionClauseSyntax GetPartialInvokeExpression(NameSyntax responseType) => + ArrowExpressionClause( InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName("mediator"), - IdentifierName("ProgressManager")), - IdentifierName("MonitorUntil"))) - .WithArgumentList( + IdentifierName("ProgressManager") + ), + IdentifierName("MonitorUntil") + ) + ) + .WithArgumentList( ArgumentList( SeparatedList( - new [] { + new[] { Argument( - IdentifierName(@"@params")), + IdentifierName(@"@params") + ), Argument( SimpleLambdaExpression( Parameter(Identifier("value")), ObjectCreationExpression(responseType) - .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("value"))))))), + .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("value"))))) + ) + ), Argument(IdentifierName("cancellationToken")) - })))); - } + } + ) + ) + ) + ); - public static string GetExtensionClassName(INamedTypeSymbol symbol) - { - return SpecialCasedHandlerFullName(symbol).Split('.').Last() + "Extensions"; - ; - } + public static string GetExtensionClassName(INamedTypeSymbol symbol) => SpecialCasedHandlerFullName(symbol).Split('.').Last() + "Extensions"; private static string SpecialCasedHandlerFullName(INamedTypeSymbol symbol) { if (symbol.IsGenericType) { - } - return new Regex(@"(\w+(?:\<\w\>)?)$") - .Replace(symbol.ToDisplayString() ?? string.Empty, - symbol.Name.Substring(1, symbol.Name.IndexOf("Handler", StringComparison.Ordinal) - 1)) + + return new Regex(@"(\w+(?:\<\w\>)?)$") + .Replace( + symbol.ToDisplayString() ?? string.Empty, + symbol.Name.Substring(1, symbol.Name.IndexOf("Handler", StringComparison.Ordinal) - 1) + ) ; } @@ -849,9 +989,9 @@ public static string SpecialCasedHandlerName(INamedTypeSymbol symbol) public static string GetOnMethodName(INamedTypeSymbol symbol, AttributeData attributeData) { var namedMethod = attributeData.NamedArguments - .Where(z => z.Key == "MethodName") - .Select(z => z.Value.Value) - .FirstOrDefault(); + .Where(z => z.Key == "MethodName") + .Select(z => z.Value.Value) + .FirstOrDefault(); if (namedMethod is string value) return value; return "On" + SpecialCasedHandlerName(symbol); } @@ -859,26 +999,26 @@ public static string GetOnMethodName(INamedTypeSymbol symbol, AttributeData attr public static string GetSendMethodName(INamedTypeSymbol symbol, AttributeData attributeData) { var namedMethod = attributeData.NamedArguments - .Where(z => z.Key == "MethodName") - .Select(z => z.Value.Value) - .FirstOrDefault(); + .Where(z => z.Key == "MethodName") + .Select(z => z.Value.Value) + .FirstOrDefault(); if (namedMethod is string value) return value; var name = SpecialCasedHandlerName(symbol); if ( name.StartsWith("Run") - || name.StartsWith("Execute") + || name.StartsWith("Execute") // TODO: Change this next breaking change // || name.StartsWith("Set") // || name.StartsWith("Attach") // || name.StartsWith("Read") - || name.StartsWith("Did") - || name.StartsWith("Log") - || name.StartsWith("Show") - || name.StartsWith("Register") - || name.StartsWith("Prepare") - || name.StartsWith("Publish") - || name.StartsWith("ApplyWorkspaceEdit") - || name.StartsWith("Unregister")) + || name.StartsWith("Did") + || name.StartsWith("Log") + || name.StartsWith("Show") + || name.StartsWith("Register") + || name.StartsWith("Prepare") + || name.StartsWith("Publish") + || name.StartsWith("ApplyWorkspaceEdit") + || name.StartsWith("Unregister")) { return name; } @@ -897,11 +1037,11 @@ private static string HandlerName(INamedTypeSymbol symbol) return name.Substring(name.LastIndexOf('.') + 1); } - private static string HandlerFullName(INamedTypeSymbol symbol) - { - return new Regex(@"(\w+)$") - .Replace(symbol.ToDisplayString() ?? string.Empty, - symbol.Name.Substring(1, symbol.Name.IndexOf("Handler", StringComparison.Ordinal) - 1)); - } + private static string HandlerFullName(INamedTypeSymbol symbol) => + new Regex(@"(\w+)$") + .Replace( + symbol.ToDisplayString() ?? string.Empty, + symbol.Name.Substring(1, symbol.Name.IndexOf("Handler", StringComparison.Ordinal) - 1) + ); } } diff --git a/src/JsonRpc.Testing/AggregateSettler.cs b/src/JsonRpc.Testing/AggregateSettler.cs index 183d35202..d351f5756 100644 --- a/src/JsonRpc.Testing/AggregateSettler.cs +++ b/src/JsonRpc.Testing/AggregateSettler.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Reactive; -using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Threading.Tasks; @@ -12,25 +11,21 @@ public class AggregateSettler : ISettler { private readonly ISettler[] _settlers; - public AggregateSettler(params ISettler[] settlers) - { - _settlers = settlers; - } + public AggregateSettler(params ISettler[] settlers) => _settlers = settlers; - public Task SettleNext() - { - return Settle().Take(1).IgnoreElements().LastOrDefaultAsync().ToTask(); - } + public Task SettleNext() => Settle().Take(1).IgnoreElements().LastOrDefaultAsync().ToTask(); public IObservable Settle() => _settlers - .Select((settler, index) => settler.Settle().Select((_, value) => new { index, value })) - .CombineLatest() - .Scan(0, ((value, result) => { - var maxValue = result.Max(z => z.value); - return result.All(z => z.value == maxValue) ? maxValue : value; - })) - .DistinctUntilChanged() - .Select(z => Unit.Default); + .Select((settler, index) => settler.Settle().Select((_, value) => new { index, value })) + .CombineLatest() + .Scan( + 0, (value, result) => { + var maxValue = result.Max(z => z.value); + return result.All(z => z.value == maxValue) ? maxValue : value; + } + ) + .DistinctUntilChanged() + .Select(z => Unit.Default); } } diff --git a/src/JsonRpc.Testing/JsonRpcIntegrationServerTestBase.cs b/src/JsonRpc.Testing/JsonRpcIntegrationServerTestBase.cs index d0a5f3a49..3de612a9d 100644 --- a/src/JsonRpc.Testing/JsonRpcIntegrationServerTestBase.cs +++ b/src/JsonRpc.Testing/JsonRpcIntegrationServerTestBase.cs @@ -14,7 +14,7 @@ public abstract class JsonRpcIntegrationServerTestBase : IDisposable public JsonRpcIntegrationServerTestBase(JsonRpcTestOptions testOptions) { TestOptions = testOptions; - Disposable = new CompositeDisposable {testOptions.ClientLoggerFactory, testOptions.ServerLoggerFactory}; + Disposable = new CompositeDisposable { testOptions.ClientLoggerFactory, testOptions.ServerLoggerFactory }; _cancellationTokenSource = new CancellationTokenSource(); if (!Debugger.IsAttached) diff --git a/src/JsonRpc.Testing/JsonRpcServerTestBase.cs b/src/JsonRpc.Testing/JsonRpcServerTestBase.cs index f797081fe..4b0e29ea2 100644 --- a/src/JsonRpc.Testing/JsonRpcServerTestBase.cs +++ b/src/JsonRpc.Testing/JsonRpcServerTestBase.cs @@ -19,50 +19,57 @@ public JsonRpcServerTestBase(JsonRpcTestOptions testOptions) : base(testOptions) { } - protected virtual void ConfigureClientInputOutput(PipeReader inMemoryReader, PipeWriter inMemoryWriter, JsonRpcServerOptions options) - { + protected virtual void ConfigureClientInputOutput(PipeReader inMemoryReader, PipeWriter inMemoryWriter, JsonRpcServerOptions options) => options.WithInput(inMemoryReader).WithOutput(inMemoryWriter); - } - protected virtual void ConfigureServerInputOutput(PipeReader inMemoryReader, PipeWriter inMemoryWriter, JsonRpcServerOptions options) - { + protected virtual void ConfigureServerInputOutput(PipeReader inMemoryReader, PipeWriter inMemoryWriter, JsonRpcServerOptions options) => options.WithInput(inMemoryReader).WithOutput(inMemoryWriter); - } protected virtual async Task<(JsonRpcServer client, JsonRpcServer server)> Initialize( Action clientOptionsAction, - Action serverOptionsAction) + Action serverOptionsAction + ) { var clientPipe = new Pipe(TestOptions.DefaultPipeOptions); var serverPipe = new Pipe(TestOptions.DefaultPipeOptions); - var clientTask = JsonRpcServer.From(options => { - options - .WithServices(services => services - .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) - .AddSingleton(ClientEvents as IRequestSettler) - .AddLogging(x => { - x.SetMinimumLevel(LogLevel.Trace); - x.Services.AddSingleton(TestOptions.ClientLoggerFactory); - }) - ); - ConfigureClientInputOutput(serverPipe.Reader, clientPipe.Writer, options); - clientOptionsAction(options); - }, CancellationToken); + var clientTask = JsonRpcServer.From( + options => { + options + .WithServices( + services => services + .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) + .AddSingleton(ClientEvents as IRequestSettler) + .AddLogging( + x => { + x.SetMinimumLevel(LogLevel.Trace); + x.Services.AddSingleton(TestOptions.ClientLoggerFactory); + } + ) + ); + ConfigureClientInputOutput(serverPipe.Reader, clientPipe.Writer, options); + clientOptionsAction(options); + }, CancellationToken + ); - var serverTask = JsonRpcServer.From(options => { - options - .WithServices(services => services - .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) - .AddSingleton(ServerEvents as IRequestSettler) - .AddLogging(x => { - x.SetMinimumLevel(LogLevel.Trace); - x.Services.AddSingleton(TestOptions.ServerLoggerFactory); - }) - ); - ConfigureServerInputOutput(clientPipe.Reader, serverPipe.Writer, options); - serverOptionsAction(options); - }, CancellationToken); + var serverTask = JsonRpcServer.From( + options => { + options + .WithServices( + services => services + .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) + .AddSingleton(ServerEvents as IRequestSettler) + .AddLogging( + x => { + x.SetMinimumLevel(LogLevel.Trace); + x.Services.AddSingleton(TestOptions.ServerLoggerFactory); + } + ) + ); + ConfigureServerInputOutput(clientPipe.Reader, serverPipe.Writer, options); + serverOptionsAction(options); + }, CancellationToken + ); await Task.WhenAll(clientTask, serverTask); _client = clientTask.Result; @@ -71,7 +78,7 @@ protected virtual void ConfigureServerInputOutput(PipeReader inMemoryReader, Pip Disposable.Add(_client); Disposable.Add(_server); - return (_client, _server); + return ( _client, _server ); } } } diff --git a/src/JsonRpc.Testing/JsonRpcTestBase.cs b/src/JsonRpc.Testing/JsonRpcTestBase.cs index 39e5c58f9..dade253ea 100644 --- a/src/JsonRpc.Testing/JsonRpcTestBase.cs +++ b/src/JsonRpc.Testing/JsonRpcTestBase.cs @@ -14,7 +14,7 @@ public abstract class JsonRpcTestBase : IDisposable public JsonRpcTestBase(JsonRpcTestOptions testOptions) { TestOptions = testOptions; - Disposable = new CompositeDisposable {testOptions.ClientLoggerFactory, testOptions.ServerLoggerFactory}; + Disposable = new CompositeDisposable { testOptions.ClientLoggerFactory, testOptions.ServerLoggerFactory }; _cancellationTokenSource = new CancellationTokenSource(); if (!Debugger.IsAttached) diff --git a/src/JsonRpc.Testing/JsonRpcTestOptions.cs b/src/JsonRpc.Testing/JsonRpcTestOptions.cs index ba6a71d81..a9607fd48 100644 --- a/src/JsonRpc.Testing/JsonRpcTestOptions.cs +++ b/src/JsonRpc.Testing/JsonRpcTestOptions.cs @@ -9,12 +9,10 @@ public sealed class JsonRpcTestOptions { public JsonRpcTestOptions() { - - } - public JsonRpcTestOptions(ILoggerFactory loggerFactory) - { - ServerLoggerFactory = ClientLoggerFactory = loggerFactory; } + + public JsonRpcTestOptions(ILoggerFactory loggerFactory) => ServerLoggerFactory = ClientLoggerFactory = loggerFactory; + public JsonRpcTestOptions(ILoggerFactory clientLoggerFactory, ILoggerFactory serverLoggerFactory) { ClientLoggerFactory = clientLoggerFactory; @@ -27,6 +25,5 @@ public JsonRpcTestOptions(ILoggerFactory clientLoggerFactory, ILoggerFactory ser public TimeSpan SettleTimeout { get; internal set; } = TimeSpan.FromMilliseconds(500); public TimeSpan TestTimeout { get; internal set; } = TimeSpan.FromSeconds(30); public PipeOptions DefaultPipeOptions { get; internal set; } = new PipeOptions(); - } } diff --git a/src/JsonRpc.Testing/JsonRpcTestOptionsExtensions.cs b/src/JsonRpc.Testing/JsonRpcTestOptionsExtensions.cs index 516f73157..82fa29733 100644 --- a/src/JsonRpc.Testing/JsonRpcTestOptionsExtensions.cs +++ b/src/JsonRpc.Testing/JsonRpcTestOptionsExtensions.cs @@ -11,26 +11,31 @@ public static JsonRpcTestOptions WithServerLoggerFactory(this JsonRpcTestOptions options.ServerLoggerFactory = serverLoggerFactory; return options; } + public static JsonRpcTestOptions WithClientLoggerFactory(this JsonRpcTestOptions options, ILoggerFactory clientLoggerFactory) { options.ClientLoggerFactory = clientLoggerFactory; return options; } + public static JsonRpcTestOptions WithSettleTimeSpan(this JsonRpcTestOptions options, TimeSpan settleTimeSpan) { options.SettleTimeSpan = settleTimeSpan; return options; } + public static JsonRpcTestOptions WithSettleTimeout(this JsonRpcTestOptions options, TimeSpan timeout) { options.SettleTimeout = timeout; return options; } + public static JsonRpcTestOptions WithTestTimeout(this JsonRpcTestOptions options, TimeSpan testTimeout) { options.TestTimeout = testTimeout; return options; } + public static JsonRpcTestOptions WithDefaultPipeOptions(this JsonRpcTestOptions options, PipeOptions pipeOptions) { options.DefaultPipeOptions = pipeOptions; diff --git a/src/JsonRpc.Testing/SettlePipeline.cs b/src/JsonRpc.Testing/SettlePipeline.cs index 6e0b5a4e1..c26e88fcd 100644 --- a/src/JsonRpc.Testing/SettlePipeline.cs +++ b/src/JsonRpc.Testing/SettlePipeline.cs @@ -9,10 +9,7 @@ public class SettlePipeline : IPipelineBehavior { private readonly IRequestSettler _settler; - public SettlePipeline(IRequestSettler settler) - { - _settler = settler; - } + public SettlePipeline(IRequestSettler settler) => _settler = settler; async Task IPipelineBehavior.Handle(T request, CancellationToken cancellationToken, RequestHandlerDelegate next) { diff --git a/src/JsonRpc.Testing/Settler.cs b/src/JsonRpc.Testing/Settler.cs index 243611306..599316501 100644 --- a/src/JsonRpc.Testing/Settler.cs +++ b/src/JsonRpc.Testing/Settler.cs @@ -1,7 +1,6 @@ using System; using System.Reactive; using System.Reactive.Concurrency; -using System.Reactive.Linq; using System.Reactive.Subjects; using System.Reactive.Threading.Tasks; using System.Threading; @@ -31,52 +30,41 @@ public Settler(TimeSpan waitTime, TimeSpan timeout, CancellationToken cancellati var data = subject; var connectable = data - .StartWith(0) - .Scan(0, (acc, next) => { - acc += next; - return acc; - }) - .DistinctUntilChanged() - .Select(z => { - if (z > 0) - { - return Timer(_timeout, _scheduler) - .Select(z => Unit.Default); - } + .StartWith(0) + .Scan( + 0, (acc, next) => { + acc += next; + return acc; + } + ) + .DistinctUntilChanged() + .Select( + z => { + if (z > 0) + { + return Timer(_timeout, _scheduler) + .Select(z => Unit.Default); + } - return Amb(Timer(waitTime, _scheduler), Timer(_timeout, _scheduler)) - .Select(z => Unit.Default); - }) - .Replay(1, _scheduler); + return Amb(Timer(waitTime, _scheduler), Timer(_timeout, _scheduler)) + .Select(z => Unit.Default); + } + ) + .Replay(1, _scheduler); _connectable = connectable.Connect(); _settle = connectable - .Switch(); + .Switch(); _requester = subject.AsObserver(); } - public Task SettleNext() - { - return _settle.Take(1).IgnoreElements().LastOrDefaultAsync().ToTask(_cancellationToken); - } + public Task SettleNext() => _settle.Take(1).IgnoreElements().LastOrDefaultAsync().ToTask(_cancellationToken); - public IObservable Settle() - { - return _settle.Timeout(_timeout, _scheduler).Catch(_ => _defaultValue); - } + public IObservable Settle() => _settle.Timeout(_timeout, _scheduler).Catch(_ => _defaultValue); - void IRequestSettler.OnStartRequest() - { - _requester.OnNext(1); - } + void IRequestSettler.OnStartRequest() => _requester.OnNext(1); - void IRequestSettler.OnEndRequest() - { - _requester.OnNext(-1); - } + void IRequestSettler.OnEndRequest() => _requester.OnNext(-1); - public void Dispose() - { - _connectable?.Dispose(); - } + public void Dispose() => _connectable?.Dispose(); } } diff --git a/src/JsonRpc/AggregateResponse.cs b/src/JsonRpc/AggregateResponse.cs index 1bff6bb3f..e68f69abf 100644 --- a/src/JsonRpc/AggregateResponse.cs +++ b/src/JsonRpc/AggregateResponse.cs @@ -8,15 +8,8 @@ public class AggregateResponse where T : IEnumerable { public IEnumerable Items { get; } - public AggregateResponse(IEnumerable items) - { - Items = items.ToArray(); - } + public AggregateResponse(IEnumerable items) => Items = items.ToArray(); - public AggregateResponse(IEnumerable items) - { - Items = items.OfType().ToArray(); - } + public AggregateResponse(IEnumerable items) => Items = items.OfType().ToArray(); } - } diff --git a/src/JsonRpc/CompositeHandlersManager.cs b/src/JsonRpc/CompositeHandlersManager.cs index 58c202de6..2504ccd47 100644 --- a/src/JsonRpc/CompositeHandlersManager.cs +++ b/src/JsonRpc/CompositeHandlersManager.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Reactive.Disposables; @@ -8,12 +7,9 @@ namespace OmniSharp.Extensions.JsonRpc public class CompositeHandlersManager : IHandlersManager { private readonly IHandlersManager _parent; - private CompositeDisposable _compositeDisposable = new CompositeDisposable(); + private readonly CompositeDisposable _compositeDisposable = new CompositeDisposable(); - public CompositeHandlersManager(IHandlersManager parent) - { - _parent = parent; - } + public CompositeHandlersManager(IHandlersManager parent) => _parent = parent; public IEnumerable Descriptors => _parent.Descriptors; diff --git a/src/JsonRpc/Connection.cs b/src/JsonRpc/Connection.cs index fe80392d4..d31f49ab3 100644 --- a/src/JsonRpc/Connection.cs +++ b/src/JsonRpc/Connection.cs @@ -2,7 +2,6 @@ using System.IO.Pipelines; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using OmniSharp.Extensions.JsonRpc.Server; namespace OmniSharp.Extensions.JsonRpc { @@ -23,8 +22,8 @@ public Connection( TimeSpan requestTimeout, bool supportContentModified, int concurrency, - CreateResponseExceptionHandler getException = null) - { + CreateResponseExceptionHandler getException = null + ) => _inputHandler = new InputHandler( input, outputHandler, @@ -37,9 +36,8 @@ public Connection( getException, requestTimeout, supportContentModified, - concurrency > 1 ? (int?)concurrency : null + concurrency > 1 ? (int?) concurrency : null ); - } public void Open() { diff --git a/src/JsonRpc/ContentModified.cs b/src/JsonRpc/ContentModified.cs index 240874bd3..9407faca7 100644 --- a/src/JsonRpc/ContentModified.cs +++ b/src/JsonRpc/ContentModified.cs @@ -5,7 +5,12 @@ namespace OmniSharp.Extensions.JsonRpc { public class ContentModified : RpcError { - internal ContentModified(string method) : base(null, method, new ErrorMessage(ErrorCodes.ContentModified, "Content Modified")) { } - internal ContentModified(object id, string method) : base(id, method, new ErrorMessage(ErrorCodes.ContentModified, "Content Modified")) { } + internal ContentModified(string method) : base(null, method, new ErrorMessage(ErrorCodes.ContentModified, "Content Modified")) + { + } + + internal ContentModified(object id, string method) : base(id, method, new ErrorMessage(ErrorCodes.ContentModified, "Content Modified")) + { + } } } diff --git a/src/JsonRpc/CreateResponseExceptionHandler.cs b/src/JsonRpc/CreateResponseExceptionHandler.cs index d5f784b9b..29c56db98 100644 --- a/src/JsonRpc/CreateResponseExceptionHandler.cs +++ b/src/JsonRpc/CreateResponseExceptionHandler.cs @@ -4,4 +4,4 @@ namespace OmniSharp.Extensions.JsonRpc { public delegate Exception CreateResponseExceptionHandler(ServerError serverError, string message); -} \ No newline at end of file +} diff --git a/src/JsonRpc/DelegatingHandlers.cs b/src/JsonRpc/DelegatingHandlers.cs index 871bc4738..1b10b7cea 100644 --- a/src/JsonRpc/DelegatingHandlers.cs +++ b/src/JsonRpc/DelegatingHandlers.cs @@ -17,10 +17,7 @@ public Request(Func> handler) : this((a, ct) => handler(a { } - public Request(Func> handler) - { - _handler = handler; - } + public Request(Func> handler) => _handler = handler; Task IRequestHandler. Handle(TParams request, CancellationToken cancellationToken) => @@ -37,10 +34,7 @@ public Request(Func handler) : this((a, ct) => handler(a)) { } - public Request(Func handler) - { - _handler = handler; - } + public Request(Func handler) => _handler = handler; async Task IRequestHandler. Handle(TParams request, CancellationToken cancellationToken) @@ -55,17 +49,16 @@ public class Notification : IJsonRpcRequestHandler { private readonly Func _handler; - public Notification(Action handler) : this((p, ct) => { - handler(p, ct); - return Task.CompletedTask; - }) + public Notification(Action handler) : this( + (p, ct) => { + handler(p, ct); + return Task.CompletedTask; + } + ) { } - public Notification(Func handler) - { - _handler = handler; - } + public Notification(Func handler) => _handler = handler; async Task IRequestHandler.Handle(TParams request, CancellationToken cancellationToken) { diff --git a/src/JsonRpc/DelegatingJsonNotificationHandler.cs b/src/JsonRpc/DelegatingJsonNotificationHandler.cs index 9ec5f0de6..5072f61da 100644 --- a/src/JsonRpc/DelegatingJsonNotificationHandler.cs +++ b/src/JsonRpc/DelegatingJsonNotificationHandler.cs @@ -10,10 +10,7 @@ public class DelegatingJsonNotificationHandler : IJsonRpcNotificationHandler _handler; - public DelegatingJsonNotificationHandler(Func handler) - { - _handler = handler; - } + public DelegatingJsonNotificationHandler(Func handler) => _handler = handler; public async Task Handle(DelegatingNotification request, CancellationToken cancellationToken) { diff --git a/src/JsonRpc/DelegatingJsonRequestHandler.cs b/src/JsonRpc/DelegatingJsonRequestHandler.cs index 45bd610f9..19c1e4f16 100644 --- a/src/JsonRpc/DelegatingJsonRequestHandler.cs +++ b/src/JsonRpc/DelegatingJsonRequestHandler.cs @@ -9,10 +9,7 @@ public class DelegatingJsonRequestHandler : IJsonRpcRequestHandler> _handler; - public DelegatingJsonRequestHandler(Func> handler) - { - _handler = handler; - } + public DelegatingJsonRequestHandler(Func> handler) => _handler = handler; public async Task Handle(DelegatingRequest request, CancellationToken cancellationToken) { diff --git a/src/JsonRpc/DelegatingNotification.cs b/src/JsonRpc/DelegatingNotification.cs index caef2a4b6..04a7b1cc4 100644 --- a/src/JsonRpc/DelegatingNotification.cs +++ b/src/JsonRpc/DelegatingNotification.cs @@ -5,10 +5,7 @@ namespace OmniSharp.Extensions.JsonRpc { public class DelegatingNotification : IRequest { - public DelegatingNotification(object value) - { - Value = typeof(T) == typeof(Unit) || value is Unit ? new JObject() : JToken.FromObject(value); - } + public DelegatingNotification(object value) => Value = typeof(T) == typeof(Unit) || value is Unit ? new JObject() : JToken.FromObject(value); public JToken Value { get; } } diff --git a/src/JsonRpc/DelegatingNotificationHandler.cs b/src/JsonRpc/DelegatingNotificationHandler.cs index 6062f3024..6ee1cfceb 100644 --- a/src/JsonRpc/DelegatingNotificationHandler.cs +++ b/src/JsonRpc/DelegatingNotificationHandler.cs @@ -10,7 +10,7 @@ public class DelegatingNotificationHandler : IJsonRpcNotificationHandler _handler; - public DelegatingNotificationHandler( ISerializer serializer, Func handler) + public DelegatingNotificationHandler(ISerializer serializer, Func handler) { _serializer = serializer; _handler = handler; diff --git a/src/JsonRpc/DelegatingRequest.cs b/src/JsonRpc/DelegatingRequest.cs index 1341c5827..e56c8dade 100644 --- a/src/JsonRpc/DelegatingRequest.cs +++ b/src/JsonRpc/DelegatingRequest.cs @@ -1,14 +1,11 @@ -using Newtonsoft.Json.Linq; using MediatR; +using Newtonsoft.Json.Linq; namespace OmniSharp.Extensions.JsonRpc { public class DelegatingRequest : IRequest, IRequest { - public DelegatingRequest(object value) - { - Value = typeof(T) == typeof(Unit) || value is Unit ? new JObject() : JToken.FromObject(value); - } + public DelegatingRequest(object value) => Value = typeof(T) == typeof(Unit) || value is Unit ? new JObject() : JToken.FromObject(value); public JToken Value { get; } } diff --git a/src/JsonRpc/EmptyRequest.cs b/src/JsonRpc/EmptyRequest.cs index ac387d701..5f9af7d9c 100644 --- a/src/JsonRpc/EmptyRequest.cs +++ b/src/JsonRpc/EmptyRequest.cs @@ -4,7 +4,10 @@ namespace OmniSharp.Extensions.JsonRpc { public class EmptyRequest : IRequest { - private EmptyRequest() { } + private EmptyRequest() + { + } + public static EmptyRequest Instance { get; } = new EmptyRequest(); } } diff --git a/src/JsonRpc/ErrorResponse.cs b/src/JsonRpc/ErrorResponse.cs index 0d8a6655c..5fc3b0450 100644 --- a/src/JsonRpc/ErrorResponse.cs +++ b/src/JsonRpc/ErrorResponse.cs @@ -21,16 +21,10 @@ 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 ? (object) Response : IsError ? Error : null; - public static implicit operator ErrorResponse(OutgoingResponse outgoingResponse) - { - return new ErrorResponse(outgoingResponse); - } + public static implicit operator ErrorResponse(OutgoingResponse outgoingResponse) => new ErrorResponse(outgoingResponse); - public static implicit operator ErrorResponse(RpcError error) - { - return new ErrorResponse(error); - } + public static implicit operator ErrorResponse(RpcError error) => new ErrorResponse(error); } } diff --git a/src/JsonRpc/Events.cs b/src/JsonRpc/Events.cs index 0321cf7ac..c7c72df6b 100644 --- a/src/JsonRpc/Events.cs +++ b/src/JsonRpc/Events.cs @@ -8,4 +8,4 @@ public static class Events public static EventId UnhandledRequest = new EventId(1337_101); public static EventId UnhandledNotification = new EventId(1337_102); } -} \ No newline at end of file +} diff --git a/src/JsonRpc/ExternalServiceProvider.cs b/src/JsonRpc/ExternalServiceProvider.cs index a59545374..78b788504 100644 --- a/src/JsonRpc/ExternalServiceProvider.cs +++ b/src/JsonRpc/ExternalServiceProvider.cs @@ -2,14 +2,11 @@ namespace OmniSharp.Extensions.JsonRpc { - class ExternalServiceProvider : IExternalServiceProvider + internal class ExternalServiceProvider : IExternalServiceProvider { private readonly IServiceProvider _serviceProvider; - public ExternalServiceProvider(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } + public ExternalServiceProvider(IServiceProvider serviceProvider) => _serviceProvider = serviceProvider; public object GetService(Type serviceType) => _serviceProvider?.GetService(serviceType); } diff --git a/src/JsonRpc/HandlerCollection.cs b/src/JsonRpc/HandlerCollection.cs index 74b62ab8f..06a868563 100644 --- a/src/JsonRpc/HandlerCollection.cs +++ b/src/JsonRpc/HandlerCollection.cs @@ -5,23 +5,19 @@ using System.Linq; using System.Reactive.Disposables; using System.Reflection; -using System.Threading; using MediatR; using Microsoft.Extensions.DependencyInjection; namespace OmniSharp.Extensions.JsonRpc { - class HandlerCollection : IHandlersManager, IEnumerable + internal class HandlerCollection : IHandlersManager, IEnumerable { private readonly IServiceProvider _serviceProvider; private ImmutableArray _descriptors = ImmutableArray.Empty; public IEnumerable Descriptors => _descriptors; - public HandlerCollection(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } + public HandlerCollection(IServiceProvider serviceProvider) => _serviceProvider = serviceProvider; private void Remove(IJsonRpcHandler handler) { @@ -42,13 +38,11 @@ public IDisposable Add(params IJsonRpcHandler[] handlers) if (_descriptors.Any(z => z.Handler == handler)) continue; cd.Add(Add(HandlerTypeDescriptorHelper.GetMethodName(handler.GetType()), handler, null)); } + return cd; } - public IDisposable Add(IJsonRpcHandler handler, JsonRpcHandlerOptions options) - { - return Add(HandlerTypeDescriptorHelper.GetMethodName(handler.GetType()), handler, options); - } + public IDisposable Add(IJsonRpcHandler handler, JsonRpcHandlerOptions options) => Add(HandlerTypeDescriptorHelper.GetMethodName(handler.GetType()), handler, options); public IDisposable Add(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options) { @@ -61,7 +55,7 @@ public IDisposable Add(string method, IJsonRpcHandler handler, JsonRpcHandlerOpt { @params = @interface.GetTypeInfo().GetGenericArguments()[0]; var requestInterface = @params.GetInterfaces() - .FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IRequest<>)); + .FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IRequest<>)); if (requestInterface != null) { response = requestInterface.GetGenericArguments()[0]; @@ -71,9 +65,9 @@ public IDisposable Add(string method, IJsonRpcHandler handler, JsonRpcHandlerOpt var requestProcessType = options?.RequestProcessType ?? type.GetCustomAttributes(true) - .Concat(@interface.GetCustomAttributes(true)) - .OfType() - .FirstOrDefault()?.Type; + .Concat(@interface.GetCustomAttributes(true)) + .OfType() + .FirstOrDefault()?.Type; var descriptor = new HandlerInstance(method, handler, @interface, @params, response, requestProcessType, () => Remove(handler)); ImmutableInterlocked.InterlockedExchange(ref _descriptors, _descriptors.Add(descriptor)); @@ -84,9 +78,12 @@ public IDisposable Add(string method, IJsonRpcHandler handler, JsonRpcHandlerOpt public IDisposable Add(string method, JsonRpcHandlerFactory factory, JsonRpcHandlerOptions options) => Add(method, factory(_serviceProvider), options); - public IDisposable Add(Type handlerType, JsonRpcHandlerOptions options) => Add(ActivatorUtilities.CreateInstance(_serviceProvider, handlerType) as IJsonRpcHandler, options); + public IDisposable Add(Type handlerType, JsonRpcHandlerOptions options) => + Add(ActivatorUtilities.CreateInstance(_serviceProvider, handlerType) as IJsonRpcHandler, options); - public IDisposable Add(string method, Type handlerType, JsonRpcHandlerOptions options) => Add(method, ActivatorUtilities.CreateInstance(_serviceProvider, handlerType) as IJsonRpcHandler, options); + public IDisposable Add(string method, Type handlerType, JsonRpcHandlerOptions options) => Add( + method, ActivatorUtilities.CreateInstance(_serviceProvider, handlerType) as IJsonRpcHandler, options + ); public IDisposable AddLink(string sourceMethod, string destinationMethod) { @@ -96,24 +93,12 @@ public IDisposable AddLink(string sourceMethod, string destinationMethod) return descriptor; } - public bool ContainsHandler(Type type) - { - return _descriptors.Any(z => type.IsAssignableFrom(z.HandlerType)); - } + public bool ContainsHandler(Type type) => _descriptors.Any(z => type.IsAssignableFrom(z.HandlerType)); - public bool ContainsHandler(TypeInfo type) - { - return _descriptors.Any(z => type.IsAssignableFrom(z.HandlerType)); - } + public bool ContainsHandler(TypeInfo type) => _descriptors.Any(z => type.IsAssignableFrom(z.HandlerType)); - public IEnumerator GetEnumerator() - { - return ((IEnumerable)_descriptors).GetEnumerator(); - } + public IEnumerator GetEnumerator() => ( (IEnumerable) _descriptors ).GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable)_descriptors).GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => ( (IEnumerable) _descriptors ).GetEnumerator(); } } diff --git a/src/JsonRpc/HandlerInstance.cs b/src/JsonRpc/HandlerInstance.cs index 5100768e1..e54ee07ac 100644 --- a/src/JsonRpc/HandlerInstance.cs +++ b/src/JsonRpc/HandlerInstance.cs @@ -10,7 +10,9 @@ internal class HandlerInstance : IHandlerDescriptor, IDisposable { private readonly Action _disposeAction; - public HandlerInstance(string method, IJsonRpcHandler handler, Type handlerInterface, Type @params, Type response, RequestProcessType? requestProcessType, Action disposeAction) + public HandlerInstance( + string method, IJsonRpcHandler handler, Type handlerInterface, Type @params, Type response, RequestProcessType? requestProcessType, Action disposeAction + ) { _disposeAction = disposeAction; Handler = handler; @@ -19,9 +21,10 @@ public HandlerInstance(string method, IJsonRpcHandler handler, Type handlerInter HandlerType = handlerInterface; Params = @params; Response = response; - HasReturnType = HandlerType.GetInterfaces().Any(@interface => - @interface.IsGenericType && - typeof(IRequestHandler<,>).IsAssignableFrom(@interface.GetGenericTypeDefinition()) + HasReturnType = HandlerType.GetInterfaces().Any( + @interface => + @interface.IsGenericType && + typeof(IRequestHandler<,>).IsAssignableFrom(@interface.GetGenericTypeDefinition()) ); IsDelegatingHandler = @params?.IsGenericType == true && @@ -31,8 +34,11 @@ public HandlerInstance(string method, IJsonRpcHandler handler, Type handlerInter ); IsNotification = typeof(IJsonRpcNotificationHandler).IsAssignableFrom(handlerInterface) || handlerInterface - .GetInterfaces().Any(z => - z.IsGenericType && typeof(IJsonRpcNotificationHandler<>).IsAssignableFrom(z.GetGenericTypeDefinition())); + .GetInterfaces().Any( + z => + z.IsGenericType && typeof(IJsonRpcNotificationHandler<>) + .IsAssignableFrom(z.GetGenericTypeDefinition()) + ); IsRequest = !IsNotification; RequestProcessType = requestProcessType; } @@ -49,9 +55,6 @@ public HandlerInstance(string method, IJsonRpcHandler handler, Type handlerInter public bool IsDelegatingHandler { get; } public RequestProcessType? RequestProcessType { get; } - public void Dispose() - { - _disposeAction(); - } + public void Dispose() => _disposeAction(); } -} \ No newline at end of file +} diff --git a/src/JsonRpc/HandlerTypeDescriptor.cs b/src/JsonRpc/HandlerTypeDescriptor.cs index 646def496..62e0c9a57 100644 --- a/src/JsonRpc/HandlerTypeDescriptor.cs +++ b/src/JsonRpc/HandlerTypeDescriptor.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.JsonRpc { [DebuggerDisplay("{" + nameof(Method) + "}")] - class HandlerTypeDescriptor : IHandlerTypeDescriptor + internal class HandlerTypeDescriptor : IHandlerTypeDescriptor { public HandlerTypeDescriptor(Type handlerType) { @@ -18,6 +18,7 @@ public HandlerTypeDescriptor(Type handlerType) { handlerType = handlerType.MakeGenericType(handlerType.GetTypeInfo().GenericTypeParameters[0].GetGenericParameterConstraints()[0]); } + HandlerType = handlerType; InterfaceType = HandlerTypeDescriptorHelper.GetHandlerInterface(handlerType); @@ -36,26 +37,30 @@ public HandlerTypeDescriptor(Type handlerType) HasParamsType = ParamsType != null && ParamsType != typeof(EmptyRequest); IsNotification = typeof(IJsonRpcNotificationHandler).IsAssignableFrom(handlerType) || handlerType - .GetInterfaces().Any(z => - z.IsGenericType && typeof(IJsonRpcNotificationHandler<>).IsAssignableFrom(z.GetGenericTypeDefinition())); + .GetInterfaces().Any( + z => + z.IsGenericType && typeof(IJsonRpcNotificationHandler<>).IsAssignableFrom( + z.GetGenericTypeDefinition() + ) + ); IsRequest = !IsNotification; var requestInterface = ParamsType? - .GetInterfaces() - .FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IRequest<>)); + .GetInterfaces() + .FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IRequest<>)); if (requestInterface != null) ResponseType = requestInterface.GetGenericArguments()[0]; HasResponseType = ResponseType != null && ResponseType != typeof(Unit); var processAttributes = HandlerType - .GetCustomAttributes(true) - .Concat(HandlerType.GetCustomAttributes(true)) - .Concat(InterfaceType.GetInterfaces().SelectMany(x => x.GetCustomAttributes(true))) - .Concat(HandlerType.GetInterfaces().SelectMany(x => x.GetCustomAttributes(true))) - .OfType() - .ToArray(); + .GetCustomAttributes(true) + .Concat(HandlerType.GetCustomAttributes(true)) + .Concat(InterfaceType.GetInterfaces().SelectMany(x => x.GetCustomAttributes(true))) + .Concat(HandlerType.GetInterfaces().SelectMany(x => x.GetCustomAttributes(true))) + .OfType() + .ToArray(); RequestProcessType = processAttributes - .FirstOrDefault()?.Type; + .FirstOrDefault()?.Type; } public string Method { get; } diff --git a/src/JsonRpc/HandlerTypeDescriptorHelper.cs b/src/JsonRpc/HandlerTypeDescriptorHelper.cs index 92329098f..778868c24 100644 --- a/src/JsonRpc/HandlerTypeDescriptorHelper.cs +++ b/src/JsonRpc/HandlerTypeDescriptorHelper.cs @@ -19,41 +19,38 @@ static HandlerTypeDescriptorHelper() try { KnownHandlers = AppDomain.CurrentDomain.GetAssemblies() - .SelectMany(x => { - try - { - return x.GetTypes(); - } - catch - { - return Enumerable.Empty(); - } - }) - .Where(z => z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z)) - .Where(z => MethodAttribute.From(z) != null) - .Where(z => !z.Name.EndsWith("Manager")) // Manager interfaces are generally specializations around the handlers - .Select(GetMethodType) - .Distinct() - .ToLookup(x => MethodAttribute.From(x).Method) - .Select(x => new HandlerTypeDescriptor(x.First()) as IHandlerTypeDescriptor) - .ToImmutableSortedDictionary(x => x.Method, x => x, StringComparer.Ordinal); + .SelectMany( + x => { + try + { + return x.GetTypes(); + } + catch + { + return Enumerable.Empty(); + } + } + ) + .Where(z => z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z)) + .Where(z => MethodAttribute.From(z) != null) + .Where(z => !z.Name.EndsWith("Manager")) // Manager interfaces are generally specializations around the handlers + .Select(GetMethodType) + .Distinct() + .ToLookup(x => MethodAttribute.From(x).Method) + .Select(x => new HandlerTypeDescriptor(x.First()) as IHandlerTypeDescriptor) + .ToImmutableSortedDictionary(x => x.Method, x => x, StringComparer.Ordinal); } catch (Exception e) { - throw new AggregateException($"Failed", e); + throw new AggregateException("Failed", e); } } - public static IHandlerTypeDescriptor GetHandlerTypeDescriptor(string method) - { - return KnownHandlers.TryGetValue(method, out var descriptor) ? descriptor : null; - } + public static IHandlerTypeDescriptor GetHandlerTypeDescriptor(string method) => KnownHandlers.TryGetValue(method, out var descriptor) ? descriptor : null; - public static IHandlerTypeDescriptor GetHandlerTypeDescriptor() - { - return KnownHandlers.Values.FirstOrDefault(x => x.InterfaceType == typeof(T)) ?? - GetHandlerTypeDescriptor(GetMethodName(typeof(T))); - } + public static IHandlerTypeDescriptor GetHandlerTypeDescriptor() => + KnownHandlers.Values.FirstOrDefault(x => x.InterfaceType == typeof(T)) ?? + GetHandlerTypeDescriptor(GetMethodName(typeof(T))); public static IHandlerTypeDescriptor GetHandlerTypeDescriptor(Type type) { @@ -69,15 +66,10 @@ public static IHandlerTypeDescriptor GetHandlerTypeDescriptor(Type type) } public static string GetMethodName() - where T : IJsonRpcHandler - { - return GetMethodName(typeof(T)); - } + where T : IJsonRpcHandler => + GetMethodName(typeof(T)); - public static bool IsMethodName(string name, params Type[] types) - { - return types.Any(z => GetMethodName(z).Equals(name)); - } + public static bool IsMethodName(string name, params Type[] types) => types.Any(z => GetMethodName(z).Equals(name)); public static string GetMethodName(Type type) { @@ -86,8 +78,10 @@ public static string GetMethodName(Type type) // Custom method var attribute = MethodAttribute.From(type); - var handler = KnownHandlers.Values.FirstOrDefault(z => - z.InterfaceType == type || z.HandlerType == type || z.ParamsType == type); + var handler = KnownHandlers.Values.FirstOrDefault( + z => + z.InterfaceType == type || z.HandlerType == type || z.ParamsType == type + ); if (handler != null) { return handler.Method; @@ -113,8 +107,8 @@ internal static Type GetMethodType(Type type) } return type.GetTypeInfo() - .ImplementedInterfaces - .FirstOrDefault(t => MethodAttribute.AllFrom(t).Any()); + .ImplementedInterfaces + .FirstOrDefault(t => MethodAttribute.AllFrom(t).Any()); } private static readonly Type[] HandlerTypes = { @@ -132,6 +126,7 @@ private static bool IsValidInterface(Type type) { return HandlerTypes.Contains(type.GetGenericTypeDefinition()); } + return HandlerTypes.Contains(type); } @@ -141,8 +136,8 @@ public static Type GetHandlerInterface(Type type) { if (IsValidInterface(type)) return type; return type?.GetTypeInfo() - .ImplementedInterfaces - .First(IsValidInterface); + .ImplementedInterfaces + .First(IsValidInterface); } catch (Exception e) { @@ -150,13 +145,11 @@ public static Type GetHandlerInterface(Type type) } } - public static Type UnwrapGenericType(Type genericType, Type type) - { - return type?.GetTypeInfo() - .ImplementedInterfaces - .FirstOrDefault(x => x.GetTypeInfo().IsGenericType && x.GetTypeInfo().GetGenericTypeDefinition() == genericType) + public static Type UnwrapGenericType(Type genericType, Type type) => + type?.GetTypeInfo() + .ImplementedInterfaces + .FirstOrDefault(x => x.GetTypeInfo().IsGenericType && x.GetTypeInfo().GetGenericTypeDefinition() == genericType) ?.GetTypeInfo() ?.GetGenericArguments()[0]; - } } } diff --git a/src/JsonRpc/IExternalServiceProvider.cs b/src/JsonRpc/IExternalServiceProvider.cs index 68893958f..1aa8b85f9 100644 --- a/src/JsonRpc/IExternalServiceProvider.cs +++ b/src/JsonRpc/IExternalServiceProvider.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.JsonRpc { - public interface IExternalServiceProvider : IServiceProvider { } -} \ No newline at end of file + public interface IExternalServiceProvider : IServiceProvider + { + } +} diff --git a/src/JsonRpc/IHandlerTypeDescriptor.cs b/src/JsonRpc/IHandlerTypeDescriptor.cs index b3fb12181..b20e46848 100644 --- a/src/JsonRpc/IHandlerTypeDescriptor.cs +++ b/src/JsonRpc/IHandlerTypeDescriptor.cs @@ -24,6 +24,5 @@ public interface IHandlerTypeDescriptor /// public interface IEventingHandler { - } } diff --git a/src/JsonRpc/IJsonRpcHandler.cs b/src/JsonRpc/IJsonRpcHandler.cs index a1bca668f..de25fa54f 100644 --- a/src/JsonRpc/IJsonRpcHandler.cs +++ b/src/JsonRpc/IJsonRpcHandler.cs @@ -1,9 +1,9 @@ -using System; - -namespace OmniSharp.Extensions.JsonRpc +namespace OmniSharp.Extensions.JsonRpc { /// /// A simple marker interface to use for storing handlings (which will be cast out later) /// - public interface IJsonRpcHandler { } + public interface IJsonRpcHandler + { + } } diff --git a/src/JsonRpc/IJsonRpcHandlerCollection.cs b/src/JsonRpc/IJsonRpcHandlerCollection.cs index fd9ff6aab..ad163a50c 100644 --- a/src/JsonRpc/IJsonRpcHandlerCollection.cs +++ b/src/JsonRpc/IJsonRpcHandlerCollection.cs @@ -6,4 +6,4 @@ public interface IJsonRpcHandlerCollection : IEnumerable { public IDisposable Register(Action registryAction); } -} \ No newline at end of file +} diff --git a/src/JsonRpc/IJsonRpcHandlerRegistry.cs b/src/JsonRpc/IJsonRpcHandlerRegistry.cs index a6f1beb1d..5bc8b7b00 100644 --- a/src/JsonRpc/IJsonRpcHandlerRegistry.cs +++ b/src/JsonRpc/IJsonRpcHandlerRegistry.cs @@ -1,10 +1,6 @@ using System; -using System.Collections.Generic; -using System.Reflection; using System.Threading; using System.Threading.Tasks; -using MediatR; -using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json.Linq; namespace OmniSharp.Extensions.JsonRpc @@ -13,7 +9,11 @@ public class JsonRpcHandlerOptions { public RequestProcessType RequestProcessType { get; set; } } - public interface IJsonRpcHandlerRegistry {} + + public interface IJsonRpcHandlerRegistry + { + } + public interface IJsonRpcHandlerRegistry : IJsonRpcHandlerRegistry where T : IJsonRpcHandlerRegistry { T AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options = null); diff --git a/src/JsonRpc/IJsonRpcNotificationHandler.cs b/src/JsonRpc/IJsonRpcNotificationHandler.cs index 3bd9e4027..b8e714ebf 100644 --- a/src/JsonRpc/IJsonRpcNotificationHandler.cs +++ b/src/JsonRpc/IJsonRpcNotificationHandler.cs @@ -2,9 +2,12 @@ namespace OmniSharp.Extensions.JsonRpc { - public interface IJsonRpcNotificationHandler : IRequestHandler, IJsonRpcHandler { } + public interface IJsonRpcNotificationHandler : IRequestHandler, IJsonRpcHandler + { + } public interface IJsonRpcNotificationHandler : IRequestHandler, IJsonRpcHandler where TNotification : IRequest - { } + { + } } diff --git a/src/JsonRpc/IJsonRpcRequestHandler.cs b/src/JsonRpc/IJsonRpcRequestHandler.cs index be76455a2..fbb5eb751 100644 --- a/src/JsonRpc/IJsonRpcRequestHandler.cs +++ b/src/JsonRpc/IJsonRpcRequestHandler.cs @@ -3,27 +3,29 @@ namespace OmniSharp.Extensions.JsonRpc { /// - /// + /// /// Client --> --> - /// | + /// | /// Server <-- <-- - /// + /// /// /// /// public interface IJsonRpcRequestHandler : IRequestHandler, IJsonRpcHandler where TRequest : IRequest - { } + { + } /// - /// + /// /// Client --> --> - /// | + /// | /// Server <-- <-- - /// + /// /// /// public interface IJsonRpcRequestHandler : IRequestHandler, IJsonRpcHandler where TRequest : IRequest - { } + { + } } diff --git a/src/JsonRpc/IJsonRpcServer.cs b/src/JsonRpc/IJsonRpcServer.cs index dcd4a82f9..1f0661600 100644 --- a/src/JsonRpc/IJsonRpcServer.cs +++ b/src/JsonRpc/IJsonRpcServer.cs @@ -4,6 +4,5 @@ namespace OmniSharp.Extensions.JsonRpc { public interface IJsonRpcServer : IResponseRouter, IJsonRpcHandlerInstance, IDisposable { - } } diff --git a/src/JsonRpc/IJsonRpcServerOptions.cs b/src/JsonRpc/IJsonRpcServerOptions.cs index 8dbdb2e36..ccc9e9900 100644 --- a/src/JsonRpc/IJsonRpcServerOptions.cs +++ b/src/JsonRpc/IJsonRpcServerOptions.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.IO.Pipelines; using System.Reflection; -using Microsoft.Extensions.DependencyInjection; -using OmniSharp.Extensions.JsonRpc.Serialization; namespace OmniSharp.Extensions.JsonRpc { diff --git a/src/JsonRpc/IJsonRpcServerRegistry.cs b/src/JsonRpc/IJsonRpcServerRegistry.cs index e5b8f64ad..8b16f7e35 100644 --- a/src/JsonRpc/IJsonRpcServerRegistry.cs +++ b/src/JsonRpc/IJsonRpcServerRegistry.cs @@ -3,4 +3,4 @@ public interface IJsonRpcServerRegistry : IJsonRpcHandlerRegistry { } -} \ No newline at end of file +} diff --git a/src/JsonRpc/IOutputHandler.cs b/src/JsonRpc/IOutputHandler.cs index 40906c18e..81fde6bf8 100644 --- a/src/JsonRpc/IOutputHandler.cs +++ b/src/JsonRpc/IOutputHandler.cs @@ -7,6 +7,5 @@ public interface IOutputHandler : IDisposable { void Send(object value); Task StopAsync(); - } } diff --git a/src/JsonRpc/IRequestRouter.cs b/src/JsonRpc/IRequestRouter.cs index 1c7d710e5..b5830bd7a 100644 --- a/src/JsonRpc/IRequestRouter.cs +++ b/src/JsonRpc/IRequestRouter.cs @@ -1,4 +1,3 @@ -using System; using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc.Server; diff --git a/src/JsonRpc/IResponseHandler.cs b/src/JsonRpc/IResponseHandler.cs index 8a7f91f70..cd02f2875 100644 --- a/src/JsonRpc/IResponseHandler.cs +++ b/src/JsonRpc/IResponseHandler.cs @@ -3,15 +3,15 @@ namespace OmniSharp.Extensions.JsonRpc { /// - /// + /// /// Server --> --> - /// | + /// | /// Client <-- <-- - /// + /// /// /// public interface IResponseHandler : IJsonRpcHandler { Task Handle(TResponse request); } -} \ No newline at end of file +} diff --git a/src/JsonRpc/InputHandler.cs b/src/JsonRpc/InputHandler.cs index 24f7ee1ae..f9a3f7c16 100644 --- a/src/JsonRpc/InputHandler.cs +++ b/src/JsonRpc/InputHandler.cs @@ -1,7 +1,6 @@ using System; using System.Buffers; using System.Collections.Concurrent; -using System.Collections.Generic; using System.IO; using System.IO.Pipelines; using System.Linq; @@ -14,11 +13,10 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -using Newtonsoft.Json.Linq; using Microsoft.Extensions.Logging; using Nerdbank.Streams; using Newtonsoft.Json; -using OmniSharp.Extensions.JsonRpc.Client; +using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.JsonRpc.Server.Messages; using Notification = OmniSharp.Extensions.JsonRpc.Server.Notification; @@ -28,10 +26,10 @@ namespace OmniSharp.Extensions.JsonRpc public class InputHandler : IInputHandler, IDisposable { public static readonly byte[] HeadersFinished = - new byte[] {(byte) '\r', (byte) '\n', (byte) '\r', (byte) '\n'}.ToArray(); + new[] { (byte) '\r', (byte) '\n', (byte) '\r', (byte) '\n' }.ToArray(); public const int HeadersFinishedLength = 4; - public static readonly char[] HeaderKeys = {'\r', '\n', ':'}; + public static readonly char[] HeaderKeys = { '\r', '\n', ':' }; public const short MinBuffer = 21; // Minimum size of the buffer "Content-Length: X\r\n\r\n" public static readonly byte[] ContentLength = "Content-Length".Select(x => (byte) x).ToArray(); public static readonly int ContentLengthLength = 14; @@ -55,8 +53,8 @@ public class InputHandler : IInputHandler, IDisposable private readonly CompositeDisposable _disposable; private readonly AsyncSubject _inputActive; - private readonly ConcurrentDictionary descriptor)> _requests = - new ConcurrentDictionary descriptor)>(); + private readonly ConcurrentDictionary descriptor)> _requests = + new ConcurrentDictionary descriptor)>(); private readonly Subject> _inputQueue; @@ -114,12 +112,13 @@ public void Start() { _disposable.Add( Observable.FromAsync(() => ProcessInputStream(_stopProcessing.Token)) - .Do(_ => { }, e => _logger.LogCritical(e, "unhandled exception")) - .Subscribe(_inputActive)); + .Do(_ => { }, e => _logger.LogCritical(e, "unhandled exception")) + .Subscribe(_inputActive) + ); _disposable.Add( _inputQueue - .Concat() - .Subscribe() + .Concat() + .Subscribe() ); } @@ -180,7 +179,7 @@ private bool TryParseHeaders(ref ReadOnlySequence buffer, out ReadOnlySequ return false; } - static bool IsEqual(in Span headers, in byte[] bytes) + private static bool IsEqual(in Span headers, in byte[] bytes) { var isEqual = true; var len = bytes.Length; @@ -194,8 +193,10 @@ static bool IsEqual(in Span headers, in byte[] bytes) return isEqual; } - private bool TryParseBodyString(in long length, ref ReadOnlySequence buffer, - out ReadOnlySequence line) + private bool TryParseBodyString( + in long length, ref ReadOnlySequence buffer, + out ReadOnlySequence line + ) { if (buffer.Length < length) { @@ -209,7 +210,7 @@ private bool TryParseBodyString(in long length, ref ReadOnlySequence buffe return true; } - bool TryParseContentLength(ref ReadOnlySequence buffer, out long length) + private bool TryParseContentLength(ref ReadOnlySequence buffer, out long length) { do { @@ -228,7 +229,7 @@ bool TryParseContentLength(ref ReadOnlySequence buffer, out long length) var position = buffer.GetPosition(1, colon.Value); var offset = 1; - while (buffer.TryGet(ref position, out var memory, true) && !memory.Span.IsEmpty) + while (buffer.TryGet(ref position, out var memory) && !memory.Span.IsEmpty) { foreach (var t in memory.Span) { @@ -267,10 +268,8 @@ bool TryParseContentLength(ref ReadOnlySequence buffer, out long length) _logger.LogError("Unable to get length from content length header..."); return false; } - else - { - buffer = buffer.Slice(buffer.GetPosition(1, buffer.PositionOf((byte) '\n') ?? buffer.End)); - } + + buffer = buffer.Slice(buffer.GetPosition(1, buffer.PositionOf((byte) '\n') ?? buffer.End)); } while (true); } @@ -386,21 +385,25 @@ private void HandleRequest(in ReadOnlySequence request) continue; } - _inputQueue.OnNext(Observable.Create(observer => { - if (response is ServerResponse serverResponse) - { - // _logger.LogDebug("Setting successful Response for {ResponseId}", response.Id); - tcs.TrySetResult(serverResponse.Result); - } - else if (response is ServerError serverError) - { - // _logger.LogDebug("Setting error for {ResponseId}", response.Id); - tcs.TrySetException(DefaultErrorParser(method, serverError, _getException)); - } + _inputQueue.OnNext( + Observable.Create( + observer => { + if (response is ServerResponse serverResponse) + { + // _logger.LogDebug("Setting successful Response for {ResponseId}", response.Id); + tcs.TrySetResult(serverResponse.Result); + } + else if (response is ServerError serverError) + { + // _logger.LogDebug("Setting error for {ResponseId}", response.Id); + tcs.TrySetException(DefaultErrorParser(method, serverError, _getException)); + } - observer.OnCompleted(); - return Disposable.Empty; - })); + observer.OnCompleted(); + return Disposable.Empty; + } + ) + ); } return; @@ -470,70 +473,103 @@ private SchedulerDelegate RouteRequest(IRequestDescriptor de { // start request, create cts, etc var cts = new CancellationTokenSource(); - _requests.TryAdd(request.Id, (cts, descriptors)); - - return (contentModifiedToken, scheduler) => Observable.Create(observer => { - // ITS A RACE! - var sub = Observable.Amb( - contentModifiedToken.Select(_ => { - _logger.LogTrace("Request {Id} was abandoned due to content be modified", request.Id); - return new ErrorResponse(new ContentModified(request.Id, request.Method)); - }), - Observable.Timer(_requestTimeout, scheduler).Select(z => new ErrorResponse(new RequestCancelled(request.Id, request.Method))), - Observable.FromAsync(async (ct) => { - using var timer = _logger.TimeDebug("Processing request {Method} {ResponseId}", request.Method, request.Id); - ct.Register(cts.Cancel); - // ObservableToToken(contentModifiedToken).Register(cts.Cancel); - try - { - return await _requestRouter.RouteRequest(descriptors, request, cts.Token); - } - catch (OperationCanceledException) - { - _logger.LogTrace("Request {Id} was cancelled", request.Id); - return new RequestCancelled(request.Id, request.Method); - } - catch (RpcErrorException e) - { - _logger.LogCritical(Events.UnhandledRequest, e, "Failed to handle request {Method} {RequestId}", request.Method, request.Id); - return new RpcError(request.Id, request.Method, new ErrorMessage(e.Code, e.Message, e.Error)); - } - catch (Exception e) - { - _logger.LogCritical(Events.UnhandledRequest, e, "Failed to handle request {Method} {RequestId}", request.Method, request.Id); - return new InternalError(request.Id, request.Method, e.ToString()); - } - }) - ) - .Subscribe(observer); - return new CompositeDisposable() { - sub, - Disposable.Create(() => { - if (_requests.TryRemove(request.Id, out var v)) - { - v.cancellationTokenSource.Dispose(); - } - }) - }; - }) - .Select(response => { - _outputHandler.Send(response.Value); - return Unit.Default; - }); + _requests.TryAdd(request.Id, ( cts, descriptors )); + + return (contentModifiedToken, scheduler) => Observable.Create( + observer => { + // ITS A RACE! + var sub = Observable.Amb( + contentModifiedToken.Select( + _ => { + _logger.LogTrace( + "Request {Id} was abandoned due to content be modified", request.Id + ); + return new ErrorResponse( + new ContentModified(request.Id, request.Method) + ); + } + ), + Observable.Timer(_requestTimeout, scheduler).Select( + z => new ErrorResponse(new RequestCancelled(request.Id, request.Method)) + ), + Observable.FromAsync( + async ct => { + using var timer = _logger.TimeDebug( + "Processing request {Method} {ResponseId}", request.Method, + request.Id + ); + ct.Register(cts.Cancel); + // ObservableToToken(contentModifiedToken).Register(cts.Cancel); + try + { + return await _requestRouter.RouteRequest( + descriptors, request, cts.Token + ); + } + catch (OperationCanceledException) + { + _logger.LogTrace("Request {Id} was cancelled", request.Id); + return new RequestCancelled(request.Id, request.Method); + } + catch (RpcErrorException e) + { + _logger.LogCritical( + Events.UnhandledRequest, e, + "Failed to handle request {Method} {RequestId}", request.Method, + request.Id + ); + return new RpcError( + request.Id, request.Method, + new ErrorMessage(e.Code, e.Message, e.Error) + ); + } + catch (Exception e) + { + _logger.LogCritical( + Events.UnhandledRequest, e, + "Failed to handle request {Method} {RequestId}", request.Method, + request.Id + ); + return new InternalError(request.Id, request.Method, e.ToString()); + } + } + ) + ) + .Subscribe(observer); + return new CompositeDisposable { + sub, + Disposable.Create( + () => { + if (_requests.TryRemove(request.Id, out var v)) + { + v.cancellationTokenSource.Dispose(); + } + } + ) + }; + } + ) + .Select( + response => { + _outputHandler.Send(response.Value); + return Unit.Default; + } + ); } - private SchedulerDelegate RouteNotification(IRequestDescriptor descriptors, Notification notification) - { - return (contentModifiedToken, scheduler) => - // ITS A RACE! - Observable.Amb( - contentModifiedToken - .Do(_ => { _logger.LogTrace("Notification was abandoned due to content be modified"); }), - Observable.Timer(_requestTimeout, scheduler) - .Select(z => Unit.Default) - .Do(z => _logger.LogTrace("Notification was cancelled due to timeout") - ), - Observable.FromAsync(async (ct) => { + private SchedulerDelegate RouteNotification(IRequestDescriptor descriptors, Notification notification) => + (contentModifiedToken, scheduler) => + // ITS A RACE! + Observable.Amb( + contentModifiedToken + .Do(_ => { _logger.LogTrace("Notification was abandoned due to content be modified"); }), + Observable.Timer(_requestTimeout, scheduler) + .Select(z => Unit.Default) + .Do( + z => _logger.LogTrace("Notification was cancelled due to timeout") + ), + Observable.FromAsync( + async ct => { using var timer = _logger.TimeDebug("Processing notification {Method}", notification.Method); try { @@ -547,30 +583,27 @@ private SchedulerDelegate RouteNotification(IRequestDescriptor + error.Error?.Code switch { ErrorCodes.ServerNotInitialized => new ServerNotInitializedException(error.Id), - ErrorCodes.MethodNotSupported => new MethodNotSupportedException(error.Id, method ?? "UNKNOWN"), - ErrorCodes.InvalidRequest => new InvalidRequestException(error.Id), - ErrorCodes.InvalidParameters => new InvalidParametersException(error.Id), - ErrorCodes.InternalError => new InternalErrorException(error.Id, error.Error.Data?.ToString() ?? string.Empty), - ErrorCodes.ParseError => new ParseErrorException(error.Id), - ErrorCodes.RequestCancelled => new RequestCancelledException(error.Id), - ErrorCodes.ContentModified => new ContentModifiedException(error.Id), - ErrorCodes.UnknownErrorCode => new UnknownErrorException(error.Id), - ErrorCodes.Exception => new JsonRpcException(ErrorCodes.Exception, error.Id, error.Error.Message ?? string.Empty, error.Error.Data.ToString()), + ErrorCodes.MethodNotSupported => new MethodNotSupportedException(error.Id, method ?? "UNKNOWN"), + ErrorCodes.InvalidRequest => new InvalidRequestException(error.Id), + ErrorCodes.InvalidParameters => new InvalidParametersException(error.Id), + ErrorCodes.InternalError => new InternalErrorException(error.Id, error.Error.Data?.ToString() ?? string.Empty), + ErrorCodes.ParseError => new ParseErrorException(error.Id), + ErrorCodes.RequestCancelled => new RequestCancelledException(error.Id), + ErrorCodes.ContentModified => new ContentModifiedException(error.Id), + ErrorCodes.UnknownErrorCode => new UnknownErrorException(error.Id), + ErrorCodes.Exception => new JsonRpcException(ErrorCodes.Exception, error.Id, error.Error.Message ?? string.Empty, error.Error.Data.ToString()), _ => customHandler?.Invoke(error, method) ?? new JsonRpcException( error.Error?.Code ?? ErrorCodes.UnknownErrorCode, error.Id, error.Error?.Message ?? string.Empty, error.Error?.Data.ToString() ?? string.Empty ) }; - } } } diff --git a/src/JsonRpc/InputProcessingException.cs b/src/JsonRpc/InputProcessingException.cs index 031681bf4..5368e327f 100644 --- a/src/JsonRpc/InputProcessingException.cs +++ b/src/JsonRpc/InputProcessingException.cs @@ -4,9 +4,10 @@ namespace OmniSharp.Extensions.JsonRpc { public class InputProcessingException : Exception { - public InputProcessingException(string message, Exception innerException) : base($"There was an error processing input the contents of the buffer were '{message}'", innerException) + public InputProcessingException(string message, Exception innerException) : base( + $"There was an error processing input the contents of the buffer were '{message}'", innerException + ) { - } } -} \ No newline at end of file +} diff --git a/src/JsonRpc/InterimJsonRpcServerRegistry.cs b/src/JsonRpc/InterimJsonRpcServerRegistry.cs index 14ad237e3..d988f0ea0 100644 --- a/src/JsonRpc/InterimJsonRpcServerRegistry.cs +++ b/src/JsonRpc/InterimJsonRpcServerRegistry.cs @@ -1,5 +1,4 @@ using System; -using Microsoft.Extensions.DependencyInjection; namespace OmniSharp.Extensions.JsonRpc { @@ -7,10 +6,7 @@ public class InterimJsonRpcServerRegistry : JsonRpcCommonMethodsBase where { private readonly IHandlersManager _handlersManager; - public InterimJsonRpcServerRegistry(IHandlersManager handlersManager) - { - _handlersManager = handlersManager; - } + public InterimJsonRpcServerRegistry(IHandlersManager handlersManager) => _handlersManager = handlersManager; public sealed override T AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options) { @@ -46,15 +42,9 @@ public sealed override T AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptio return (T) (object) this; } - public sealed override T AddHandler(JsonRpcHandlerOptions options) - { - return AddHandler(typeof(THandler), options); - } + public sealed override T AddHandler(JsonRpcHandlerOptions options) => AddHandler(typeof(THandler), options); - public sealed override T AddHandler(string method, JsonRpcHandlerOptions options) - { - return AddHandler(method, typeof(THandler), options); - } + public sealed override T AddHandler(string method, JsonRpcHandlerOptions options) => AddHandler(method, typeof(THandler), options); public sealed override T AddHandler(Type type, JsonRpcHandlerOptions options) { diff --git a/src/JsonRpc/JsonRpcCancelRequestExtensions.cs b/src/JsonRpc/JsonRpcCancelRequestExtensions.cs index 3d542a3df..ea0b94d36 100644 --- a/src/JsonRpc/JsonRpcCancelRequestExtensions.cs +++ b/src/JsonRpc/JsonRpcCancelRequestExtensions.cs @@ -1,24 +1,11 @@ - - - - namespace OmniSharp.Extensions.JsonRpc { public static class JsonRpcCancelRequestExtensions { - public static void CancelRequest(this IResponseRouter mediator, CancelParams @params) - { - mediator.SendNotification(@params); - } + public static void CancelRequest(this IResponseRouter mediator, CancelParams @params) => mediator.SendNotification(@params); - public static void CancelRequest(this IResponseRouter mediator, string id) - { - mediator.SendNotification(new CancelParams() { Id = id }); - } + public static void CancelRequest(this IResponseRouter mediator, string id) => mediator.SendNotification(new CancelParams { Id = id }); - public static void CancelRequest(this IResponseRouter mediator, long id) - { - mediator.SendNotification(new CancelParams() { Id = id }); - } + public static void CancelRequest(this IResponseRouter mediator, long id) => mediator.SendNotification(new CancelParams { Id = id }); } } diff --git a/src/JsonRpc/JsonRpcCommonMethodsBase.cs b/src/JsonRpc/JsonRpcCommonMethodsBase.cs index 3e773754b..80acb9405 100644 --- a/src/JsonRpc/JsonRpcCommonMethodsBase.cs +++ b/src/JsonRpc/JsonRpcCommonMethodsBase.cs @@ -11,121 +11,93 @@ public abstract class JsonRpcCommonMethodsBase : IJsonRpcHandlerRegistry w { #region OnRequest / OnNotification - - 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, (request, ct) => handler(request), options); - } - - public T OnRequest(string method, Func> handler, JsonRpcHandlerOptions options = null) - { - return OnRequest(method, (value, cancellationToken) => handler(value), options); - } - - public T OnRequest(string method, Func> handler, JsonRpcHandlerOptions options = null) - { - return OnRequest(method, (value, cancellationToken) => 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, (value, cancellationToken) => handler(cancellationToken), options); - } - - public T OnRequest(string method, Func handler, JsonRpcHandlerOptions options = null) - { - return OnRequest(method, (value, cancellationToken) => handler(value), 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, (value, cancellationToken) => handler(cancellationToken), options); - } - - public T OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions options = null) - { - return OnJsonNotification(method, (value, cancellationToken) => { - handler(value, cancellationToken); - return Task.CompletedTask; - }, options); - } - - public T OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions options = null) - { - return OnJsonNotification(method, (value, cancellationToken) => { - handler(value); - return Task.CompletedTask; - }, 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, (value, cancellationToken) => handler(value), options); - } - - public T OnNotification(string method, Action handler, JsonRpcHandlerOptions options = null) - { - return OnNotification(method, (value, cancellationToken) => { - handler(value, cancellationToken); - return Task.CompletedTask; - }, options); - } - - public T OnNotification(string method, Action handler, JsonRpcHandlerOptions options = null) - { - return OnNotification(method, (value, cancellationToken) => { - handler(value); - return Task.CompletedTask; - }, 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, (value, cancellationToken) => handler(value), options); - } - - public T OnNotification(string method, Action handler, JsonRpcHandlerOptions options = null) - { - return OnNotification(method, (value, cancellationToken) => { - handler(); - return Task.CompletedTask; - }, options); - } - - public T OnNotification(string method, Func handler, JsonRpcHandlerOptions options = null) - { - return AddHandler(method, _ => new DelegatingNotificationHandler(_.GetRequiredService(), (unit, token) => handler(token)), options); - } - - public T OnNotification(string method, Func handler, JsonRpcHandlerOptions options = null) - { - return OnNotification(method, (cancellationToken) => handler(), options); - } + 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, (request, ct) => handler(request), options); + + public T OnRequest(string method, Func> handler, JsonRpcHandlerOptions options = null) => + OnRequest(method, (value, cancellationToken) => handler(value), options); + + public T OnRequest(string method, Func> handler, JsonRpcHandlerOptions options = null) => + OnRequest(method, (value, cancellationToken) => 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, (value, cancellationToken) => handler(cancellationToken), options); + + public T OnRequest(string method, Func handler, JsonRpcHandlerOptions options = null) => + OnRequest(method, (value, cancellationToken) => handler(value), 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, (value, cancellationToken) => handler(cancellationToken), options); + + public T OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions options = null) => + OnJsonNotification( + method, (value, cancellationToken) => { + handler(value, cancellationToken); + return Task.CompletedTask; + }, options + ); + + public T OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions options = null) => + OnJsonNotification( + method, (value, cancellationToken) => { + handler(value); + return Task.CompletedTask; + }, 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, (value, cancellationToken) => handler(value), options); + + public T OnNotification(string method, Action handler, JsonRpcHandlerOptions options = null) => + OnNotification( + method, (value, cancellationToken) => { + handler(value, cancellationToken); + return Task.CompletedTask; + }, options + ); + + public T OnNotification(string method, Action handler, JsonRpcHandlerOptions options = null) => + OnNotification( + method, (value, cancellationToken) => { + handler(value); + return Task.CompletedTask; + }, 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, (value, cancellationToken) => handler(value), options); + + public T OnNotification(string method, Action handler, JsonRpcHandlerOptions options = null) => + OnNotification( + method, (value, cancellationToken) => { + handler(); + return Task.CompletedTask; + }, options + ); + + public T OnNotification(string method, Func handler, JsonRpcHandlerOptions options = null) => AddHandler( + method, _ => new DelegatingNotificationHandler(_.GetRequiredService(), (unit, token) => handler(token)), options + ); + + public T OnNotification(string method, Func handler, JsonRpcHandlerOptions options = null) => OnNotification(method, cancellationToken => handler(), options); #endregion diff --git a/src/JsonRpc/JsonRpcHandlerCollection.cs b/src/JsonRpc/JsonRpcHandlerCollection.cs index b9af04e62..f1c5fab4d 100644 --- a/src/JsonRpc/JsonRpcHandlerCollection.cs +++ b/src/JsonRpc/JsonRpcHandlerCollection.cs @@ -3,7 +3,7 @@ namespace OmniSharp.Extensions.JsonRpc { - class JsonRpcHandlerCollection : IJsonRpcHandlerCollection + internal class JsonRpcHandlerCollection : IJsonRpcHandlerCollection { private readonly List _descriptions = new List(); public IEnumerator GetEnumerator() => _descriptions.GetEnumerator(); diff --git a/src/JsonRpc/JsonRpcHandlerCollectionExtensions.cs b/src/JsonRpc/JsonRpcHandlerCollectionExtensions.cs index 2240f244e..71f9537cc 100644 --- a/src/JsonRpc/JsonRpcHandlerCollectionExtensions.cs +++ b/src/JsonRpc/JsonRpcHandlerCollectionExtensions.cs @@ -36,6 +36,7 @@ public static void Populate(this IJsonRpcHandlerCollection collection, IServiceP continue; } } + foreach (var link in links) { handlersManager.AddLink(link.Method, link.LinkToMethod); diff --git a/src/JsonRpc/JsonRpcHandlerDescription.cs b/src/JsonRpc/JsonRpcHandlerDescription.cs index 0da2b2c50..7b374deb4 100644 --- a/src/JsonRpc/JsonRpcHandlerDescription.cs +++ b/src/JsonRpc/JsonRpcHandlerDescription.cs @@ -4,47 +4,28 @@ namespace OmniSharp.Extensions.JsonRpc { public abstract class JsonRpcHandlerDescription { - protected JsonRpcHandlerDescription(JsonRpcHandlerOptions options) - { - Options = options; - } + protected JsonRpcHandlerDescription(JsonRpcHandlerOptions options) => Options = options; public JsonRpcHandlerOptions Options { get; } - public static JsonRpcHandlerDescription Infer(Type handlerType, JsonRpcHandlerOptions options = null) - { - return new JsonRpcHandlerTypeDescription(null, handlerType, options); - } - - public static JsonRpcHandlerDescription Named(string method, Type handlerType, JsonRpcHandlerOptions options = null) - { - return new JsonRpcHandlerTypeDescription(method, handlerType, options); - } - - public static JsonRpcHandlerDescription Infer(IJsonRpcHandler handlerInstance, JsonRpcHandlerOptions options = null) - { - return new JsonRpcHandlerInstanceDescription(null, handlerInstance, options); - } - - public static JsonRpcHandlerDescription Named(string method, IJsonRpcHandler handlerInstance, JsonRpcHandlerOptions options = null) - { - return new JsonRpcHandlerInstanceDescription(method, handlerInstance, options); - } - - public static JsonRpcHandlerDescription Infer(JsonRpcHandlerFactory handlerFactory, JsonRpcHandlerOptions options = null) - { - return new JsonRpcHandlerFactoryDescription(null, handlerFactory, options); - } - - public static JsonRpcHandlerDescription Named(string method, JsonRpcHandlerFactory handlerFactory, JsonRpcHandlerOptions options = null) - { - return new JsonRpcHandlerFactoryDescription(method, handlerFactory, options); - } - - public static JsonRpcHandlerDescription Link(string method, string methodToLink) - { - return new JsonRpcHandlerLinkDescription(method, methodToLink); - } + public static JsonRpcHandlerDescription Infer(Type handlerType, JsonRpcHandlerOptions options = null) => new JsonRpcHandlerTypeDescription(null, handlerType, options); + + public static JsonRpcHandlerDescription Named(string method, Type handlerType, JsonRpcHandlerOptions options = null) => + new JsonRpcHandlerTypeDescription(method, handlerType, options); + + public static JsonRpcHandlerDescription Infer(IJsonRpcHandler handlerInstance, JsonRpcHandlerOptions options = null) => + new JsonRpcHandlerInstanceDescription(null, handlerInstance, options); + + public static JsonRpcHandlerDescription Named(string method, IJsonRpcHandler handlerInstance, JsonRpcHandlerOptions options = null) => + new JsonRpcHandlerInstanceDescription(method, handlerInstance, options); + + public static JsonRpcHandlerDescription Infer(JsonRpcHandlerFactory handlerFactory, JsonRpcHandlerOptions options = null) => + new JsonRpcHandlerFactoryDescription(null, handlerFactory, options); + + public static JsonRpcHandlerDescription Named(string method, JsonRpcHandlerFactory handlerFactory, JsonRpcHandlerOptions options = null) => + new JsonRpcHandlerFactoryDescription(method, handlerFactory, options); + + public static JsonRpcHandlerDescription Link(string method, string methodToLink) => new JsonRpcHandlerLinkDescription(method, methodToLink); } -} \ No newline at end of file +} diff --git a/src/JsonRpc/JsonRpcHandlerFactory.cs b/src/JsonRpc/JsonRpcHandlerFactory.cs index 52b91acac..1ba97aa87 100644 --- a/src/JsonRpc/JsonRpcHandlerFactory.cs +++ b/src/JsonRpc/JsonRpcHandlerFactory.cs @@ -3,4 +3,4 @@ namespace OmniSharp.Extensions.JsonRpc { public delegate IJsonRpcHandler JsonRpcHandlerFactory(IServiceProvider serviceProvider); -} \ No newline at end of file +} diff --git a/src/JsonRpc/JsonRpcHandlerFactoryDescription.cs b/src/JsonRpc/JsonRpcHandlerFactoryDescription.cs index 88c7dc848..5b8dbb288 100644 --- a/src/JsonRpc/JsonRpcHandlerFactoryDescription.cs +++ b/src/JsonRpc/JsonRpcHandlerFactoryDescription.cs @@ -2,7 +2,7 @@ { public class JsonRpcHandlerFactoryDescription : JsonRpcHandlerDescription { - public JsonRpcHandlerFactoryDescription(string method, JsonRpcHandlerFactory handlerFactory, JsonRpcHandlerOptions options): base(options) + public JsonRpcHandlerFactoryDescription(string method, JsonRpcHandlerFactory handlerFactory, JsonRpcHandlerOptions options) : base(options) { Method = method; HandlerFactory = handlerFactory; @@ -11,4 +11,4 @@ public JsonRpcHandlerFactoryDescription(string method, JsonRpcHandlerFactory han public string Method { get; } public JsonRpcHandlerFactory HandlerFactory { get; } } -} \ No newline at end of file +} diff --git a/src/JsonRpc/JsonRpcHandlerInstanceDescription.cs b/src/JsonRpc/JsonRpcHandlerInstanceDescription.cs index 777e7ec1d..051401cfa 100644 --- a/src/JsonRpc/JsonRpcHandlerInstanceDescription.cs +++ b/src/JsonRpc/JsonRpcHandlerInstanceDescription.cs @@ -2,7 +2,7 @@ { public class JsonRpcHandlerInstanceDescription : JsonRpcHandlerDescription { - public JsonRpcHandlerInstanceDescription(string method, IJsonRpcHandler handlerInstance, JsonRpcHandlerOptions options): base(options) + public JsonRpcHandlerInstanceDescription(string method, IJsonRpcHandler handlerInstance, JsonRpcHandlerOptions options) : base(options) { Method = method; HandlerInstance = handlerInstance; @@ -11,4 +11,4 @@ public JsonRpcHandlerInstanceDescription(string method, IJsonRpcHandler handlerI public string Method { get; } public IJsonRpcHandler HandlerInstance { get; } } -} \ No newline at end of file +} diff --git a/src/JsonRpc/JsonRpcHandlerLinkDescription.cs b/src/JsonRpc/JsonRpcHandlerLinkDescription.cs index 728a12523..57d473872 100644 --- a/src/JsonRpc/JsonRpcHandlerLinkDescription.cs +++ b/src/JsonRpc/JsonRpcHandlerLinkDescription.cs @@ -11,4 +11,4 @@ public JsonRpcHandlerLinkDescription(string method, string linkToMethod) : base( public string Method { get; } public string LinkToMethod { get; } } -} \ No newline at end of file +} diff --git a/src/JsonRpc/JsonRpcHandlerRegistrationExtensions.cs b/src/JsonRpc/JsonRpcHandlerRegistrationExtensions.cs index e906e246e..a2cefa45f 100644 --- a/src/JsonRpc/JsonRpcHandlerRegistrationExtensions.cs +++ b/src/JsonRpc/JsonRpcHandlerRegistrationExtensions.cs @@ -7,25 +7,25 @@ public static class JsonRpcHandlerRegistrationExtensions { public static IServiceCollection AddJsonRpcHandler(this IServiceCollection services, string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options = null) { - services.AddSingleton(JsonRpcHandlerDescription.Named(method, handler, options)); + services.AddSingleton(JsonRpcHandlerDescription.Named(method, handler, options)); return services; } public static IServiceCollection AddJsonRpcHandler(this IServiceCollection services, string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options = null) { - services.AddSingleton(JsonRpcHandlerDescription.Named(method, handlerFunc, options)); + services.AddSingleton(JsonRpcHandlerDescription.Named(method, handlerFunc, options)); return services; } public static IServiceCollection AddJsonRpcHandler(this IServiceCollection services, IJsonRpcHandler handler, JsonRpcHandlerOptions options = null) { - services.AddSingleton(JsonRpcHandlerDescription.Named(null, handler, options)); + services.AddSingleton(JsonRpcHandlerDescription.Named(null, handler, options)); return services; } public static IServiceCollection AddJsonRpcHandler(this IServiceCollection services, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options = null) { - services.AddSingleton(JsonRpcHandlerDescription.Named(null, handlerFunc, options)); + services.AddSingleton(JsonRpcHandlerDescription.Named(null, handlerFunc, options)); return services; } @@ -33,31 +33,27 @@ public static IServiceCollection AddJsonRpcHandler(this IServiceCollection servi { foreach (var item in handlers) { - services.AddSingleton(JsonRpcHandlerDescription.Infer(item)); + services.AddSingleton(JsonRpcHandlerDescription.Infer(item)); } return services; } - public static IServiceCollection AddJsonRpcHandler(this IServiceCollection services, JsonRpcHandlerOptions options = null) where THandler : IJsonRpcHandler - { - return AddJsonRpcHandler(services, typeof(THandler), options); - } + public static IServiceCollection AddJsonRpcHandler(this IServiceCollection services, JsonRpcHandlerOptions options = null) where THandler : IJsonRpcHandler => + AddJsonRpcHandler(services, typeof(THandler), options); - public static IServiceCollection AddJsonRpcHandler(this IServiceCollection services, string method, JsonRpcHandlerOptions options = null)where THandler : IJsonRpcHandler - { - return AddJsonRpcHandler(services, method, typeof(THandler), options); - } + public static IServiceCollection AddJsonRpcHandler(this IServiceCollection services, string method, JsonRpcHandlerOptions options = null) + where THandler : IJsonRpcHandler => AddJsonRpcHandler(services, method, typeof(THandler), options); public static IServiceCollection AddJsonRpcHandler(this IServiceCollection services, Type type, JsonRpcHandlerOptions options = null) { - services.AddSingleton(JsonRpcHandlerDescription.Infer(type, options)); + services.AddSingleton(JsonRpcHandlerDescription.Infer(type, options)); return services; } public static IServiceCollection AddJsonRpcHandler(this IServiceCollection services, string method, Type type, JsonRpcHandlerOptions options = null) { - services.AddSingleton(JsonRpcHandlerDescription.Named(method, type, options)); + services.AddSingleton(JsonRpcHandlerDescription.Named(method, type, options)); return services; } } diff --git a/src/JsonRpc/JsonRpcHandlerTypeDescription.cs b/src/JsonRpc/JsonRpcHandlerTypeDescription.cs index 155a1b206..8e8a3a0cf 100644 --- a/src/JsonRpc/JsonRpcHandlerTypeDescription.cs +++ b/src/JsonRpc/JsonRpcHandlerTypeDescription.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.JsonRpc { public class JsonRpcHandlerTypeDescription : JsonRpcHandlerDescription { - public JsonRpcHandlerTypeDescription(string method, Type handlerType, JsonRpcHandlerOptions options): base(options) + public JsonRpcHandlerTypeDescription(string method, Type handlerType, JsonRpcHandlerOptions options) : base(options) { Method = method; HandlerType = handlerType; @@ -13,4 +13,4 @@ public JsonRpcHandlerTypeDescription(string method, Type handlerType, JsonRpcHan public string Method { get; } public Type HandlerType { get; } } -} \ No newline at end of file +} diff --git a/src/JsonRpc/JsonRpcOptionsRegistryBase.cs b/src/JsonRpc/JsonRpcOptionsRegistryBase.cs index b8cdf879f..6b6503a2e 100644 --- a/src/JsonRpc/JsonRpcOptionsRegistryBase.cs +++ b/src/JsonRpc/JsonRpcOptionsRegistryBase.cs @@ -6,8 +6,9 @@ namespace OmniSharp.Extensions.JsonRpc public abstract class JsonRpcOptionsRegistryBase : JsonRpcCommonMethodsBase where T : IJsonRpcHandlerRegistry { public IServiceCollection Services { get; set; } = new ServiceCollection() - .AddOptions() - .AddLogging(); + .AddOptions() + .AddLogging(); + public IJsonRpcHandlerCollection Handlers { get; } = new JsonRpcHandlerCollection(); public T WithServices(Action servicesAction) @@ -52,15 +53,9 @@ public sealed override T AddHandlers(params IJsonRpcHandler[] handlers) return (T) (object) this; } - public sealed override T AddHandler(JsonRpcHandlerOptions options = null) - { - return AddHandler(typeof(THandler), options); - } + public sealed override T AddHandler(JsonRpcHandlerOptions options = null) => AddHandler(typeof(THandler), options); - public sealed override T AddHandler(string method, JsonRpcHandlerOptions options = null) - { - return AddHandler(method, typeof(THandler), options); - } + public sealed override T AddHandler(string method, JsonRpcHandlerOptions options = null) => AddHandler(method, typeof(THandler), options); public sealed override T AddHandler(Type type, JsonRpcHandlerOptions options = null) { diff --git a/src/JsonRpc/JsonRpcServer.cs b/src/JsonRpc/JsonRpcServer.cs index 85bfc9e69..a5392f385 100644 --- a/src/JsonRpc/JsonRpcServer.cs +++ b/src/JsonRpc/JsonRpcServer.cs @@ -1,15 +1,9 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Reactive.Concurrency; -using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; using System.Reactive.Disposables; using System.Threading; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Options; +using System.Threading.Tasks; using DryIoc; -using OmniSharp.Extensions.JsonRpc.Server; +using Microsoft.Extensions.Options; namespace OmniSharp.Extensions.JsonRpc { @@ -20,10 +14,11 @@ public class JsonRpcServer : JsonRpcServerBase, IJsonRpcServer internal static IContainer CreateContainer(JsonRpcServerOptions options, IServiceProvider outerServiceProvider) => JsonRpcServerContainer.Create(outerServiceProvider) - .AddJsonRpcServerInternals(options); + .AddJsonRpcServerInternals(options); public static JsonRpcServer Create(JsonRpcServerOptions options) => Create(options, null); public static JsonRpcServer Create(Action optionsAction) => Create(optionsAction, null); + public static JsonRpcServer Create(Action optionsAction, IServiceProvider outerServiceProvider) { var options = new JsonRpcServerOptions(); @@ -31,14 +26,18 @@ public static JsonRpcServer Create(Action optionsAction, I return Create(options, outerServiceProvider); } - public static JsonRpcServer Create(JsonRpcServerOptions options, IServiceProvider outerServiceProvider) => CreateContainer(options, outerServiceProvider).Resolve(); + public static JsonRpcServer Create(JsonRpcServerOptions options, IServiceProvider outerServiceProvider) => + CreateContainer(options, outerServiceProvider).Resolve(); public static Task From(JsonRpcServerOptions options) => From(options, null, CancellationToken.None); public static Task From(Action optionsAction) => From(optionsAction, null, CancellationToken.None); public static Task From(JsonRpcServerOptions options, CancellationToken cancellationToken) => From(options, null, cancellationToken); public static Task From(Action optionsAction, CancellationToken cancellationToken) => From(optionsAction, null, cancellationToken); public static Task From(JsonRpcServerOptions options, IServiceProvider outerServiceProvider) => 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) => + From(optionsAction, outerServiceProvider, CancellationToken.None); + public static Task From(Action optionsAction, IServiceProvider outerServiceProvider, CancellationToken cancellationToken) { var options = new JsonRpcServerOptions(); @@ -76,10 +75,7 @@ public virtual async Task Initialize(CancellationToken cancellationToken) _connection.Open(); } - public void Dispose() - { - _disposable.Dispose(); - } + public void Dispose() => _disposable.Dispose(); public IDisposable Register(Action registryAction) { diff --git a/src/JsonRpc/JsonRpcServerBase.cs b/src/JsonRpc/JsonRpcServerBase.cs index 89e485050..5e2e88cb7 100644 --- a/src/JsonRpc/JsonRpcServerBase.cs +++ b/src/JsonRpc/JsonRpcServerBase.cs @@ -1,8 +1,6 @@ -using System.Linq; -using System.Threading; +using System.Threading; using System.Threading.Tasks; using MediatR; -using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json.Linq; namespace OmniSharp.Extensions.JsonRpc @@ -18,39 +16,18 @@ 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) - { - return ResponseRouter.SendRequest(@params, cancellationToken); - } + public Task SendRequest(IRequest @params, CancellationToken cancellationToken) => ResponseRouter.SendRequest(@params, cancellationToken); - public IResponseRouterReturns SendRequest(string method, T @params) - { - return ResponseRouter.SendRequest(method, @params); - } + public IResponseRouterReturns SendRequest(string method, T @params) => ResponseRouter.SendRequest(method, @params); - public IResponseRouterReturns SendRequest(string method) - { - return ResponseRouter.SendRequest(method); - } + public IResponseRouterReturns SendRequest(string method) => ResponseRouter.SendRequest(method); - (string method, TaskCompletionSource pendingTask) IResponseRouter.GetRequest(long id) - { - return ResponseRouter.GetRequest(id); - } + (string method, TaskCompletionSource pendingTask) IResponseRouter.GetRequest(long id) => ResponseRouter.GetRequest(id); } } diff --git a/src/JsonRpc/JsonRpcServerContainer.cs b/src/JsonRpc/JsonRpcServerContainer.cs index 533d02fcc..c81edbb38 100644 --- a/src/JsonRpc/JsonRpcServerContainer.cs +++ b/src/JsonRpc/JsonRpcServerContainer.cs @@ -1,12 +1,7 @@ using System; -using System.IO.Pipelines; -using System.Linq; -using System.Reflection; using DryIoc; -using MediatR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using OmniSharp.Extensions.JsonRpc.Pipelines; namespace OmniSharp.Extensions.JsonRpc { @@ -14,18 +9,19 @@ internal static class JsonRpcServerContainer { public static IContainer Create(IServiceProvider outerServiceProvider) { - IContainer container = new Container() - .WithDependencyInjectionAdapter() - .With(rules => - rules - .WithTrackingDisposableTransients() - .WithoutThrowOnRegisteringDisposableTransient() - .WithFactorySelector(Rules.SelectLastRegisteredFactory()) - .WithResolveIEnumerableAsLazyEnumerable() - .With(FactoryMethod.ConstructorWithResolvableArgumentsIncludingNonPublic) - //.WithDefaultReuse(Reuse.Singleton) - .WithDefaultReuse(Reuse.Scoped) - ); + var container = new Container() + .WithDependencyInjectionAdapter() + .With( + rules => + rules + .WithTrackingDisposableTransients() + .WithoutThrowOnRegisteringDisposableTransient() + .WithFactorySelector(Rules.SelectLastRegisteredFactory()) + .WithResolveIEnumerableAsLazyEnumerable() + .With(FactoryMethod.ConstructorWithResolvableArgumentsIncludingNonPublic) + //.WithDefaultReuse(Reuse.Singleton) + .WithDefaultReuse(Reuse.Scoped) + ); var outerLoggerFactory = outerServiceProvider?.GetService(); if (outerLoggerFactory != null) @@ -36,10 +32,14 @@ public static IContainer Create(IServiceProvider outerServiceProvider) if (outerServiceProvider != null) { container.RegisterInstance(new ExternalServiceProvider(outerServiceProvider)); - container = container.With(rules => rules.WithUnknownServiceResolvers((request) => { - var value = outerServiceProvider.GetService(request.ServiceType); - return value == null ? null : (Factory)new RegisteredInstanceFactory(value, Reuse.Transient); - })); + container = container.With( + rules => rules.WithUnknownServiceResolvers( + request => { + var value = outerServiceProvider.GetService(request.ServiceType); + return value == null ? null : (Factory) new RegisteredInstanceFactory(value, Reuse.Transient); + } + ) + ); } else { diff --git a/src/JsonRpc/JsonRpcServerOptions.cs b/src/JsonRpc/JsonRpcServerOptions.cs index dee845674..3c0260676 100644 --- a/src/JsonRpc/JsonRpcServerOptions.cs +++ b/src/JsonRpc/JsonRpcServerOptions.cs @@ -1,12 +1,4 @@ -using System.Collections.Generic; -using System.Diagnostics; -using System.IO.Pipelines; -using System.Reactive.Disposables; -using System.Reflection; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using OmniSharp.Extensions.JsonRpc.Serialization; -using OmniSharp.Extensions.JsonRpc.Server; namespace OmniSharp.Extensions.JsonRpc { diff --git a/src/JsonRpc/JsonRpcServerOptionsBase.cs b/src/JsonRpc/JsonRpcServerOptionsBase.cs index ae91509ce..3760bc4f2 100644 --- a/src/JsonRpc/JsonRpcServerOptionsBase.cs +++ b/src/JsonRpc/JsonRpcServerOptionsBase.cs @@ -9,7 +9,6 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Nerdbank.Streams; -using OmniSharp.Extensions.JsonRpc.Server; namespace OmniSharp.Extensions.JsonRpc { @@ -34,10 +33,7 @@ public ILoggerFactory LoggerFactory internal CompositeDisposable CompositeDisposable { get; } = new CompositeDisposable(); IDisposable IJsonRpcServerOptions.RegisteredDisposables => CompositeDisposable; - public void RegisterForDisposal(IDisposable disposable) - { - CompositeDisposable.Add(disposable); - } + public void RegisterForDisposal(IDisposable disposable) => CompositeDisposable.Add(disposable); public T WithAssemblies(IEnumerable assemblies) { @@ -98,20 +94,12 @@ public T WithRequestProcessIdentifier(IRequestProcessIdentifier requestProcessId } public T WithHandler(JsonRpcHandlerOptions options = null) - where THandler : class, IJsonRpcHandler - { - return AddHandler(options); - } + where THandler : class, IJsonRpcHandler => + AddHandler(options); - public T WithHandlersFrom(Type type, JsonRpcHandlerOptions options = null) - { - return AddHandler(type, options); - } + public T WithHandlersFrom(Type type, JsonRpcHandlerOptions options = null) => AddHandler(type, options); - public T WithHandlersFrom(TypeInfo typeInfo, JsonRpcHandlerOptions options = null) - { - return AddHandler(typeInfo.AsType(), options); - } + public T WithHandlersFrom(TypeInfo typeInfo, JsonRpcHandlerOptions options = null) => AddHandler(typeInfo.AsType(), options); public T WithResponseExceptionFactory(CreateResponseExceptionHandler handler) { diff --git a/src/JsonRpc/JsonRpcServerOptionsExtensions.cs b/src/JsonRpc/JsonRpcServerOptionsExtensions.cs index 1ee614650..742d1c736 100644 --- a/src/JsonRpc/JsonRpcServerOptionsExtensions.cs +++ b/src/JsonRpc/JsonRpcServerOptionsExtensions.cs @@ -1,12 +1,3 @@ -using System; -using System.IO; -using System.IO.Pipelines; -using System.Reflection; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Nerdbank.Streams; -using OmniSharp.Extensions.JsonRpc.Server; - namespace OmniSharp.Extensions.JsonRpc { public static class JsonRpcServerOptionsExtensions diff --git a/src/JsonRpc/JsonRpcServerRegistry.cs b/src/JsonRpc/JsonRpcServerRegistry.cs index 7fd375df7..60df6dd08 100644 --- a/src/JsonRpc/JsonRpcServerRegistry.cs +++ b/src/JsonRpc/JsonRpcServerRegistry.cs @@ -1,8 +1,6 @@ -using System; - -namespace OmniSharp.Extensions.JsonRpc +namespace OmniSharp.Extensions.JsonRpc { - class JsonRpcServerRegistry : InterimJsonRpcServerRegistry, IJsonRpcServerRegistry + internal class JsonRpcServerRegistry : InterimJsonRpcServerRegistry, IJsonRpcServerRegistry { public JsonRpcServerRegistry(CompositeHandlersManager handlersManager) : base(handlersManager) { diff --git a/src/JsonRpc/JsonRpcServerResolver.cs b/src/JsonRpc/JsonRpcServerResolver.cs index 9e1036638..54efe518c 100644 --- a/src/JsonRpc/JsonRpcServerResolver.cs +++ b/src/JsonRpc/JsonRpcServerResolver.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Concurrent; using DryIoc; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; namespace OmniSharp.Extensions.JsonRpc diff --git a/src/JsonRpc/JsonRpcServerServiceCollectionExtensions.cs b/src/JsonRpc/JsonRpcServerServiceCollectionExtensions.cs index 5c7d09944..ce3f91736 100644 --- a/src/JsonRpc/JsonRpcServerServiceCollectionExtensions.cs +++ b/src/JsonRpc/JsonRpcServerServiceCollectionExtensions.cs @@ -1,19 +1,13 @@ using System; using System.IO.Pipelines; using System.Linq; -using System.Net.NetworkInformation; -using System.Reflection; +using DryIoc; +using MediatR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -using DryIoc; -using MediatR.Pipeline; -using MediatR.Registration; -using Microsoft.Extensions.Logging; using OmniSharp.Extensions.JsonRpc.Pipelines; -using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.JsonRpc.Serialization; -using MediatR; namespace OmniSharp.Extensions.JsonRpc { @@ -46,15 +40,15 @@ internal static IContainer AddJsonRpcServerCore(this IContainer container, Js container.RegisterMany( serviceTypeCondition: type => type.IsInterface, made: Parameters.Of - .Type(serviceKey: nameof(options.Output)), + .Type(serviceKey: nameof(options.Output)), reuse: Reuse.Singleton ); container.Register( made: new Made.TypedMade().Parameters - .Type(serviceKey: nameof(options.Input)) - .Type(serviceKey: nameof(options.MaximumRequestTimeout)) - .Type(serviceKey: nameof(options.SupportsContentModified)) - .Name("concurrency", serviceKey: nameof(options.Concurrency)), + .Type(serviceKey: nameof(options.Input)) + .Type(serviceKey: nameof(options.MaximumRequestTimeout)) + .Type(serviceKey: nameof(options.SupportsContentModified)) + .Name("concurrency", serviceKey: nameof(options.Concurrency)), reuse: Reuse.Singleton ); @@ -64,39 +58,46 @@ internal static IContainer AddJsonRpcServerCore(this IContainer container, Js ); container.RegisterInstance(options.Handlers); - container.RegisterInitializer((collection, context) => { - foreach (var description in context - .ResolveMany() - .Concat(context - .ResolveMany().Select(_ => JsonRpcHandlerDescription.Infer(_)) - )) - { - collection.Add(description); + container.RegisterInitializer( + (collection, context) => { + foreach (var description in context + .ResolveMany() + .Concat( + context + .ResolveMany().Select(_ => JsonRpcHandlerDescription.Infer(_)) + )) + { + collection.Add(description); + } } - }); + ); return container.AddJsonRpcMediatR(); } internal static IContainer AddJsonRpcMediatR(this IContainer container) { - container.RegisterMany(new[] {typeof(IMediator).GetAssembly()}, Registrator.Interfaces, reuse: Reuse.ScopedOrSingleton); - container.RegisterMany(new[] {typeof(RequestMustNotBeNullProcessor<>), typeof(ResponseMustNotBeNullProcessor<,>)}, reuse: Reuse.ScopedOrSingleton); - container.RegisterMany(reuse: Reuse.Scoped); - container.RegisterDelegate(context => context.Resolve, reuse: Reuse.ScopedOrSingleton); - - return container.With(rules => rules.WithUnknownServiceResolvers(request => { - if (request.ServiceType.IsGenericType && typeof(IRequestHandler<,>).IsAssignableFrom(request.ServiceType.GetGenericTypeDefinition())) - { - var context = request.Container.Resolve(); - if (context != null) - { - return new RegisteredInstanceFactory(context.Descriptor.Handler); + container.RegisterMany(new[] { typeof(IMediator).GetAssembly() }, Registrator.Interfaces, Reuse.ScopedOrSingleton); + container.RegisterMany(new[] { typeof(RequestMustNotBeNullProcessor<>), typeof(ResponseMustNotBeNullProcessor<,>) }, Reuse.ScopedOrSingleton); + container.RegisterMany(Reuse.Scoped); + container.RegisterDelegate(context => context.Resolve, Reuse.ScopedOrSingleton); + + return container.With( + rules => rules.WithUnknownServiceResolvers( + request => { + if (request.ServiceType.IsGenericType && typeof(IRequestHandler<,>).IsAssignableFrom(request.ServiceType.GetGenericTypeDefinition())) + { + var context = request.Container.Resolve(); + if (context != null) + { + return new RegisteredInstanceFactory(context.Descriptor.Handler); + } + } + + return null; } - } - - return null; - })); + ) + ); } internal static IContainer AddJsonRpcServerInternals(this IContainer container, JsonRpcServerOptions options) @@ -121,18 +122,20 @@ internal static IContainer AddJsonRpcServerInternals(this IContainer container, container.RegisterInstance(options.Serializer ?? new JsonRpcSerializer()); container.RegisterInstance(options.Receiver); container.RegisterInstance(options.RequestProcessIdentifier); - container.RegisterInstance(options.OnUnhandledException ?? (e => { })); + container.RegisterInstance(options.OnUnhandledException ?? ( e => { } )); - container.RegisterMany(reuse: Reuse.Singleton); + container.RegisterMany(Reuse.Singleton); container.RegisterMany( nonPublicServiceTypes: true, serviceTypeCondition: type => typeof(IHandlersManager) == type || type == typeof(HandlerCollection), reuse: Reuse.Singleton ); - container.RegisterInitializer((manager, context) => { - var descriptions = context.Resolve(); - descriptions.Populate(context, manager); - }); + container.RegisterInitializer( + (manager, context) => { + var descriptions = context.Resolve(); + descriptions.Populate(context, manager); + } + ); container.RegisterInstance>(new ValueOptionsFactory(options)); container.RegisterMany(serviceTypeCondition: type => type == typeof(IJsonRpcServer) || type == typeof(JsonRpcServer), reuse: Reuse.Singleton); @@ -140,10 +143,8 @@ internal static IContainer AddJsonRpcServerInternals(this IContainer container, return container; } - public static IServiceCollection AddJsonRpcServer(this IServiceCollection services, Action configureOptions = null) - { - return AddJsonRpcServer(services, Options.DefaultName, configureOptions); - } + public static IServiceCollection AddJsonRpcServer(this IServiceCollection services, Action configureOptions = null) => + AddJsonRpcServer(services, Options.DefaultName, configureOptions); public static IServiceCollection AddJsonRpcServer(this IServiceCollection services, string name, Action configureOptions = null) { @@ -153,15 +154,19 @@ public static IServiceCollection AddJsonRpcServer(this IServiceCollection servic { services.RemoveAll(); services.RemoveAll(); - services.AddSingleton(_ => - throw new NotSupportedException("JsonRpcServer has been registered multiple times, you must use JsonRpcServerResolver instead")); - services.AddSingleton(_ => - throw new NotSupportedException("JsonRpcServer has been registered multiple times, you must use JsonRpcServerResolver instead")); + services.AddSingleton( + _ => + throw new NotSupportedException("JsonRpcServer has been registered multiple times, you must use JsonRpcServerResolver instead") + ); + services.AddSingleton( + _ => + throw new NotSupportedException("JsonRpcServer has been registered multiple times, you must use JsonRpcServerResolver instead") + ); } services - .AddOptions() - .AddLogging(); + .AddOptions() + .AddLogging(); services.TryAddSingleton(); services.TryAddSingleton(_ => _.GetRequiredService().Get(name)); services.TryAddSingleton(_ => _.GetRequiredService().Get(name)); diff --git a/src/JsonRpc/LinkedHandler.cs b/src/JsonRpc/LinkedHandler.cs index 1fbd3f6fa..f88b02118 100644 --- a/src/JsonRpc/LinkedHandler.cs +++ b/src/JsonRpc/LinkedHandler.cs @@ -15,6 +15,7 @@ public LinkedHandler(string method, IHandlerDescriptor descriptor, Action dispos _disposeAction = disposeAction; Method = method; } + public string Method { get; } public Type HandlerType => _descriptor.HandlerType; @@ -32,9 +33,6 @@ public LinkedHandler(string method, IHandlerDescriptor descriptor, Action dispos public RequestProcessType? RequestProcessType => _descriptor.RequestProcessType; - public void Dispose() - { - _disposeAction(); - } + public void Dispose() => _disposeAction(); } -} \ No newline at end of file +} diff --git a/src/JsonRpc/MethodAttribute.cs b/src/JsonRpc/MethodAttribute.cs index d6042e410..26bd017a4 100644 --- a/src/JsonRpc/MethodAttribute.cs +++ b/src/JsonRpc/MethodAttribute.cs @@ -12,10 +12,7 @@ public class MethodAttribute : Attribute public string Method { get; } public Direction Direction { get; } - public MethodAttribute(string method) - { - Method = method; - } + public MethodAttribute(string method) => Method = method; /// /// Decorate the method given the given direction @@ -28,18 +25,15 @@ public MethodAttribute(string method, Direction direction) Direction = direction; } - public static MethodAttribute From(Type type) - { - return AllFrom(type).FirstOrDefault(); - } + public static MethodAttribute From(Type type) => AllFrom(type).FirstOrDefault(); - public static IEnumerable AllFrom(Type type) - { - return CollectMethodAttributes(type) - .Concat(type - .GetInterfaces() - .SelectMany(CollectMethodAttributes)); - } + public static IEnumerable AllFrom(Type type) => + CollectMethodAttributes(type) + .Concat( + type + .GetInterfaces() + .SelectMany(CollectMethodAttributes) + ); private static IEnumerable CollectMethodAttributes(Type t) { diff --git a/src/JsonRpc/NoopResponseRouter.cs b/src/JsonRpc/NoopResponseRouter.cs index 2f51ab80e..d5f6e82ec 100644 --- a/src/JsonRpc/NoopResponseRouter.cs +++ b/src/JsonRpc/NoopResponseRouter.cs @@ -8,51 +8,39 @@ namespace OmniSharp.Extensions.JsonRpc /// /// Used top ensure noop behaviors don't throw if they consume a router /// - class NoopResponseRouter : IResponseRouter + internal class NoopResponseRouter : IResponseRouter { - private NoopResponseRouter() {} + private NoopResponseRouter() + { + } + public static NoopResponseRouter Instance = new NoopResponseRouter(); public void SendNotification(string method) { - } public void SendNotification(string method, T @params) { - } public void SendNotification(IRequest request) { - } public IResponseRouterReturns SendRequest(string method, T @params) => new Impl(); public IResponseRouterReturns SendRequest(string method) => new Impl(); - public Task SendRequest(IRequest request, CancellationToken cancellationToken) - { - return Task.FromResult(default); - } + public Task SendRequest(IRequest request, CancellationToken cancellationToken) => Task.FromResult(default); - (string method, TaskCompletionSource pendingTask) IResponseRouter.GetRequest(long id) - { - return ("UNKNOWN", new TaskCompletionSource()); - } + (string method, TaskCompletionSource pendingTask) IResponseRouter.GetRequest(long id) => ( "UNKNOWN", new TaskCompletionSource() ); - class Impl : IResponseRouterReturns + private class Impl : IResponseRouterReturns { - public Task Returning(CancellationToken cancellationToken) - { - return Task.FromResult(default); - } - - public Task ReturningVoid(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + public Task Returning(CancellationToken cancellationToken) => Task.FromResult(default); + + public Task ReturningVoid(CancellationToken cancellationToken) => Task.CompletedTask; } } } diff --git a/src/JsonRpc/NotificationHandler.cs b/src/JsonRpc/NotificationHandler.cs index 31d1262a0..256d44e11 100644 --- a/src/JsonRpc/NotificationHandler.cs +++ b/src/JsonRpc/NotificationHandler.cs @@ -8,27 +8,19 @@ namespace OmniSharp.Extensions.JsonRpc public static class NotificationHandler { public static DelegatingHandlers.Notification For(Action handler) - where TParams : IRequest - { - return new DelegatingHandlers.Notification(handler); - } + where TParams : IRequest => + new DelegatingHandlers.Notification(handler); public static DelegatingHandlers.Notification For(Func handler) - where TParams : IRequest - { - return new DelegatingHandlers.Notification(handler); - } + where TParams : IRequest => + new DelegatingHandlers.Notification(handler); public static DelegatingHandlers.Notification For(Action handler) - where TParams : IRequest - { - return new DelegatingHandlers.Notification((p, ct) => handler(p)); - } + where TParams : IRequest => + new DelegatingHandlers.Notification((p, ct) => handler(p)); public static DelegatingHandlers.Notification For(Func handler) - where TParams : IRequest - { - return new DelegatingHandlers.Notification((p, ct) => handler(p)); - } + where TParams : IRequest => + new DelegatingHandlers.Notification((p, ct) => handler(p)); } } diff --git a/src/JsonRpc/OnUnhandledExceptionHandler.cs b/src/JsonRpc/OnUnhandledExceptionHandler.cs index c919273b3..461a13468 100644 --- a/src/JsonRpc/OnUnhandledExceptionHandler.cs +++ b/src/JsonRpc/OnUnhandledExceptionHandler.cs @@ -3,4 +3,4 @@ namespace OmniSharp.Extensions.JsonRpc { public delegate void OnUnhandledExceptionHandler(Exception exception); -} \ No newline at end of file +} diff --git a/src/JsonRpc/OutputHandler.cs b/src/JsonRpc/OutputHandler.cs index e0cf41854..85698767e 100644 --- a/src/JsonRpc/OutputHandler.cs +++ b/src/JsonRpc/OutputHandler.cs @@ -9,7 +9,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Nerdbank.Streams; namespace OmniSharp.Extensions.JsonRpc { @@ -27,7 +26,8 @@ public OutputHandler( ISerializer serializer, IReceiver receiver, IScheduler scheduler, - ILogger logger) + ILogger logger + ) { _pipeWriter = pipeWriter; _serializer = serializer; @@ -37,11 +37,11 @@ public OutputHandler( _disposable = new CompositeDisposable { _queue - .ObserveOn(scheduler) - .Where(receiver.ShouldFilterOutput) - .Select(value => Observable.FromAsync(ct => ProcessOutputStream(value, ct))) - .Concat() - .Subscribe(), + .ObserveOn(scheduler) + .Where(receiver.ShouldFilterOutput) + .Select(value => Observable.FromAsync(ct => ProcessOutputStream(value, ct))) + .Concat() + .Subscribe(), _queue }; } @@ -50,12 +50,14 @@ public OutputHandler( PipeWriter pipeWriter, ISerializer serializer, IReceiver receiver, - ILogger logger): this( + ILogger logger + ) : this( pipeWriter, serializer, receiver, - new EventLoopScheduler(_ => new Thread(_) {IsBackground = true, Name = "OutputHandler"}), - logger) + new EventLoopScheduler(_ => new Thread(_) { IsBackground = true, Name = "OutputHandler" }), + logger + ) { } @@ -105,10 +107,7 @@ private async Task ProcessOutputStream(object value, CancellationToken cancellat } } - public Task WaitForShutdown() - { - return _outputIsFinished.Task; - } + public Task WaitForShutdown() => _outputIsFinished.Task; private void Error(Exception ex) { diff --git a/src/JsonRpc/ParallelAttribute.cs b/src/JsonRpc/ParallelAttribute.cs index de968b1ec..840aed835 100644 --- a/src/JsonRpc/ParallelAttribute.cs +++ b/src/JsonRpc/ParallelAttribute.cs @@ -2,6 +2,8 @@ namespace OmniSharp.Extensions.JsonRpc { public sealed class ParallelAttribute : ProcessAttribute { - public ParallelAttribute() : base(RequestProcessType.Parallel) { } + public ParallelAttribute() : base(RequestProcessType.Parallel) + { + } } } diff --git a/src/JsonRpc/ParallelRequestProcessIdentifier.cs b/src/JsonRpc/ParallelRequestProcessIdentifier.cs index b44045129..54fafbf2a 100644 --- a/src/JsonRpc/ParallelRequestProcessIdentifier.cs +++ b/src/JsonRpc/ParallelRequestProcessIdentifier.cs @@ -2,9 +2,6 @@ namespace OmniSharp.Extensions.JsonRpc { public class ParallelRequestProcessIdentifier : IRequestProcessIdentifier { - public RequestProcessType Identify(IHandlerDescriptor descriptor) - { - return descriptor.RequestProcessType ?? RequestProcessType.Parallel; - } + public RequestProcessType Identify(IHandlerDescriptor descriptor) => descriptor.RequestProcessType ?? RequestProcessType.Parallel; } } diff --git a/src/JsonRpc/Pipelines/RequestMustNotBeNullProcessor.cs b/src/JsonRpc/Pipelines/RequestMustNotBeNullProcessor.cs index 451cdd9d4..5a829390e 100644 --- a/src/JsonRpc/Pipelines/RequestMustNotBeNullProcessor.cs +++ b/src/JsonRpc/Pipelines/RequestMustNotBeNullProcessor.cs @@ -2,10 +2,11 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using MediatR.Pipeline; namespace OmniSharp.Extensions.JsonRpc.Pipelines { - public class RequestMustNotBeNullProcessor : MediatR.Pipeline.IRequestPreProcessor + public class RequestMustNotBeNullProcessor : IRequestPreProcessor { public Task Process(T request, CancellationToken cancellationToken) { diff --git a/src/JsonRpc/Pipelines/ResponseMustNotBeNullProcessor.cs b/src/JsonRpc/Pipelines/ResponseMustNotBeNullProcessor.cs index fc91e2cf2..87866e4b5 100644 --- a/src/JsonRpc/Pipelines/ResponseMustNotBeNullProcessor.cs +++ b/src/JsonRpc/Pipelines/ResponseMustNotBeNullProcessor.cs @@ -2,10 +2,11 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using MediatR.Pipeline; namespace OmniSharp.Extensions.JsonRpc.Pipelines { - public class ResponseMustNotBeNullProcessor : MediatR.Pipeline.IRequestPostProcessor + public class ResponseMustNotBeNullProcessor : IRequestPostProcessor { public Task Process(T request, R response, CancellationToken cancellationToken) { diff --git a/src/JsonRpc/ProcessAttribute.cs b/src/JsonRpc/ProcessAttribute.cs index 9dc8121b3..a91864e38 100644 --- a/src/JsonRpc/ProcessAttribute.cs +++ b/src/JsonRpc/ProcessAttribute.cs @@ -5,11 +5,8 @@ namespace OmniSharp.Extensions.JsonRpc [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class ProcessAttribute : Attribute { - public ProcessAttribute(RequestProcessType type) - { - Type = type; - } + public ProcessAttribute(RequestProcessType type) => Type = type; public RequestProcessType Type { get; } } -} \ No newline at end of file +} diff --git a/src/JsonRpc/ProcessScheduler.cs b/src/JsonRpc/ProcessScheduler.cs index 701c01468..1ca6f8089 100644 --- a/src/JsonRpc/ProcessScheduler.cs +++ b/src/JsonRpc/ProcessScheduler.cs @@ -9,7 +9,7 @@ namespace OmniSharp.Extensions.JsonRpc { - class ProcessScheduler : IDisposable + internal class ProcessScheduler : IDisposable { private readonly IObserver<(RequestProcessType type, string name, SchedulerDelegate request)> _enqueue; private readonly CompositeDisposable _disposable = new CompositeDisposable(); @@ -19,7 +19,8 @@ public ProcessScheduler( bool supportContentModified, int? concurrency, TimeSpan requestTimeout, - IScheduler scheduler) + IScheduler scheduler + ) { var concurrency1 = concurrency; var logger = loggerFactory.CreateLogger(); @@ -28,84 +29,105 @@ public ProcessScheduler( _disposable.Add(subject); _enqueue = subject; - var obs = Observable.Create(observer => { - var cd = new CompositeDisposable(); - - var observableQueue = - new BehaviorSubject<(RequestProcessType type, ReplaySubject> observer, Subject contentModifiedSource)>(( - RequestProcessType.Serial, new ReplaySubject>(int.MaxValue), supportContentModified ? new Subject() : null)); - - cd.Add(subject.Subscribe(item => { - if (observableQueue.Value.type != item.type) - { - logger.LogDebug("Swapping from {From} to {To}", observableQueue.Value.type, item.type); - if (supportContentModified && observableQueue.Value.type == RequestProcessType.Parallel) - { - logger.LogDebug("Cancelling any outstanding requests (switch from parallel to serial)"); - observableQueue.Value.contentModifiedSource.OnNext(Unit.Default); - observableQueue.Value.contentModifiedSource.OnCompleted(); - } - logger.LogDebug("Completing existing request process type {Type}", observableQueue.Value.type); - observableQueue.Value.observer.OnCompleted(); - observableQueue.OnNext((item.type, new ReplaySubject>(int.MaxValue), supportContentModified ? new Subject() : null)); - } - - logger.LogDebug("Queueing {Type}:{Name} request for processing", item.type, item.name); - observableQueue.Value.observer.OnNext(HandleRequest(item.name, item.request(observableQueue.Value.contentModifiedSource ?? Observable.Never(), scheduler))); - })); - - cd.Add(observableQueue - .Select(item => { - var (type, replay, _) = item; - - if (type == RequestProcessType.Serial) - { - // logger.LogDebug("Changing to serial processing"); - return replay.Concat(); - } - - if (concurrency1.HasValue) - { - // logger.LogDebug("Changing to parallel processing with concurrency of {Concurrency}", concurrency1.Value); - return replay.Merge(concurrency1.Value); - } - else - { - // logger.LogDebug("Changing to parallel processing with concurrency of {Concurrency}", "Unlimited"); - return replay.Merge(); - } - }) - .Concat() - .Subscribe(observer) - ); - - return cd; - }); - - _disposable.Add(obs - .ObserveOn(scheduler) - .Subscribe(_ => { }) + var obs = Observable.Create( + observer => { + var cd = new CompositeDisposable(); + + var observableQueue = + new BehaviorSubject<(RequestProcessType type, ReplaySubject> observer, Subject contentModifiedSource)>( + ( + RequestProcessType.Serial, new ReplaySubject>(int.MaxValue), supportContentModified ? new Subject() : null ) + ); + + cd.Add( + subject.Subscribe( + item => { + if (observableQueue.Value.type != item.type) + { + logger.LogDebug("Swapping from {From} to {To}", observableQueue.Value.type, item.type); + if (supportContentModified && observableQueue.Value.type == RequestProcessType.Parallel) + { + logger.LogDebug("Cancelling any outstanding requests (switch from parallel to serial)"); + observableQueue.Value.contentModifiedSource.OnNext(Unit.Default); + observableQueue.Value.contentModifiedSource.OnCompleted(); + } + + logger.LogDebug("Completing existing request process type {Type}", observableQueue.Value.type); + observableQueue.Value.observer.OnCompleted(); + observableQueue.OnNext(( item.type, new ReplaySubject>(int.MaxValue), supportContentModified ? new Subject() : null )); + } + + logger.LogDebug("Queueing {Type}:{Name} request for processing", item.type, item.name); + observableQueue.Value.observer.OnNext( + HandleRequest(item.name, item.request(observableQueue.Value.contentModifiedSource ?? Observable.Never(), scheduler)) + ); + } + ) + ); + + cd.Add( + observableQueue + .Select( + item => { + var (type, replay, _) = item; + + if (type == RequestProcessType.Serial) + { + // logger.LogDebug("Changing to serial processing"); + return replay.Concat(); + } + + if (concurrency1.HasValue) + { + // logger.LogDebug("Changing to parallel processing with concurrency of {Concurrency}", concurrency1.Value); + return replay.Merge(concurrency1.Value); + } + + // logger.LogDebug("Changing to parallel processing with concurrency of {Concurrency}", "Unlimited"); + return replay.Merge(); + } + ) + .Concat() + .Subscribe(observer) + ); + + return cd; + } + ); + + _disposable.Add( + obs + .ObserveOn(scheduler) + .Subscribe(_ => { }) ); IObservable HandleRequest(string name, IObservable request) { return request - .Catch(ex => { - logger.LogDebug(ex, "Request {Name} was explicitly cancelled", name); - return Observable.Empty(); - }) - .Catch(ex => { - logger.LogDebug(ex, "Request {Name} was cancelled, due to content being modified", name); - return Observable.Empty(); - }) - .Catch(ex => { - logger.LogDebug(ex, "Request {Name} was cancelled, due to timeout", name); - return Observable.Empty(); - }) - .Catch(ex => { - logger.LogCritical(Events.UnhandledException, ex, "Unhandled exception executing {Name}", name); - return Observable.Empty(); - }) + .Catch( + ex => { + logger.LogDebug(ex, "Request {Name} was explicitly cancelled", name); + return Observable.Empty(); + } + ) + .Catch( + ex => { + logger.LogDebug(ex, "Request {Name} was cancelled, due to content being modified", name); + return Observable.Empty(); + } + ) + .Catch( + ex => { + logger.LogDebug(ex, "Request {Name} was cancelled, due to timeout", name); + return Observable.Empty(); + } + ) + .Catch( + ex => { + logger.LogCritical(Events.UnhandledException, ex, "Unhandled exception executing {Name}", name); + return Observable.Empty(); + } + ) // .Do(v => { // logger.LogDebug("Request {Name} was processed", name); // }, (ex) => { @@ -117,14 +139,8 @@ IObservable HandleRequest(string name, IObservable request) } } - public void Add(RequestProcessType type, string name, SchedulerDelegate request) - { - _enqueue.OnNext((type, name, request)); - } + public void Add(RequestProcessType type, string name, SchedulerDelegate request) => _enqueue.OnNext(( type, name, request )); - public void Dispose() - { - _disposable.Dispose(); - } + public void Dispose() => _disposable.Dispose(); } } diff --git a/src/JsonRpc/Receiver.cs b/src/JsonRpc/Receiver.cs index c1d9ca99f..b4ca35cf2 100644 --- a/src/JsonRpc/Receiver.cs +++ b/src/JsonRpc/Receiver.cs @@ -38,12 +38,13 @@ public virtual (IEnumerable results, bool hasResponse) GetRequests(JToken { results.Add(GetRenor(container)); } - return (results, results.Any(z => z.IsResponse)); + + return ( results, results.Any(z => z.IsResponse) ); } protected virtual Renor GetRenor(JToken @object) { - if (!(@object is JObject request)) + if (!( @object is JObject request )) { return new InvalidRequest(null, "Not an object"); } @@ -58,9 +59,9 @@ protected virtual Renor GetRenor(JToken @object) bool hasRequestId; 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); + 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 ); } if (hasRequestId && request.TryGetValue("result", out var response)) @@ -99,10 +100,8 @@ protected virtual Renor GetRenor(JToken @object) { return new Notification(method, @params); } - else - { - return new Request(requestId, method, @params); - } + + return new Request(requestId, method, @params); } } } diff --git a/src/JsonRpc/RequestCancelled.cs b/src/JsonRpc/RequestCancelled.cs index 5a722e4bd..6bda757ef 100644 --- a/src/JsonRpc/RequestCancelled.cs +++ b/src/JsonRpc/RequestCancelled.cs @@ -5,7 +5,12 @@ namespace OmniSharp.Extensions.JsonRpc { public class RequestCancelled : RpcError { - internal RequestCancelled(string method) : base(null, method, new ErrorMessage(ErrorCodes.RequestCancelled, "Request Cancelled")) { } - internal RequestCancelled(object id, string method) : base(id, method, new ErrorMessage(ErrorCodes.RequestCancelled, "Request Cancelled")) { } + internal RequestCancelled(string method) : base(null, method, new ErrorMessage(ErrorCodes.RequestCancelled, "Request Cancelled")) + { + } + + internal RequestCancelled(object id, string method) : base(id, method, new ErrorMessage(ErrorCodes.RequestCancelled, "Request Cancelled")) + { + } } } diff --git a/src/JsonRpc/RequestContext.cs b/src/JsonRpc/RequestContext.cs index 727a82d61..6d1bb9968 100644 --- a/src/JsonRpc/RequestContext.cs +++ b/src/JsonRpc/RequestContext.cs @@ -1,6 +1,6 @@ namespace OmniSharp.Extensions.JsonRpc { - class RequestContext : IRequestContext + internal class RequestContext : IRequestContext { public IHandlerDescriptor Descriptor { get; set; } } diff --git a/src/JsonRpc/RequestDescriptor.cs b/src/JsonRpc/RequestDescriptor.cs index b0273441b..7c2e7c02f 100644 --- a/src/JsonRpc/RequestDescriptor.cs +++ b/src/JsonRpc/RequestDescriptor.cs @@ -4,9 +4,9 @@ namespace OmniSharp.Extensions.JsonRpc { - class RequestDescriptor : IRequestDescriptor + internal class RequestDescriptor : IRequestDescriptor { - private IEnumerable _descriptors; + private readonly IEnumerable _descriptors; public RequestDescriptor(IEnumerable descriptors) { @@ -23,7 +23,7 @@ public RequestDescriptor(params TDescriptor[] descriptors) } public IEnumerator GetEnumerator() => _descriptors.GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable) _descriptors).GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => ( (IEnumerable) _descriptors ).GetEnumerator(); public TDescriptor Default { get; } } diff --git a/src/JsonRpc/RequestHandler.cs b/src/JsonRpc/RequestHandler.cs index 4e404bdd5..d5a9b6497 100644 --- a/src/JsonRpc/RequestHandler.cs +++ b/src/JsonRpc/RequestHandler.cs @@ -5,32 +5,26 @@ namespace OmniSharp.Extensions.JsonRpc { - public static class RequestHandler { - + public static class RequestHandler + { public static DelegatingHandlers.Request For( - Func> handler) - where TParams : IRequest - { - return new DelegatingHandlers.Request(handler); - } + Func> handler + ) + where TParams : IRequest => + new DelegatingHandlers.Request(handler); public static DelegatingHandlers.Request For( - Func> handler) - where TParams : IRequest - { - return new DelegatingHandlers.Request(handler); - } + Func> handler + ) + where TParams : IRequest => + new DelegatingHandlers.Request(handler); public static DelegatingHandlers.Request For(Func handler) - where TParams : IRequest - { - return new DelegatingHandlers.Request(handler); - } + where TParams : IRequest => + new DelegatingHandlers.Request(handler); public static DelegatingHandlers.Request For(Func handler) - where TParams : IRequest - { - return new DelegatingHandlers.Request(handler); - } + where TParams : IRequest => + new DelegatingHandlers.Request(handler); } -} \ No newline at end of file +} diff --git a/src/JsonRpc/RequestRouter.cs b/src/JsonRpc/RequestRouter.cs index 0269323ea..12a0ddb23 100644 --- a/src/JsonRpc/RequestRouter.cs +++ b/src/JsonRpc/RequestRouter.cs @@ -1,8 +1,7 @@ -using System; using System.Linq; using Microsoft.Extensions.DependencyInjection; -using OmniSharp.Extensions.JsonRpc.Server; using Microsoft.Extensions.Logging; +using OmniSharp.Extensions.JsonRpc.Server; namespace OmniSharp.Extensions.JsonRpc { @@ -16,24 +15,13 @@ public RequestRouter( IServiceScopeFactory serviceScopeFactory, ILogger logger ) - : base(serializer, serviceScopeFactory, logger) - { + : base(serializer, serviceScopeFactory, logger) => _collection = collection; - } - private IHandlerDescriptor FindDescriptor(IMethodWithParams instance) - { - return _collection.Descriptors.FirstOrDefault(x => x.Method == instance.Method); - } + private IHandlerDescriptor FindDescriptor(IMethodWithParams instance) => _collection.Descriptors.FirstOrDefault(x => x.Method == instance.Method); - public override IRequestDescriptor GetDescriptors(Notification notification) - { - return new RequestDescriptor(FindDescriptor(notification)); - } + public override IRequestDescriptor GetDescriptors(Notification notification) => new RequestDescriptor(FindDescriptor(notification)); - public override IRequestDescriptor GetDescriptors(Request request) - { - return new RequestDescriptor(FindDescriptor(request)); - } + public override IRequestDescriptor GetDescriptors(Request request) => new RequestDescriptor(FindDescriptor(request)); } } diff --git a/src/JsonRpc/RequestRouterBase.cs b/src/JsonRpc/RequestRouterBase.cs index 6a8aaf195..f94faf014 100644 --- a/src/JsonRpc/RequestRouterBase.cs +++ b/src/JsonRpc/RequestRouterBase.cs @@ -1,17 +1,16 @@ using System; +using System.Collections.Generic; +using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using MediatR; using Microsoft.Extensions.DependencyInjection; -using OmniSharp.Extensions.JsonRpc.Server; -using OmniSharp.Extensions.JsonRpc.Server.Messages; -using System.Collections.Concurrent; using Microsoft.Extensions.Logging; -using System.Collections.Generic; -using System.Linq; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc.Client; +using OmniSharp.Extensions.JsonRpc.Server; +using OmniSharp.Extensions.JsonRpc.Server.Messages; namespace OmniSharp.Extensions.JsonRpc { @@ -32,19 +31,21 @@ public RequestRouterBase(ISerializer serializer, IServiceScopeFactory serviceSco public async Task RouteNotification(IRequestDescriptor descriptors, Notification notification, CancellationToken token) { using var debug = _logger.TimeDebug("Routing Notification {Method}", notification.Method); - using var _ = _logger.BeginScope(new[] { - new KeyValuePair("Method", notification.Method), - new KeyValuePair("Params", notification.Params?.ToString()) - }); + using var _ = _logger.BeginScope( + new[] { + new KeyValuePair("Method", notification.Method), + new KeyValuePair("Params", notification.Params?.ToString()) + } + ); object @params = null; - if (!(descriptors.Default.Params is null)) + if (!( descriptors.Default.Params is null )) { if (descriptors.Default.IsDelegatingHandler) { _logger.LogTrace("Converting params for Notification {Method} to {Type}", notification.Method, descriptors.Default.Params.GetGenericArguments()[0].FullName); var o = notification.Params?.ToObject(descriptors.Default.Params.GetGenericArguments()[0], _serializer.JsonSerializer); - @params = Activator.CreateInstance(descriptors.Default.Params, new object[] {o}); + @params = Activator.CreateInstance(descriptors.Default.Params, o); } else { @@ -76,21 +77,25 @@ static async Task InnerRoute(IServiceScopeFactory serviceScopeFactory, TDescript public virtual async Task RouteRequest(IRequestDescriptor descriptors, Request request, CancellationToken token) { using var debug = _logger.TimeDebug("Routing Request ({Id}) {Method}", request.Id, request.Method); - using var _ = _logger.BeginScope(new[] { - new KeyValuePair("Id", request.Id?.ToString()), - new KeyValuePair("Method", request.Method), - new KeyValuePair("Params", request.Params?.ToString()) - }); + using var _ = _logger.BeginScope( + new[] { + new KeyValuePair("Id", request.Id?.ToString()), + new KeyValuePair("Method", request.Method), + new KeyValuePair("Params", request.Params?.ToString()) + } + ); object @params = null; try { if (descriptors.Default.IsDelegatingHandler) { - _logger.LogTrace("Converting params for Request ({Id}) {Method} to {Type}", request.Id, request.Method, - descriptors.Default.Params.GetGenericArguments()[0].FullName); + _logger.LogTrace( + "Converting params for Request ({Id}) {Method} to {Type}", request.Id, request.Method, + descriptors.Default.Params.GetGenericArguments()[0].FullName + ); var o = request.Params?.ToObject(descriptors.Default.Params.GetGenericArguments()[0], _serializer.JsonSerializer); - @params = Activator.CreateInstance(descriptors.Default.Params, new object[] {o}); + @params = Activator.CreateInstance(descriptors.Default.Params, o); } else { @@ -118,16 +123,17 @@ public virtual async Task RouteRequest(IRequestDescriptor).MakeGenericType(descriptors.Default.Response), - new object[] {responses.Select(z => z.Response.Result)} + typeof(AggregateResponse<>).MakeGenericType(descriptors.Default.Response), responses.Select(z => z.Response.Result) ); return new OutgoingResponse(request.Id, response, request); } return await InnerRoute(_serviceScopeFactory, request, descriptors.Default, @params, token, _logger); - static async Task InnerRoute(IServiceScopeFactory serviceScopeFactory, Request request, TDescriptor descriptor, object @params, CancellationToken token, - ILogger logger) + static async Task InnerRoute( + IServiceScopeFactory serviceScopeFactory, Request request, TDescriptor descriptor, object @params, CancellationToken token, + ILogger logger + ) { using var scope = serviceScopeFactory.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); @@ -145,8 +151,8 @@ static async Task InnerRoute(IServiceScopeFactory serviceScopeFac if (result.GetType().GetTypeInfo().IsGenericType) { var property = typeof(Task<>) - .MakeGenericType(result.GetType().GetTypeInfo().GetGenericArguments()[0]).GetTypeInfo() - .GetProperty(nameof(Task.Result), BindingFlags.Public | BindingFlags.Instance); + .MakeGenericType(result.GetType().GetTypeInfo().GetGenericArguments()[0]).GetTypeInfo() + .GetProperty(nameof(Task.Result), BindingFlags.Public | BindingFlags.Instance); responseValue = property.GetValue(result); if (responseValue?.GetType() == typeof(Unit)) @@ -158,7 +164,7 @@ static async Task InnerRoute(IServiceScopeFactory serviceScopeFac } return new OutgoingResponse(request.Id, responseValue, request); - return new JsonRpc.Client.OutgoingResponse(request.Id, responseValue, request); + return new OutgoingResponse(request.Id, responseValue, request); } } @@ -166,48 +172,40 @@ static async Task InnerRoute(IServiceScopeFactory serviceScopeFac public abstract IRequestDescriptor GetDescriptors(Request request); private static readonly MethodInfo SendRequestUnit = typeof(RequestRouterBase) - .GetMethods(BindingFlags.NonPublic | BindingFlags.Static) - .Where(x => x.Name == nameof(SendRequest)) - .First(x => x.GetGenericArguments().Length == 1); + .GetMethods(BindingFlags.NonPublic | BindingFlags.Static) + .Where(x => x.Name == nameof(SendRequest)) + .First(x => x.GetGenericArguments().Length == 1); private static readonly MethodInfo SendRequestResponse = typeof(RequestRouterBase) - .GetMethods(BindingFlags.NonPublic | BindingFlags.Static) - .Where(x => x.Name == nameof(SendRequest)) - .First(x => x.GetGenericArguments().Length == 2); + .GetMethods(BindingFlags.NonPublic | BindingFlags.Static) + .Where(x => x.Name == nameof(SendRequest)) + .First(x => x.GetGenericArguments().Length == 2); - public static Task HandleNotification(IMediator mediator, IHandlerDescriptor handler, object @params, CancellationToken token) - { - return (Task) SendRequestUnit - .MakeGenericMethod(handler.Params ?? typeof(EmptyRequest)) - .Invoke(null, new object[] {mediator, @params, token}); - } + public static Task HandleNotification(IMediator mediator, IHandlerDescriptor handler, object @params, CancellationToken token) => + (Task) SendRequestUnit + .MakeGenericMethod(handler.Params ?? typeof(EmptyRequest)) + .Invoke(null, new[] { mediator, @params, token }); public static Task HandleRequest(IMediator mediator, IHandlerDescriptor descriptor, object @params, CancellationToken token) { if (!descriptor.HasReturnType) { return (Task) SendRequestUnit - .MakeGenericMethod(descriptor.Params) - .Invoke(null, new object[] {mediator, @params, token}); - } - else - { - return (Task) SendRequestResponse - .MakeGenericMethod(descriptor.Params, descriptor.Response) - .Invoke(null, new object[] {mediator, @params, token}); + .MakeGenericMethod(descriptor.Params) + .Invoke(null, new[] { mediator, @params, token }); } + + return (Task) SendRequestResponse + .MakeGenericMethod(descriptor.Params, descriptor.Response) + .Invoke(null, new[] { mediator, @params, token }); } private static Task SendRequest(IMediator mediator, T request, CancellationToken token) - where T : IRequest - { - return mediator.Send(request, token); - } + where T : IRequest => + mediator.Send(request, token); private static Task SendRequest(IMediator mediator, T request, CancellationToken token) - where T : IRequest - { - return mediator.Send(request, token); - } + where T : IRequest => + mediator.Send(request, token); } } diff --git a/src/JsonRpc/ResponseRouter.cs b/src/JsonRpc/ResponseRouter.cs index 11be03e58..46f15d419 100644 --- a/src/JsonRpc/ResponseRouter.cs +++ b/src/JsonRpc/ResponseRouter.cs @@ -1,11 +1,10 @@ using System; using System.Collections.Concurrent; -using System.Reflection; using System.Threading; using System.Threading.Tasks; using MediatR; using Newtonsoft.Json.Linq; -using OmniSharp.Extensions.JsonRpc.Server; +using OmniSharp.Extensions.JsonRpc.Client; namespace OmniSharp.Extensions.JsonRpc { @@ -23,40 +22,29 @@ public ResponseRouter(IOutputHandler outputHandler, ISerializer serializer) Serializer = serializer; } - public void SendNotification(string method) - { - OutputHandler.Send(new Client.OutgoingNotification() { - Method = method - }); - } + public void SendNotification(string method) => + OutputHandler.Send( + new OutgoingNotification { + Method = method + } + ); - public void SendNotification(string method, T @params) - { - OutputHandler.Send(new Client.OutgoingNotification() { - Method = method, - Params = @params - }); - } + public void SendNotification(string method, T @params) => + OutputHandler.Send( + 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) - { - return SendRequest(GetMethodName(@params.GetType()), @params).Returning(cancellationToken); - } + public Task SendRequest(IRequest @params, CancellationToken cancellationToken) => + SendRequest(GetMethodName(@params.GetType()), @params).Returning(cancellationToken); - public IResponseRouterReturns SendRequest(string method) - { - return new ResponseRouterReturnsImpl(this, method, new object()); - } + public IResponseRouterReturns SendRequest(string method) => new ResponseRouterReturnsImpl(this, method, new object()); - public IResponseRouterReturns SendRequest(string method, T @params) - { - return new ResponseRouterReturnsImpl(this, method, @params); - } + public IResponseRouterReturns SendRequest(string method, T @params) => new ResponseRouterReturnsImpl(this, method, @params); public (string method, TaskCompletionSource pendingTask) GetRequest(long id) { @@ -64,12 +52,10 @@ public IResponseRouterReturns SendRequest(string method, T @params) return source; } - private string GetMethodName(Type type) - { - return HandlerTypeDescriptorHelper.GetMethodName(type) ?? throw new NotSupportedException($"Unable to infer method name for type {type.FullName}"); - } + private string GetMethodName(Type type) => + HandlerTypeDescriptorHelper.GetMethodName(type) ?? throw new NotSupportedException($"Unable to infer method name for type {type.FullName}"); - class ResponseRouterReturnsImpl : IResponseRouterReturns + private class ResponseRouterReturnsImpl : IResponseRouterReturns { private readonly ResponseRouter _router; private readonly string _method; @@ -86,19 +72,23 @@ public async Task Returning(CancellationToken cancellation { var nextId = _router.Serializer.GetNextId(); var tcs = new TaskCompletionSource(); - _router.Requests.TryAdd(nextId, (_method, tcs)); + _router.Requests.TryAdd(nextId, ( _method, tcs )); cancellationToken.ThrowIfCancellationRequested(); - _router.OutputHandler.Send(new Client.OutgoingRequest() { - Method = _method, - Params = _params, - Id = nextId - }); - cancellationToken.Register(() => { - if (tcs.Task.IsCompleted) return; - _router.CancelRequest(new CancelParams() {Id = nextId}); - }); + _router.OutputHandler.Send( + new OutgoingRequest { + Method = _method, + Params = _params, + Id = nextId + } + ); + cancellationToken.Register( + () => { + if (tcs.Task.IsCompleted) return; + _router.CancelRequest(new CancelParams { Id = nextId }); + } + ); try { @@ -116,10 +106,7 @@ public async Task Returning(CancellationToken cancellation } } - public async Task ReturningVoid(CancellationToken cancellationToken) - { - await Returning(cancellationToken); - } + public async Task ReturningVoid(CancellationToken cancellationToken) => await Returning(cancellationToken); } } } diff --git a/src/JsonRpc/RpcError.cs b/src/JsonRpc/RpcError.cs index abac1496b..754262036 100644 --- a/src/JsonRpc/RpcError.cs +++ b/src/JsonRpc/RpcError.cs @@ -23,7 +23,6 @@ public RpcError(object id, string method, ErrorMessage message) public object Id { get; } public ErrorMessage Error { get; } - [JsonIgnore] - public string Method { get; } + [JsonIgnore] public string Method { get; } } } diff --git a/src/JsonRpc/SchedulerDelegate.cs b/src/JsonRpc/SchedulerDelegate.cs index 1e263c327..285a32b2d 100644 --- a/src/JsonRpc/SchedulerDelegate.cs +++ b/src/JsonRpc/SchedulerDelegate.cs @@ -4,5 +4,5 @@ namespace OmniSharp.Extensions.JsonRpc { - delegate IObservable SchedulerDelegate(IObservable contentModifiedToken, IScheduler scheduler); + internal delegate IObservable SchedulerDelegate(IObservable contentModifiedToken, IScheduler scheduler); } diff --git a/src/JsonRpc/SerialAttribute.cs b/src/JsonRpc/SerialAttribute.cs index da6803fb2..538f3fa96 100644 --- a/src/JsonRpc/SerialAttribute.cs +++ b/src/JsonRpc/SerialAttribute.cs @@ -2,6 +2,8 @@ { public sealed class SerialAttribute : ProcessAttribute { - public SerialAttribute() : base(RequestProcessType.Serial) { } + public SerialAttribute() : base(RequestProcessType.Serial) + { + } } -} \ No newline at end of file +} diff --git a/src/JsonRpc/SerialRequestProcessIdentifier.cs b/src/JsonRpc/SerialRequestProcessIdentifier.cs index 94ff5a617..8f1fbe172 100644 --- a/src/JsonRpc/SerialRequestProcessIdentifier.cs +++ b/src/JsonRpc/SerialRequestProcessIdentifier.cs @@ -2,9 +2,6 @@ namespace OmniSharp.Extensions.JsonRpc { public class SerialRequestProcessIdentifier : IRequestProcessIdentifier { - public RequestProcessType Identify(IHandlerDescriptor descriptor) - { - return descriptor.RequestProcessType ?? RequestProcessType.Serial; - } + public RequestProcessType Identify(IHandlerDescriptor descriptor) => descriptor.RequestProcessType ?? RequestProcessType.Serial; } } diff --git a/src/JsonRpc/Serialization/Converters/AggregateConverter.cs b/src/JsonRpc/Serialization/Converters/AggregateConverter.cs index b2c18ec48..f783ea32d 100644 --- a/src/JsonRpc/Serialization/Converters/AggregateConverter.cs +++ b/src/JsonRpc/Serialization/Converters/AggregateConverter.cs @@ -1,6 +1,5 @@ using System; using System.Collections; -using System.Collections.Generic; using Newtonsoft.Json; namespace OmniSharp.Extensions.JsonRpc.Serialization.Converters @@ -17,11 +16,13 @@ public override void WriteJson(JsonWriter writer, AggregateResponse value, Js serializer.Serialize(writer, v); } } + writer.WriteEndArray(); } public override bool CanRead => false; - public override AggregateResponse ReadJson(JsonReader reader, Type objectType, AggregateResponse existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override AggregateResponse ReadJson(JsonReader reader, Type objectType, AggregateResponse existingValue, bool hasExistingValue, JsonSerializer serializer) => + throw new NotImplementedException(); } } diff --git a/src/JsonRpc/Serialization/Converters/ClientNotificationConverter.cs b/src/JsonRpc/Serialization/Converters/ClientNotificationConverter.cs index a25783a32..14561083c 100644 --- a/src/JsonRpc/Serialization/Converters/ClientNotificationConverter.cs +++ b/src/JsonRpc/Serialization/Converters/ClientNotificationConverter.cs @@ -7,11 +7,12 @@ namespace OmniSharp.Extensions.JsonRpc.Serialization.Converters public class ClientNotificationConverter : JsonConverter { public override bool CanRead => false; - public override OutgoingNotification ReadJson(JsonReader reader, Type objectType, OutgoingNotification existingValue, - bool hasExistingValue, JsonSerializer serializer) - { + + public override OutgoingNotification ReadJson( + JsonReader reader, Type objectType, OutgoingNotification existingValue, + bool hasExistingValue, JsonSerializer serializer + ) => throw new NotImplementedException(); - } public override void WriteJson(JsonWriter writer, OutgoingNotification value, JsonSerializer serializer) { @@ -25,6 +26,7 @@ public override void WriteJson(JsonWriter writer, OutgoingNotification value, Js writer.WritePropertyName("params"); serializer.Serialize(writer, value.Params); } + writer.WriteEndObject(); } } diff --git a/src/JsonRpc/Serialization/Converters/ClientRequestConverter.cs b/src/JsonRpc/Serialization/Converters/ClientRequestConverter.cs index 4a2b3b7f5..edf7863f0 100644 --- a/src/JsonRpc/Serialization/Converters/ClientRequestConverter.cs +++ b/src/JsonRpc/Serialization/Converters/ClientRequestConverter.cs @@ -7,11 +7,12 @@ namespace OmniSharp.Extensions.JsonRpc.Serialization.Converters public class ClientRequestConverter : JsonConverter { public override bool CanRead => false; - public override OutgoingRequest ReadJson(JsonReader reader, Type objectType, OutgoingRequest existingValue, - bool hasExistingValue, JsonSerializer serializer) - { + + public override OutgoingRequest ReadJson( + JsonReader reader, Type objectType, OutgoingRequest existingValue, + bool hasExistingValue, JsonSerializer serializer + ) => throw new NotImplementedException(); - } public override void WriteJson(JsonWriter writer, OutgoingRequest value, JsonSerializer serializer) { @@ -27,6 +28,7 @@ public override void WriteJson(JsonWriter writer, OutgoingRequest value, JsonSer writer.WritePropertyName("params"); serializer.Serialize(writer, value.Params); } + writer.WriteEndObject(); } } diff --git a/src/JsonRpc/Serialization/Converters/ClientResponseConverter.cs b/src/JsonRpc/Serialization/Converters/ClientResponseConverter.cs index c32468419..b51a80f3b 100644 --- a/src/JsonRpc/Serialization/Converters/ClientResponseConverter.cs +++ b/src/JsonRpc/Serialization/Converters/ClientResponseConverter.cs @@ -7,11 +7,12 @@ namespace OmniSharp.Extensions.JsonRpc.Serialization.Converters public class ClientResponseConverter : JsonConverter { public override bool CanRead => false; - public override OutgoingResponse ReadJson(JsonReader reader, Type objectType, OutgoingResponse existingValue, - bool hasExistingValue, JsonSerializer serializer) - { + + public override OutgoingResponse ReadJson( + JsonReader reader, Type objectType, OutgoingResponse existingValue, + bool hasExistingValue, JsonSerializer serializer + ) => throw new NotImplementedException(); - } public override void WriteJson(JsonWriter writer, OutgoingResponse value, JsonSerializer serializer) { @@ -25,9 +26,11 @@ public override void WriteJson(JsonWriter writer, OutgoingResponse value, JsonSe { serializer.Serialize(writer, value.Result); } - else{ + else + { writer.WriteNull(); } + writer.WriteEndObject(); } } diff --git a/src/JsonRpc/Serialization/Converters/ErrorMessageConverter.cs b/src/JsonRpc/Serialization/Converters/ErrorMessageConverter.cs index ba4ef61e5..74471f7ef 100644 --- a/src/JsonRpc/Serialization/Converters/ErrorMessageConverter.cs +++ b/src/JsonRpc/Serialization/Converters/ErrorMessageConverter.cs @@ -16,12 +16,14 @@ public override void WriteJson(JsonWriter writer, ErrorMessage value, JsonSerial writer.WritePropertyName("data"); serializer.Serialize(writer, value.Data); } + writer.WritePropertyName("message"); writer.WriteValue(value.Message); writer.WriteEndObject(); } - public override ErrorMessage ReadJson(JsonReader reader, Type objectType, ErrorMessage existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override ErrorMessage ReadJson(JsonReader reader, Type objectType, ErrorMessage existingValue, bool hasExistingValue, JsonSerializer serializer) => + throw new NotImplementedException(); public override bool CanRead => false; } diff --git a/src/JsonRpc/Serialization/Converters/RpcErrorConverter.cs b/src/JsonRpc/Serialization/Converters/RpcErrorConverter.cs index f7c4aa185..f0e747fda 100644 --- a/src/JsonRpc/Serialization/Converters/RpcErrorConverter.cs +++ b/src/JsonRpc/Serialization/Converters/RpcErrorConverter.cs @@ -17,15 +17,17 @@ public override void WriteJson(JsonWriter writer, RpcError value, JsonSerializer writer.WritePropertyName("id"); writer.WriteValue(value.Id); } + writer.WritePropertyName("error"); serializer.Serialize(writer, value.Error); writer.WriteEndObject(); } - public override RpcError ReadJson(JsonReader reader, Type objectType, RpcError existingValue, - bool hasExistingValue, JsonSerializer serializer) + public override RpcError ReadJson( + JsonReader reader, Type objectType, RpcError existingValue, + bool hasExistingValue, JsonSerializer serializer + ) { - var obj = JObject.Load(reader); object requestId = null; @@ -40,7 +42,7 @@ public override RpcError ReadJson(JsonReader reader, Type objectType, RpcError e if (obj.TryGetValue("error", out var dataToken)) { var errorMessageType = typeof(ErrorMessage); - data = dataToken.ToObject< ErrorMessage>(serializer); + data = dataToken.ToObject(serializer); } return new RpcError(requestId, data); diff --git a/src/JsonRpc/Serialization/SerializerBase.cs b/src/JsonRpc/Serialization/SerializerBase.cs index cdb584a66..369724e68 100644 --- a/src/JsonRpc/Serialization/SerializerBase.cs +++ b/src/JsonRpc/Serialization/SerializerBase.cs @@ -8,7 +8,7 @@ namespace OmniSharp.Extensions.JsonRpc.Serialization { public abstract class SerializerBase : ISerializer { - private long _id = 0; + private long _id; protected virtual JsonSerializer CreateSerializer() { @@ -33,34 +33,23 @@ protected internal static void ReplaceConverter(ICollection co foreach (var converter in existingConverters) converters.Remove(converter); } + converters.Add(item); } private JsonSerializer _jsonSerializer; - public JsonSerializer JsonSerializer => _jsonSerializer ?? ( CreateSerializer() ); + public JsonSerializer JsonSerializer => _jsonSerializer ?? CreateSerializer(); private JsonSerializerSettings _settings; - public JsonSerializerSettings Settings => _settings ?? ( CreateSerializerSettings() ); + public JsonSerializerSettings Settings => _settings ?? CreateSerializerSettings(); - public string SerializeObject(object value) - { - return JsonConvert.SerializeObject(value, Settings); - } + public string SerializeObject(object value) => JsonConvert.SerializeObject(value, Settings); - public object DeserializeObject(string json, Type type) - { - return JsonConvert.DeserializeObject(json, type, Settings); - } + public object DeserializeObject(string json, Type type) => JsonConvert.DeserializeObject(json, type, Settings); - public T DeserializeObject(string json) - { - return JsonConvert.DeserializeObject(json, Settings); - } - public long GetNextId() - { - return Interlocked.Increment(ref _id); - } + public T DeserializeObject(string json) => JsonConvert.DeserializeObject(json, Settings); + public long GetNextId() => Interlocked.Increment(ref _id); protected abstract void AddOrReplaceConverters(ICollection converters); } } diff --git a/src/JsonRpc/Server/ContentModifiedException.cs b/src/JsonRpc/Server/ContentModifiedException.cs index b544c6f89..237e9703e 100644 --- a/src/JsonRpc/Server/ContentModifiedException.cs +++ b/src/JsonRpc/Server/ContentModifiedException.cs @@ -5,17 +5,17 @@ namespace OmniSharp.Extensions.JsonRpc.Server { /// - /// Exception raised when request parameters are invalid according to the target method. + /// Exception raised when request parameters are invalid according to the target method. /// [Serializable] public class ContentModifiedException : TaskCanceledException, IRequestException { /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// public ContentModifiedException(object requestId) : this(ErrorCodes.ContentModified, requestId.ToString(), "Content not modified.", null) @@ -23,13 +23,13 @@ public ContentModifiedException(object requestId) } /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// /// - /// The exception that caused this exception to be raised. + /// The exception that caused this exception to be raised. /// public ContentModifiedException(object requestId, Exception inner) : this(ErrorCodes.ContentModified, requestId.ToString(), "Content not modified.", inner) @@ -37,19 +37,19 @@ public ContentModifiedException(object requestId, Exception inner) } /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC error code. + /// The LSP / JSON-RPC error code. /// /// - /// The exception message. + /// The exception message. /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// /// - /// The exception that caused this exception to be raised. + /// The exception that caused this exception to be raised. /// public ContentModifiedException(int errorCode, string message, string requestId, Exception inner) : base(message, inner) { @@ -58,13 +58,13 @@ public ContentModifiedException(int errorCode, string message, string requestId, } /// - /// Serialisation constructor. + /// Serialisation constructor. /// /// - /// The serialisation data-store. + /// The serialisation data-store. /// /// - /// The serialisation streaming context. + /// The serialisation streaming context. /// protected ContentModifiedException(SerializationInfo info, StreamingContext context) { @@ -73,17 +73,17 @@ protected ContentModifiedException(SerializationInfo info, StreamingContext cont } /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// public object RequestId { get; } /// - /// The LSP / JSON-RPC error code. + /// The LSP / JSON-RPC error code. /// public int ErrorCode { get; } /// - /// The request Id used when no valid request Id was supplied. + /// The request Id used when no valid request Id was supplied. /// public const string UnknownRequestId = "(unknown)"; } diff --git a/src/JsonRpc/Server/ErrorCodes.cs b/src/JsonRpc/Server/ErrorCodes.cs index 3368bc4e4..a33a53c7f 100644 --- a/src/JsonRpc/Server/ErrorCodes.cs +++ b/src/JsonRpc/Server/ErrorCodes.cs @@ -1,12 +1,12 @@ namespace OmniSharp.Extensions.JsonRpc.Server { /// - /// Well-known LSP error codes. + /// Well-known LSP error codes. /// public static class ErrorCodes { /// - /// No error code was supplied. + /// No error code was supplied. /// public const int UnknownErrorCode = -32001; @@ -16,43 +16,43 @@ public static class ErrorCodes public const int Exception = -32050; /// - /// Server has not been initialised. + /// Server has not been initialised. /// public const int ServerNotInitialized = -32002; /// - /// Method not found. + /// Method not found. /// public const int MethodNotSupported = -32601; /// - /// Invalid request. + /// Invalid request. /// public const int InvalidRequest = -32600; /// - /// Invalid request parameters. + /// Invalid request parameters. /// public const int InvalidParameters = -32602; /// - /// Internal error. + /// Internal error. /// public const int InternalError = -32603; /// - /// Unable to parse request. + /// Unable to parse request. /// public const int ParseError = -32700; /// - /// Request was cancelled. + /// Request was cancelled. /// public const int RequestCancelled = -32800; /// - /// Request was cancelled. + /// Request was cancelled. /// public const int ContentModified = -32801; } -} \ No newline at end of file +} diff --git a/src/JsonRpc/Server/IRequestException.cs b/src/JsonRpc/Server/IRequestException.cs index 352edb1f3..9403200a8 100644 --- a/src/JsonRpc/Server/IRequestException.cs +++ b/src/JsonRpc/Server/IRequestException.cs @@ -3,12 +3,12 @@ namespace OmniSharp.Extensions.JsonRpc.Server public interface IRequestException { /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// public object RequestId { get; } /// - /// The LSP / JSON-RPC error code. + /// The LSP / JSON-RPC error code. /// public int ErrorCode { get; } } diff --git a/src/JsonRpc/Server/InternalErrorException.cs b/src/JsonRpc/Server/InternalErrorException.cs index 3a655ad56..51d29c588 100644 --- a/src/JsonRpc/Server/InternalErrorException.cs +++ b/src/JsonRpc/Server/InternalErrorException.cs @@ -4,17 +4,17 @@ namespace OmniSharp.Extensions.JsonRpc.Server { /// - /// Exception raised when an internal error has occurred in the language server. + /// Exception raised when an internal error has occurred in the language server. /// [Serializable] public class InternalErrorException : RequestException { /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// /// public InternalErrorException(object requestId, string message) @@ -23,13 +23,13 @@ public InternalErrorException(object requestId, string message) } /// - /// Serialisation constructor. + /// Serialisation constructor. /// /// - /// The serialisation data-store. + /// The serialisation data-store. /// /// - /// The serialisation streaming context. + /// The serialisation streaming context. /// protected InternalErrorException(SerializationInfo info, StreamingContext context) : base(info, context) diff --git a/src/JsonRpc/Server/InvalidParametersException.cs b/src/JsonRpc/Server/InvalidParametersException.cs index 0d86f4b98..46c3c164d 100644 --- a/src/JsonRpc/Server/InvalidParametersException.cs +++ b/src/JsonRpc/Server/InvalidParametersException.cs @@ -4,17 +4,17 @@ namespace OmniSharp.Extensions.JsonRpc.Server { /// - /// Exception raised when request parameters are invalid according to the target method. + /// Exception raised when request parameters are invalid according to the target method. /// [Serializable] public class InvalidParametersException : RequestException { /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// public InvalidParametersException(object requestId) : base(ErrorCodes.InvalidParameters, requestId, "Invalid parameters.") @@ -22,13 +22,13 @@ public InvalidParametersException(object requestId) } /// - /// Serialisation constructor. + /// Serialisation constructor. /// /// - /// The serialisation data-store. + /// The serialisation data-store. /// /// - /// The serialisation streaming context. + /// The serialisation streaming context. /// protected InvalidParametersException(SerializationInfo info, StreamingContext context) : base(info, context) diff --git a/src/JsonRpc/Server/InvalidRequestException.cs b/src/JsonRpc/Server/InvalidRequestException.cs index 3d9740654..16b287774 100644 --- a/src/JsonRpc/Server/InvalidRequestException.cs +++ b/src/JsonRpc/Server/InvalidRequestException.cs @@ -4,17 +4,17 @@ namespace OmniSharp.Extensions.JsonRpc.Server { /// - /// Exception raised an LSP request is invalid. + /// Exception raised an LSP request is invalid. /// [Serializable] public class InvalidRequestException : RequestException { /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// public InvalidRequestException(object requestId) : base(ErrorCodes.InvalidRequest, requestId, "Invalid request.") @@ -22,13 +22,13 @@ public InvalidRequestException(object requestId) } /// - /// Serialisation constructor. + /// Serialisation constructor. /// /// - /// The serialisation data-store. + /// The serialisation data-store. /// /// - /// The serialisation streaming context. + /// The serialisation streaming context. /// protected InvalidRequestException(SerializationInfo info, StreamingContext context) : base(info, context) diff --git a/src/JsonRpc/Server/JsonRpcException.cs b/src/JsonRpc/Server/JsonRpcException.cs index f14f6832a..7d70d7db6 100644 --- a/src/JsonRpc/Server/JsonRpcException.cs +++ b/src/JsonRpc/Server/JsonRpcException.cs @@ -2,10 +2,7 @@ namespace OmniSharp.Extensions.JsonRpc.Server { public class JsonRpcException : RequestException { - public JsonRpcException(int code, object requestId, string message, string data) : base(code, requestId, message) - { - Error = data; - } + public JsonRpcException(int code, object requestId, string message, string data) : base(code, requestId, message) => Error = data; public string Error { get; } } diff --git a/src/JsonRpc/Server/Messages/IErrorMessage.cs b/src/JsonRpc/Server/Messages/IErrorMessage.cs index 071e8ada2..d496eecd7 100644 --- a/src/JsonRpc/Server/Messages/IErrorMessage.cs +++ b/src/JsonRpc/Server/Messages/IErrorMessage.cs @@ -11,4 +11,4 @@ public interface IErrorMessage [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] object Data { get; } } -} \ No newline at end of file +} diff --git a/src/JsonRpc/Server/Messages/InternalError.cs b/src/JsonRpc/Server/Messages/InternalError.cs index 3f8383e6e..1bfc3318e 100644 --- a/src/JsonRpc/Server/Messages/InternalError.cs +++ b/src/JsonRpc/Server/Messages/InternalError.cs @@ -2,8 +2,16 @@ namespace OmniSharp.Extensions.JsonRpc.Server.Messages { public class InternalError : RpcError { - public InternalError() : this(null, null) { } - public InternalError(object id, string method) : base(id, method, new ErrorMessage(ErrorCodes.InternalError, "Internal Error")) { } - public InternalError(object id, string method, string message) : base(id, method, new ErrorMessage(ErrorCodes.InternalError, "Internal Error - " + message)) { } + public InternalError() : this(null, null) + { + } + + public InternalError(object id, string method) : base(id, method, new ErrorMessage(ErrorCodes.InternalError, "Internal Error")) + { + } + + public InternalError(object id, string method, string message) : base(id, method, new ErrorMessage(ErrorCodes.InternalError, "Internal Error - " + message)) + { + } } } diff --git a/src/JsonRpc/Server/Messages/InvalidParams.cs b/src/JsonRpc/Server/Messages/InvalidParams.cs index 69b2ac742..5cae242b7 100644 --- a/src/JsonRpc/Server/Messages/InvalidParams.cs +++ b/src/JsonRpc/Server/Messages/InvalidParams.cs @@ -2,7 +2,12 @@ namespace OmniSharp.Extensions.JsonRpc.Server.Messages { public class InvalidParams : RpcError { - public InvalidParams(string method) : this(null, method) { } - public InvalidParams(object id, string method) : base(id, method, new ErrorMessage(-32602, "Invalid params")) { } + public InvalidParams(string method) : this(null, method) + { + } + + public InvalidParams(object id, string method) : base(id, method, new ErrorMessage(-32602, "Invalid params")) + { + } } } diff --git a/src/JsonRpc/Server/Messages/InvalidRequest.cs b/src/JsonRpc/Server/Messages/InvalidRequest.cs index 5547eef05..5905c3b6a 100644 --- a/src/JsonRpc/Server/Messages/InvalidRequest.cs +++ b/src/JsonRpc/Server/Messages/InvalidRequest.cs @@ -2,8 +2,16 @@ namespace OmniSharp.Extensions.JsonRpc.Server.Messages { public class InvalidRequest : RpcError { - public InvalidRequest(string method) : base(null, method, new ErrorMessage(-32600, $"Invalid Request")) { } - public InvalidRequest(string method, string message) : base(null, method, new ErrorMessage(-32600, $"Invalid Request - {message}")) { } - public InvalidRequest(object id, string method, string message) : base(id, method, new ErrorMessage(-32600, $"Invalid Request - {message}")) { } + public InvalidRequest(string method) : base(null, method, new ErrorMessage(-32600, "Invalid Request")) + { + } + + public InvalidRequest(string method, string message) : base(null, method, new ErrorMessage(-32600, $"Invalid Request - {message}")) + { + } + + public InvalidRequest(object id, string method, string message) : base(id, method, new ErrorMessage(-32600, $"Invalid Request - {message}")) + { + } } } diff --git a/src/JsonRpc/Server/Messages/MethodNotFound.cs b/src/JsonRpc/Server/Messages/MethodNotFound.cs index 1902af6bd..d191a9eac 100644 --- a/src/JsonRpc/Server/Messages/MethodNotFound.cs +++ b/src/JsonRpc/Server/Messages/MethodNotFound.cs @@ -2,6 +2,8 @@ { public class MethodNotFound : RpcError { - public MethodNotFound(object id, string method) : base(id, method, new ErrorMessage(-32601, $"Method not found - {method}")) { } + public MethodNotFound(object id, string method) : base(id, method, new ErrorMessage(-32601, $"Method not found - {method}")) + { + } } } diff --git a/src/JsonRpc/Server/Messages/ParseError.cs b/src/JsonRpc/Server/Messages/ParseError.cs index 71794d423..88975d421 100644 --- a/src/JsonRpc/Server/Messages/ParseError.cs +++ b/src/JsonRpc/Server/Messages/ParseError.cs @@ -2,7 +2,12 @@ { public class ParseError : RpcError { - public ParseError(string method) : this(null, method) { } - public ParseError(object id, string method) : base(id, method, new ErrorMessage(-32700, "Parse Error")) { } + public ParseError(string method) : this(null, method) + { + } + + public ParseError(object id, string method) : base(id, method, new ErrorMessage(-32700, "Parse Error")) + { + } } } diff --git a/src/JsonRpc/Server/MethodNotSupportedException.cs b/src/JsonRpc/Server/MethodNotSupportedException.cs index f4dbae165..eabb270fd 100644 --- a/src/JsonRpc/Server/MethodNotSupportedException.cs +++ b/src/JsonRpc/Server/MethodNotSupportedException.cs @@ -4,50 +4,46 @@ namespace OmniSharp.Extensions.JsonRpc.Server { /// - /// Exception raised when an LSP request is made for a method not supported by the remote process. + /// Exception raised when an LSP request is made for a method not supported by the remote process. /// [Serializable] public class MethodNotSupportedException : RequestException { /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// /// - /// The name of the target method. + /// The name of the target method. /// public MethodNotSupportedException(object requestId, string method) - : base(ErrorCodes.MethodNotSupported, requestId, $"Method not found: '{method}'.") - { + : base(ErrorCodes.MethodNotSupported, requestId, $"Method not found: '{method}'.") => Method = !string.IsNullOrWhiteSpace(method) ? method : "(unknown)"; - } /// - /// Serialisation constructor. + /// Serialisation constructor. /// /// - /// The serialisation data-store. + /// The serialisation data-store. /// /// - /// The serialisation streaming context. + /// The serialisation streaming context. /// protected MethodNotSupportedException(SerializationInfo info, StreamingContext context) - : base(info, context) - { + : base(info, context) => Method = info.GetString("Method"); - } /// - /// Get exception data for serialisation. + /// Get exception data for serialisation. /// /// - /// The serialisation data-store. + /// The serialisation data-store. /// /// - /// The serialisation streaming context. + /// The serialisation streaming context. /// public override void GetObjectData(SerializationInfo info, StreamingContext context) { @@ -57,7 +53,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } /// - /// The name of the method that was not supported by the remote process. + /// The name of the method that was not supported by the remote process. /// public string Method { get; } } diff --git a/src/JsonRpc/Server/Notification.cs b/src/JsonRpc/Server/Notification.cs index 65d4abea6..2761851ba 100644 --- a/src/JsonRpc/Server/Notification.cs +++ b/src/JsonRpc/Server/Notification.cs @@ -6,7 +6,8 @@ public class Notification : IMethodWithParams { public Notification( string method, - JToken @params) + JToken @params + ) { Method = method; Params = @params; diff --git a/src/JsonRpc/Server/ParseErrorException.cs b/src/JsonRpc/Server/ParseErrorException.cs index 7287cb135..382c2fa2b 100644 --- a/src/JsonRpc/Server/ParseErrorException.cs +++ b/src/JsonRpc/Server/ParseErrorException.cs @@ -4,31 +4,31 @@ namespace OmniSharp.Extensions.JsonRpc.Server { /// - /// Exception raised when an LSP request could not be parsed. + /// Exception raised when an LSP request could not be parsed. /// [Serializable] public class ParseErrorException : RequestException { /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// public ParseErrorException(object requestId) - : base( ErrorCodes.ParseError, requestId, "Error parsing request.") + : base(ErrorCodes.ParseError, requestId, "Error parsing request.") { } /// - /// Serialisation constructor. + /// Serialisation constructor. /// /// - /// The serialisation data-store. + /// The serialisation data-store. /// /// - /// The serialisation streaming context. + /// The serialisation streaming context. /// protected ParseErrorException(SerializationInfo info, StreamingContext context) : base(info, context) diff --git a/src/JsonRpc/Server/Renor.cs b/src/JsonRpc/Server/Renor.cs index a0362e522..7811e0a36 100644 --- a/src/JsonRpc/Server/Renor.cs +++ b/src/JsonRpc/Server/Renor.cs @@ -50,29 +50,14 @@ internal Renor(ResponseBase response) public bool IsResponse => Response != null; public ResponseBase Response { get; } - public static implicit operator Renor(Notification notification) - { - return new Renor(notification); - } + public static implicit operator Renor(Notification notification) => new Renor(notification); - public static implicit operator Renor(Request request) - { - return new Renor(request); - } + public static implicit operator Renor(Request request) => new Renor(request); - public static implicit operator Renor(RpcError error) - { - return new Renor(error); - } + public static implicit operator Renor(RpcError error) => new Renor(error); - public static implicit operator Renor(ServerResponse response) - { - return new Renor(response); - } + public static implicit operator Renor(ServerResponse response) => new Renor(response); - public static implicit operator Renor(ServerError response) - { - return new Renor(response); - } + public static implicit operator Renor(ServerError response) => new Renor(response); } } diff --git a/src/JsonRpc/Server/Request.cs b/src/JsonRpc/Server/Request.cs index 75405e36d..4feb64227 100644 --- a/src/JsonRpc/Server/Request.cs +++ b/src/JsonRpc/Server/Request.cs @@ -7,7 +7,8 @@ public class Request : IMethodWithParams public Request( object id, string method, - JToken @params) + JToken @params + ) { Id = id; Method = method; diff --git a/src/JsonRpc/Server/RequestCancelledException.cs b/src/JsonRpc/Server/RequestCancelledException.cs index de8600f5f..f1215d1fb 100644 --- a/src/JsonRpc/Server/RequestCancelledException.cs +++ b/src/JsonRpc/Server/RequestCancelledException.cs @@ -5,17 +5,17 @@ namespace OmniSharp.Extensions.JsonRpc.Server { /// - /// Exception raised when an LSP request is cancelled. + /// Exception raised when an LSP request is cancelled. /// [Serializable] public class RequestCancelledException : TaskCanceledException, IRequestException { /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// public RequestCancelledException(object requestId) : this(ErrorCodes.RequestCancelled, requestId.ToString(), "Request was cancelled.", null) @@ -23,13 +23,13 @@ public RequestCancelledException(object requestId) } /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// /// - /// The exception that caused this exception to be raised. + /// The exception that caused this exception to be raised. /// public RequestCancelledException(object requestId, Exception inner) : this(ErrorCodes.RequestCancelled, requestId.ToString(), "Request was cancelled.", inner) @@ -37,19 +37,19 @@ public RequestCancelledException(object requestId, Exception inner) } /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC error code. + /// The LSP / JSON-RPC error code. /// /// - /// The exception message. + /// The exception message. /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// /// - /// The exception that caused this exception to be raised. + /// The exception that caused this exception to be raised. /// public RequestCancelledException(int errorCode, string message, string requestId, Exception inner) : base(message, inner) { @@ -58,13 +58,13 @@ public RequestCancelledException(int errorCode, string message, string requestId } /// - /// Serialisation constructor. + /// Serialisation constructor. /// /// - /// The serialisation data-store. + /// The serialisation data-store. /// /// - /// The serialisation streaming context. + /// The serialisation streaming context. /// protected RequestCancelledException(SerializationInfo info, StreamingContext context) { @@ -73,17 +73,17 @@ protected RequestCancelledException(SerializationInfo info, StreamingContext con } /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// public object RequestId { get; } /// - /// The LSP / JSON-RPC error code. + /// The LSP / JSON-RPC error code. /// public int ErrorCode { get; } /// - /// The request Id used when no valid request Id was supplied. + /// The request Id used when no valid request Id was supplied. /// public const string UnknownRequestId = "(unknown)"; } diff --git a/src/JsonRpc/Server/RequestException.cs b/src/JsonRpc/Server/RequestException.cs index b50fa51aa..b5b44c9a6 100644 --- a/src/JsonRpc/Server/RequestException.cs +++ b/src/JsonRpc/Server/RequestException.cs @@ -4,27 +4,27 @@ namespace OmniSharp.Extensions.JsonRpc.Server { /// - /// Exception raised when a Language Server Protocol error is encountered while processing a request. + /// Exception raised when a Language Server Protocol error is encountered while processing a request. /// [Serializable] - public class RequestException: Exception, IRequestException + public class RequestException : Exception, IRequestException { /// - /// The request Id used when no valid request Id was supplied. + /// The request Id used when no valid request Id was supplied. /// public const string UnknownRequestId = "(unknown)"; /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC error code. + /// The LSP / JSON-RPC error code. /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// /// - /// The exception message. + /// The exception message. /// public RequestException(int errorCode, object requestId, string message) : base(message) { @@ -33,19 +33,19 @@ public RequestException(int errorCode, object requestId, string message) : base( } /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC error code. + /// The LSP / JSON-RPC error code. /// /// - /// The exception message. + /// The exception message. /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// /// - /// The exception that caused this exception to be raised. + /// The exception that caused this exception to be raised. /// public RequestException(int errorCode, string message, string requestId, Exception inner) : base(message, inner) { @@ -54,13 +54,13 @@ public RequestException(int errorCode, string message, string requestId, Excepti } /// - /// Serialisation constructor. + /// Serialisation constructor. /// /// - /// The serialisation data-store. + /// The serialisation data-store. /// /// - /// The serialisation streaming context. + /// The serialisation streaming context. /// protected RequestException(SerializationInfo info, StreamingContext context) { @@ -69,13 +69,13 @@ protected RequestException(SerializationInfo info, StreamingContext context) } /// - /// Get exception data for serialisation. + /// Get exception data for serialisation. /// /// - /// The serialisation data-store. + /// The serialisation data-store. /// /// - /// The serialisation streaming context. + /// The serialisation streaming context. /// public override void GetObjectData(SerializationInfo info, StreamingContext context) { @@ -86,12 +86,12 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// public object RequestId { get; } /// - /// The LSP / JSON-RPC error code. + /// The LSP / JSON-RPC error code. /// public int ErrorCode { get; } } diff --git a/src/JsonRpc/Server/ResponseBase.cs b/src/JsonRpc/Server/ResponseBase.cs index e0396c4ed..c1f7c1d1a 100644 --- a/src/JsonRpc/Server/ResponseBase.cs +++ b/src/JsonRpc/Server/ResponseBase.cs @@ -2,10 +2,7 @@ namespace OmniSharp.Extensions.JsonRpc.Server { public class ResponseBase { - public ResponseBase(object id) - { - Id = id; - } + public ResponseBase(object id) => Id = id; public object Id { get; set; } } diff --git a/src/JsonRpc/Server/ServerError.cs b/src/JsonRpc/Server/ServerError.cs index cf6e63f56..af353d8ec 100644 --- a/src/JsonRpc/Server/ServerError.cs +++ b/src/JsonRpc/Server/ServerError.cs @@ -2,15 +2,9 @@ namespace OmniSharp.Extensions.JsonRpc.Server { public class ServerError : ResponseBase { - public ServerError(ServerErrorResult result) : this(null, result) - { - Error = result; - } + public ServerError(ServerErrorResult result) : this(null, result) => Error = result; - public ServerError(object id, ServerErrorResult result) : base(id) - { - Error = result; - } + public ServerError(object id, ServerErrorResult result) : base(id) => Error = result; public ServerErrorResult Error { get; } } diff --git a/src/JsonRpc/Server/ServerErrorResult.cs b/src/JsonRpc/Server/ServerErrorResult.cs index f94910cdd..c817b30ce 100644 --- a/src/JsonRpc/Server/ServerErrorResult.cs +++ b/src/JsonRpc/Server/ServerErrorResult.cs @@ -12,6 +12,7 @@ public ServerErrorResult(int code, string message, JToken data) Message = message; Data = data; } + public ServerErrorResult(int code, string message) { Code = code; @@ -21,6 +22,7 @@ public ServerErrorResult(int code, string message) public int Code { get; set; } public string Message { get; set; } + [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public JToken Data { get; set; } } diff --git a/src/JsonRpc/Server/ServerNotInitializedException.cs b/src/JsonRpc/Server/ServerNotInitializedException.cs index 6c1efe8a7..3e43cd926 100644 --- a/src/JsonRpc/Server/ServerNotInitializedException.cs +++ b/src/JsonRpc/Server/ServerNotInitializedException.cs @@ -4,17 +4,17 @@ namespace OmniSharp.Extensions.JsonRpc.Server { /// - /// Exception raised when request parameters are invalid according to the target method. + /// Exception raised when request parameters are invalid according to the target method. /// [Serializable] public class ServerNotInitializedException : RequestException { /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// public ServerNotInitializedException(object requestId) : base(ErrorCodes.ServerNotInitialized, requestId, "Server not initialized.") @@ -22,13 +22,13 @@ public ServerNotInitializedException(object requestId) } /// - /// Serialisation constructor. + /// Serialisation constructor. /// /// - /// The serialisation data-store. + /// The serialisation data-store. /// /// - /// The serialisation streaming context. + /// The serialisation streaming context. /// protected ServerNotInitializedException(SerializationInfo info, StreamingContext context) : base(info, context) diff --git a/src/JsonRpc/Server/ServerResponse.cs b/src/JsonRpc/Server/ServerResponse.cs index 62d968f94..5fc395832 100644 --- a/src/JsonRpc/Server/ServerResponse.cs +++ b/src/JsonRpc/Server/ServerResponse.cs @@ -4,10 +4,7 @@ namespace OmniSharp.Extensions.JsonRpc.Server { public class ServerResponse : ResponseBase { - public ServerResponse(object id, JToken result) : base(id) - { - Result = result; - } + public ServerResponse(object id, JToken result) : base(id) => Result = result; public JToken Result { get; set; } } diff --git a/src/JsonRpc/Server/UnknownErrorException.cs b/src/JsonRpc/Server/UnknownErrorException.cs index 94de172d8..54bcc36df 100644 --- a/src/JsonRpc/Server/UnknownErrorException.cs +++ b/src/JsonRpc/Server/UnknownErrorException.cs @@ -4,17 +4,17 @@ namespace OmniSharp.Extensions.JsonRpc.Server { /// - /// Exception raised when request parameters are invalid according to the target method. + /// Exception raised when request parameters are invalid according to the target method. /// [Serializable] public class UnknownErrorException : RequestException { /// - /// Create a new . + /// Create a new . /// /// - /// The LSP / JSON-RPC request Id (if known). + /// The LSP / JSON-RPC request Id (if known). /// public UnknownErrorException(object requestId) : base(ErrorCodes.ContentModified, requestId, "Content not modified.") @@ -22,13 +22,13 @@ public UnknownErrorException(object requestId) } /// - /// Serialisation constructor. + /// Serialisation constructor. /// /// - /// The serialisation data-store. + /// The serialisation data-store. /// /// - /// The serialisation streaming context. + /// The serialisation streaming context. /// protected UnknownErrorException(SerializationInfo info, StreamingContext context) : base(info, context) diff --git a/src/JsonRpc/TimeLoggerExtensions.cs b/src/JsonRpc/TimeLoggerExtensions.cs index d8da6dd7c..3a8066ac6 100644 --- a/src/JsonRpc/TimeLoggerExtensions.cs +++ b/src/JsonRpc/TimeLoggerExtensions.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.JsonRpc { internal static class TimeLoggerExtensions { - class Disposable : IDisposable + private class Disposable : IDisposable { private readonly IDisposable _disposable; private readonly Action _action; @@ -40,11 +40,12 @@ public static IDisposable TimeTrace(this ILogger logger, string message, params { var scope = logger.BeginScope(new { }); logger.LogTrace($"Starting: {message}", args); - return new Disposable(scope, elapsed => - { - var a = args.Concat(new object[] { elapsed }).ToArray(); - logger.LogTrace($"Finished: {message} in {{ElapsedMilliseconds}}ms", a); - }); + return new Disposable( + scope, elapsed => { + var a = args.Concat(new object[] { elapsed }).ToArray(); + logger.LogTrace($"Finished: {message} in {{ElapsedMilliseconds}}ms", a); + } + ); } /// @@ -58,11 +59,12 @@ public static IDisposable TimeDebug(this ILogger logger, string message, params { var scope = logger.BeginScope(new { }); logger.LogDebug($"Starting: {message}", args); - return new Disposable(scope, elapsed => - { - var a = args.Concat(new object[] { elapsed }).ToArray(); - logger.LogDebug($"Finished: {message} in {{ElapsedMilliseconds}}ms", a); - }); + return new Disposable( + scope, elapsed => { + var a = args.Concat(new object[] { elapsed }).ToArray(); + logger.LogDebug($"Finished: {message} in {{ElapsedMilliseconds}}ms", a); + } + ); } /// @@ -76,11 +78,12 @@ public static IDisposable TimeInformation(this ILogger logger, string message, p { var scope = logger.BeginScope(new { }); logger.LogInformation($"Starting: {message}", args); - return new Disposable(scope, elapsed => - { - var a = args.Concat(new object[] { elapsed }).ToArray(); - logger.LogInformation($"Finished: {message} in {{ElapsedMilliseconds}}ms", a); - }); + return new Disposable( + scope, elapsed => { + var a = args.Concat(new object[] { elapsed }).ToArray(); + logger.LogInformation($"Finished: {message} in {{ElapsedMilliseconds}}ms", a); + } + ); } } } diff --git a/src/JsonRpc/ValueOptionsFactory.cs b/src/JsonRpc/ValueOptionsFactory.cs index 9f5380753..6c0bc6b54 100644 --- a/src/JsonRpc/ValueOptionsFactory.cs +++ b/src/JsonRpc/ValueOptionsFactory.cs @@ -2,13 +2,11 @@ namespace OmniSharp.Extensions.JsonRpc { - internal class ValueOptionsFactory : IOptionsFactory where T : class, new() { + internal class ValueOptionsFactory : IOptionsFactory where T : class, new() + { private readonly T _options; - public ValueOptionsFactory(T options) - { - _options = options; - } + public ValueOptionsFactory(T options) => _options = options; public T Create(string name) => _options; } diff --git a/src/Protocol/AbstractHandlers.cs b/src/Protocol/AbstractHandlers.cs index a73864c26..b1582e589 100644 --- a/src/Protocol/AbstractHandlers.cs +++ b/src/Protocol/AbstractHandlers.cs @@ -49,15 +49,18 @@ public abstract class PartialResult factory) + Func factory + ) { _registrationOptions = registrationOptions; _progressManager = progressManager; _factory = factory; } - async Task IRequestHandler.Handle(TItem request, - CancellationToken cancellationToken) + async Task IRequestHandler.Handle( + TItem request, + CancellationToken cancellationToken + ) { var observer = _progressManager.For(request, cancellationToken); if (observer != null) @@ -74,8 +77,10 @@ async Task IRequestHandler.Handle(TItem request, return _factory(await subject); } - protected abstract void Handle(TItem request, IObserver results, - CancellationToken cancellationToken); + protected abstract void Handle( + TItem request, IObserver results, + CancellationToken cancellationToken + ); TRegistrationOptions IRegistration.GetRegistrationOptions() => _registrationOptions; void ICapability.SetCapability(TCapability capability) => Capability = capability; @@ -97,15 +102,18 @@ public abstract class PartialResults, TResponse> factory) + Func, TResponse> factory + ) { _registrationOptions = registrationOptions; _progressManager = progressManager; _factory = factory; } - async Task IRequestHandler.Handle(TParams request, - CancellationToken cancellationToken) + async Task IRequestHandler.Handle( + TParams request, + CancellationToken cancellationToken + ) { var observer = _progressManager.For(request, cancellationToken); if (observer != null) @@ -116,17 +124,21 @@ async Task IRequestHandler.Handle(TParams request } var subject = new Subject>(); - var task = subject.Aggregate(new List(), (acc, items) => { - acc.AddRange(items); - return acc; - }) - .ToTask(cancellationToken); + var task = subject.Aggregate( + new List(), (acc, items) => { + acc.AddRange(items); + return acc; + } + ) + .ToTask(cancellationToken); Handle(request, subject, cancellationToken); return _factory(await task); } - protected abstract void Handle(TParams request, IObserver> results, - CancellationToken cancellationToken); + protected abstract void Handle( + TParams request, IObserver> results, + CancellationToken cancellationToken + ); TRegistrationOptions IRegistration.GetRegistrationOptions() => _registrationOptions; void ICapability.SetCapability(TCapability capability) => Capability = capability; @@ -143,7 +155,8 @@ public abstract class Notification : protected TCapability Capability { get; private set; } protected Notification( - TRegistrationOptions registrationOptions) => + TRegistrationOptions registrationOptions + ) => _registrationOptions = registrationOptions; public Task Handle(TParams request, CancellationToken cancellationToken) diff --git a/src/Protocol/CharCode.cs b/src/Protocol/CharCode.cs index 8cb35908f..7c95a3259 100644 --- a/src/Protocol/CharCode.cs +++ b/src/Protocol/CharCode.cs @@ -1,77 +1,96 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol { - static class CharCode + internal static class CharCode { public const int Null = 0; + /// /// The `\t` character. /// public const int Tab = 9; + /// /// The `\n` character. /// public const int LineFeed = 10; + /// /// The `\r` character. /// public const int CarriageReturn = 13; + public const int Space = 32; + /// /// The `!` character. /// public const int ExclamationMark = 33; + /// /// The `"` character. /// public const int DoubleQuote = 34; + /// /// The `#` character. /// public const int Hash = 35; + /// /// The `$` character. /// public const int DollarSign = 36; + /// /// The `%` character. /// public const int PercentSign = 37; + /// /// The `&` character. /// public const int Ampersand = 38; + /// /// The `'` character. /// public const int SingleQuote = 39; + /// /// The `(` character. /// public const int OpenParen = 40; + /// /// The `)` character. /// public const int CloseParen = 41; + /// /// The `*` character. /// public const int Asterisk = 42; + /// /// The `+` character. /// public const int Plus = 43; + /// /// The `,` character. /// public const int Comma = 44; + /// /// The `-` character. /// public const int Dash = 45; + /// /// The `.` character. /// public const int Period = 46; + /// /// The `/` character. /// @@ -92,26 +111,32 @@ static class CharCode /// The `:` character. /// public const int Colon = 58; + /// /// The `;` character. /// public const int Semicolon = 59; + /// /// The `<` character. /// public const int LessThan = 60; + /// /// The `=` character. /// public const int Equals = 61; + /// /// The `>` character. /// public const int GreaterThan = 62; + /// /// The `?` character. /// public const int QuestionMark = 63; + /// /// The `@` character. /// @@ -148,22 +173,27 @@ static class CharCode /// The `[` character. /// public const int OpenSquareBracket = 91; + /// /// The `\` character. /// public const int Backslash = 92; + /// /// The `]` character. /// public const int CloseSquareBracket = 93; + /// /// The `^` character. /// public const int Caret = 94; + /// /// The `_` character. /// public const int Underline = 95; + /// /// The ``(`)`` character. /// @@ -200,131 +230,134 @@ static class CharCode /// The `{` character. /// public const int OpenCurlyBrace = 123; + /// /// The `|` character. /// public const int Pipe = 124; + /// /// The `}` character. /// public const int CloseCurlyBrace = 125; + /// /// The `~` character. /// public const int Tilde = 126; - public const int U_Combining_Grave_Accent = 0x0300; // U+0300 Combining Grave Accent - public const int U_Combining_Acute_Accent = 0x0301; // U+0301 Combining Acute Accent - public const int U_Combining_Circumflex_Accent = 0x0302; // U+0302 Combining Circumflex Accent - public const int U_Combining_Tilde = 0x0303; // U+0303 Combining Tilde - public const int U_Combining_Macron = 0x0304; // U+0304 Combining Macron - public const int U_Combining_Overline = 0x0305; // U+0305 Combining Overline - public const int U_Combining_Breve = 0x0306; // U+0306 Combining Breve - public const int U_Combining_Dot_Above = 0x0307; // U+0307 Combining Dot Above - public const int U_Combining_Diaeresis = 0x0308; // U+0308 Combining Diaeresis - public const int U_Combining_Hook_Above = 0x0309; // U+0309 Combining Hook Above - public const int U_Combining_Ring_Above = 0x030A; // U+030A Combining Ring Above - public const int U_Combining_Double_Acute_Accent = 0x030B; // U+030B Combining Double Acute Accent - public const int U_Combining_Caron = 0x030C; // U+030C Combining Caron - public const int U_Combining_Vertical_Line_Above = 0x030D; // U+030D Combining Vertical Line Above - public const int U_Combining_Double_Vertical_Line_Above = 0x030E; // U+030E Combining Double Vertical Line Above - public const int U_Combining_Double_Grave_Accent = 0x030F; // U+030F Combining Double Grave Accent - public const int U_Combining_Candrabindu = 0x0310; // U+0310 Combining Candrabindu - public const int U_Combining_Inverted_Breve = 0x0311; // U+0311 Combining Inverted Breve - public const int U_Combining_Turned_Comma_Above = 0x0312; // U+0312 Combining Turned Comma Above - public const int U_Combining_Comma_Above = 0x0313; // U+0313 Combining Comma Above - public const int U_Combining_Reversed_Comma_Above = 0x0314; // U+0314 Combining Reversed Comma Above - public const int U_Combining_Comma_Above_Right = 0x0315; // U+0315 Combining Comma Above Right - public const int U_Combining_Grave_Accent_Below = 0x0316; // U+0316 Combining Grave Accent Below - public const int U_Combining_Acute_Accent_Below = 0x0317; // U+0317 Combining Acute Accent Below - public const int U_Combining_Left_Tack_Below = 0x0318; // U+0318 Combining Left Tack Below - public const int U_Combining_Right_Tack_Below = 0x0319; // U+0319 Combining Right Tack Below - public const int U_Combining_Left_Angle_Above = 0x031A; // U+031A Combining Left Angle Above - public const int U_Combining_Horn = 0x031B; // U+031B Combining Horn - public const int U_Combining_Left_Half_Ring_Below = 0x031C; // U+031C Combining Left Half Ring Below - public const int U_Combining_Up_Tack_Below = 0x031D; // U+031D Combining Up Tack Below - public const int U_Combining_Down_Tack_Below = 0x031E; // U+031E Combining Down Tack Below - public const int U_Combining_Plus_Sign_Below = 0x031F; // U+031F Combining Plus Sign Below - public const int U_Combining_Minus_Sign_Below = 0x0320; // U+0320 Combining Minus Sign Below - public const int U_Combining_Palatalized_Hook_Below = 0x0321; // U+0321 Combining Palatalized Hook Below - public const int U_Combining_Retroflex_Hook_Below = 0x0322; // U+0322 Combining Retroflex Hook Below - public const int U_Combining_Dot_Below = 0x0323; // U+0323 Combining Dot Below - public const int U_Combining_Diaeresis_Below = 0x0324; // U+0324 Combining Diaeresis Below - public const int U_Combining_Ring_Below = 0x0325; // U+0325 Combining Ring Below - public const int U_Combining_Comma_Below = 0x0326; // U+0326 Combining Comma Below - public const int U_Combining_Cedilla = 0x0327; // U+0327 Combining Cedilla - public const int U_Combining_Ogonek = 0x0328; // U+0328 Combining Ogonek - public const int U_Combining_Vertical_Line_Below = 0x0329; // U+0329 Combining Vertical Line Below - public const int U_Combining_Bridge_Below = 0x032A; // U+032A Combining Bridge Below - public const int U_Combining_Inverted_Double_Arch_Below = 0x032B; // U+032B Combining Inverted Double Arch Below - public const int U_Combining_Caron_Below = 0x032C; // U+032C Combining Caron Below - public const int U_Combining_Circumflex_Accent_Below = 0x032D; // U+032D Combining Circumflex Accent Below - public const int U_Combining_Breve_Below = 0x032E; // U+032E Combining Breve Below - public const int U_Combining_Inverted_Breve_Below = 0x032F; // U+032F Combining Inverted Breve Below - public const int U_Combining_Tilde_Below = 0x0330; // U+0330 Combining Tilde Below - public const int U_Combining_Macron_Below = 0x0331; // U+0331 Combining Macron Below - public const int U_Combining_Low_Line = 0x0332; // U+0332 Combining Low Line - public const int U_Combining_Double_Low_Line = 0x0333; // U+0333 Combining Double Low Line - public const int U_Combining_Tilde_Overlay = 0x0334; // U+0334 Combining Tilde Overlay - public const int U_Combining_Short_Stroke_Overlay = 0x0335; // U+0335 Combining Short Stroke Overlay - public const int U_Combining_Long_Stroke_Overlay = 0x0336; // U+0336 Combining Long Stroke Overlay - public const int U_Combining_Short_Solidus_Overlay = 0x0337; // U+0337 Combining Short Solidus Overlay - public const int U_Combining_Long_Solidus_Overlay = 0x0338; // U+0338 Combining Long Solidus Overlay - public const int U_Combining_Right_Half_Ring_Below = 0x0339; // U+0339 Combining Right Half Ring Below - public const int U_Combining_Inverted_Bridge_Below = 0x033A; // U+033A Combining Inverted Bridge Below - public const int U_Combining_Square_Below = 0x033B; // U+033B Combining Square Below - public const int U_Combining_Seagull_Below = 0x033C; // U+033C Combining Seagull Below - public const int U_Combining_X_Above = 0x033D; // U+033D Combining X Above - public const int U_Combining_Vertical_Tilde = 0x033E; // U+033E Combining Vertical Tilde - public const int U_Combining_Double_Overline = 0x033F; // U+033F Combining Double Overline - public const int U_Combining_Grave_Tone_Mark = 0x0340; // U+0340 Combining Grave Tone Mark - public const int U_Combining_Acute_Tone_Mark = 0x0341; // U+0341 Combining Acute Tone Mark - public const int U_Combining_Greek_Perispomeni = 0x0342; // U+0342 Combining Greek Perispomeni - public const int U_Combining_Greek_Koronis = 0x0343; // U+0343 Combining Greek Koronis - public const int U_Combining_Greek_Dialytika_Tonos = 0x0344; // U+0344 Combining Greek Dialytika Tonos - public const int U_Combining_Greek_Ypogegrammeni = 0x0345; // U+0345 Combining Greek Ypogegrammeni - public const int U_Combining_Bridge_Above = 0x0346; // U+0346 Combining Bridge Above - public const int U_Combining_Equals_Sign_Below = 0x0347; // U+0347 Combining Equals Sign Below - public const int U_Combining_Double_Vertical_Line_Below = 0x0348; // U+0348 Combining Double Vertical Line Below - public const int U_Combining_Left_Angle_Below = 0x0349; // U+0349 Combining Left Angle Below - public const int U_Combining_Not_Tilde_Above = 0x034A; // U+034A Combining Not Tilde Above - public const int U_Combining_Homothetic_Above = 0x034B; // U+034B Combining Homothetic Above - public const int U_Combining_Almost_Equal_To_Above = 0x034C; // U+034C Combining Almost Equal To Above - public const int U_Combining_Left_Right_Arrow_Below = 0x034D; // U+034D Combining Left Right Arrow Below - public const int U_Combining_Upwards_Arrow_Below = 0x034E; // U+034E Combining Upwards Arrow Below - public const int U_Combining_Grapheme_Joiner = 0x034F; // U+034F Combining Grapheme Joiner - public const int U_Combining_Right_Arrowhead_Above = 0x0350; // U+0350 Combining Right Arrowhead Above - public const int U_Combining_Left_Half_Ring_Above = 0x0351; // U+0351 Combining Left Half Ring Above - public const int U_Combining_Fermata = 0x0352; // U+0352 Combining Fermata - public const int U_Combining_X_Below = 0x0353; // U+0353 Combining X Below - public const int U_Combining_Left_Arrowhead_Below = 0x0354; // U+0354 Combining Left Arrowhead Below - public const int U_Combining_Right_Arrowhead_Below = 0x0355; // U+0355 Combining Right Arrowhead Below - public const int U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below = 0x0356; // U+0356 Combining Right Arrowhead And Up Arrowhead Below - public const int U_Combining_Right_Half_Ring_Above = 0x0357; // U+0357 Combining Right Half Ring Above - public const int U_Combining_Dot_Above_Right = 0x0358; // U+0358 Combining Dot Above Right - public const int U_Combining_Asterisk_Below = 0x0359; // U+0359 Combining Asterisk Below - public const int U_Combining_Double_Ring_Below = 0x035A; // U+035A Combining Double Ring Below - public const int U_Combining_Zigzag_Above = 0x035B; // U+035B Combining Zigzag Above - public const int U_Combining_Double_Breve_Below = 0x035C; // U+035C Combining Double Breve Below - public const int U_Combining_Double_Breve = 0x035D; // U+035D Combining Double Breve - public const int U_Combining_Double_Macron = 0x035E; // U+035E Combining Double Macron - public const int U_Combining_Double_Macron_Below = 0x035F; // U+035F Combining Double Macron Below - public const int U_Combining_Double_Tilde = 0x0360; // U+0360 Combining Double Tilde - public const int U_Combining_Double_Inverted_Breve = 0x0361; // U+0361 Combining Double Inverted Breve - public const int U_Combining_Double_Rightwards_Arrow_Below = 0x0362; // U+0362 Combining Double Rightwards Arrow Below - public const int U_Combining_Latin_Small_Letter_A = 0x0363; // U+0363 Combining Latin Small Letter A - public const int U_Combining_Latin_Small_Letter_E = 0x0364; // U+0364 Combining Latin Small Letter E - public const int U_Combining_Latin_Small_Letter_I = 0x0365; // U+0365 Combining Latin Small Letter I - public const int U_Combining_Latin_Small_Letter_O = 0x0366; // U+0366 Combining Latin Small Letter O - public const int U_Combining_Latin_Small_Letter_U = 0x0367; // U+0367 Combining Latin Small Letter U - public const int U_Combining_Latin_Small_Letter_C = 0x0368; // U+0368 Combining Latin Small Letter C - public const int U_Combining_Latin_Small_Letter_D = 0x0369; // U+0369 Combining Latin Small Letter D - public const int U_Combining_Latin_Small_Letter_H = 0x036A; // U+036A Combining Latin Small Letter H - public const int U_Combining_Latin_Small_Letter_M = 0x036B; // U+036B Combining Latin Small Letter M - public const int U_Combining_Latin_Small_Letter_R = 0x036C; // U+036C Combining Latin Small Letter R - public const int U_Combining_Latin_Small_Letter_T = 0x036D; // U+036D Combining Latin Small Letter T - public const int U_Combining_Latin_Small_Letter_V = 0x036E; // U+036E Combining Latin Small Letter V - public const int U_Combining_Latin_Small_Letter_X = 0x036F; // U+036F Combining Latin Small Letter X + public const int U_Combining_Grave_Accent = 0x0300; // U+0300 Combining Grave Accent + public const int U_Combining_Acute_Accent = 0x0301; // U+0301 Combining Acute Accent + public const int U_Combining_Circumflex_Accent = 0x0302; // U+0302 Combining Circumflex Accent + public const int U_Combining_Tilde = 0x0303; // U+0303 Combining Tilde + public const int U_Combining_Macron = 0x0304; // U+0304 Combining Macron + public const int U_Combining_Overline = 0x0305; // U+0305 Combining Overline + public const int U_Combining_Breve = 0x0306; // U+0306 Combining Breve + public const int U_Combining_Dot_Above = 0x0307; // U+0307 Combining Dot Above + public const int U_Combining_Diaeresis = 0x0308; // U+0308 Combining Diaeresis + public const int U_Combining_Hook_Above = 0x0309; // U+0309 Combining Hook Above + public const int U_Combining_Ring_Above = 0x030A; // U+030A Combining Ring Above + public const int U_Combining_Double_Acute_Accent = 0x030B; // U+030B Combining Double Acute Accent + public const int U_Combining_Caron = 0x030C; // U+030C Combining Caron + public const int U_Combining_Vertical_Line_Above = 0x030D; // U+030D Combining Vertical Line Above + public const int U_Combining_Double_Vertical_Line_Above = 0x030E; // U+030E Combining Double Vertical Line Above + public const int U_Combining_Double_Grave_Accent = 0x030F; // U+030F Combining Double Grave Accent + public const int U_Combining_Candrabindu = 0x0310; // U+0310 Combining Candrabindu + public const int U_Combining_Inverted_Breve = 0x0311; // U+0311 Combining Inverted Breve + public const int U_Combining_Turned_Comma_Above = 0x0312; // U+0312 Combining Turned Comma Above + public const int U_Combining_Comma_Above = 0x0313; // U+0313 Combining Comma Above + public const int U_Combining_Reversed_Comma_Above = 0x0314; // U+0314 Combining Reversed Comma Above + public const int U_Combining_Comma_Above_Right = 0x0315; // U+0315 Combining Comma Above Right + public const int U_Combining_Grave_Accent_Below = 0x0316; // U+0316 Combining Grave Accent Below + public const int U_Combining_Acute_Accent_Below = 0x0317; // U+0317 Combining Acute Accent Below + public const int U_Combining_Left_Tack_Below = 0x0318; // U+0318 Combining Left Tack Below + public const int U_Combining_Right_Tack_Below = 0x0319; // U+0319 Combining Right Tack Below + public const int U_Combining_Left_Angle_Above = 0x031A; // U+031A Combining Left Angle Above + public const int U_Combining_Horn = 0x031B; // U+031B Combining Horn + public const int U_Combining_Left_Half_Ring_Below = 0x031C; // U+031C Combining Left Half Ring Below + public const int U_Combining_Up_Tack_Below = 0x031D; // U+031D Combining Up Tack Below + public const int U_Combining_Down_Tack_Below = 0x031E; // U+031E Combining Down Tack Below + public const int U_Combining_Plus_Sign_Below = 0x031F; // U+031F Combining Plus Sign Below + public const int U_Combining_Minus_Sign_Below = 0x0320; // U+0320 Combining Minus Sign Below + public const int U_Combining_Palatalized_Hook_Below = 0x0321; // U+0321 Combining Palatalized Hook Below + public const int U_Combining_Retroflex_Hook_Below = 0x0322; // U+0322 Combining Retroflex Hook Below + public const int U_Combining_Dot_Below = 0x0323; // U+0323 Combining Dot Below + public const int U_Combining_Diaeresis_Below = 0x0324; // U+0324 Combining Diaeresis Below + public const int U_Combining_Ring_Below = 0x0325; // U+0325 Combining Ring Below + public const int U_Combining_Comma_Below = 0x0326; // U+0326 Combining Comma Below + public const int U_Combining_Cedilla = 0x0327; // U+0327 Combining Cedilla + public const int U_Combining_Ogonek = 0x0328; // U+0328 Combining Ogonek + public const int U_Combining_Vertical_Line_Below = 0x0329; // U+0329 Combining Vertical Line Below + public const int U_Combining_Bridge_Below = 0x032A; // U+032A Combining Bridge Below + public const int U_Combining_Inverted_Double_Arch_Below = 0x032B; // U+032B Combining Inverted Double Arch Below + public const int U_Combining_Caron_Below = 0x032C; // U+032C Combining Caron Below + public const int U_Combining_Circumflex_Accent_Below = 0x032D; // U+032D Combining Circumflex Accent Below + public const int U_Combining_Breve_Below = 0x032E; // U+032E Combining Breve Below + public const int U_Combining_Inverted_Breve_Below = 0x032F; // U+032F Combining Inverted Breve Below + public const int U_Combining_Tilde_Below = 0x0330; // U+0330 Combining Tilde Below + public const int U_Combining_Macron_Below = 0x0331; // U+0331 Combining Macron Below + public const int U_Combining_Low_Line = 0x0332; // U+0332 Combining Low Line + public const int U_Combining_Double_Low_Line = 0x0333; // U+0333 Combining Double Low Line + public const int U_Combining_Tilde_Overlay = 0x0334; // U+0334 Combining Tilde Overlay + public const int U_Combining_Short_Stroke_Overlay = 0x0335; // U+0335 Combining Short Stroke Overlay + public const int U_Combining_Long_Stroke_Overlay = 0x0336; // U+0336 Combining Long Stroke Overlay + public const int U_Combining_Short_Solidus_Overlay = 0x0337; // U+0337 Combining Short Solidus Overlay + public const int U_Combining_Long_Solidus_Overlay = 0x0338; // U+0338 Combining Long Solidus Overlay + public const int U_Combining_Right_Half_Ring_Below = 0x0339; // U+0339 Combining Right Half Ring Below + public const int U_Combining_Inverted_Bridge_Below = 0x033A; // U+033A Combining Inverted Bridge Below + public const int U_Combining_Square_Below = 0x033B; // U+033B Combining Square Below + public const int U_Combining_Seagull_Below = 0x033C; // U+033C Combining Seagull Below + public const int U_Combining_X_Above = 0x033D; // U+033D Combining X Above + public const int U_Combining_Vertical_Tilde = 0x033E; // U+033E Combining Vertical Tilde + public const int U_Combining_Double_Overline = 0x033F; // U+033F Combining Double Overline + public const int U_Combining_Grave_Tone_Mark = 0x0340; // U+0340 Combining Grave Tone Mark + public const int U_Combining_Acute_Tone_Mark = 0x0341; // U+0341 Combining Acute Tone Mark + public const int U_Combining_Greek_Perispomeni = 0x0342; // U+0342 Combining Greek Perispomeni + public const int U_Combining_Greek_Koronis = 0x0343; // U+0343 Combining Greek Koronis + public const int U_Combining_Greek_Dialytika_Tonos = 0x0344; // U+0344 Combining Greek Dialytika Tonos + public const int U_Combining_Greek_Ypogegrammeni = 0x0345; // U+0345 Combining Greek Ypogegrammeni + public const int U_Combining_Bridge_Above = 0x0346; // U+0346 Combining Bridge Above + public const int U_Combining_Equals_Sign_Below = 0x0347; // U+0347 Combining Equals Sign Below + public const int U_Combining_Double_Vertical_Line_Below = 0x0348; // U+0348 Combining Double Vertical Line Below + public const int U_Combining_Left_Angle_Below = 0x0349; // U+0349 Combining Left Angle Below + public const int U_Combining_Not_Tilde_Above = 0x034A; // U+034A Combining Not Tilde Above + public const int U_Combining_Homothetic_Above = 0x034B; // U+034B Combining Homothetic Above + public const int U_Combining_Almost_Equal_To_Above = 0x034C; // U+034C Combining Almost Equal To Above + public const int U_Combining_Left_Right_Arrow_Below = 0x034D; // U+034D Combining Left Right Arrow Below + public const int U_Combining_Upwards_Arrow_Below = 0x034E; // U+034E Combining Upwards Arrow Below + public const int U_Combining_Grapheme_Joiner = 0x034F; // U+034F Combining Grapheme Joiner + public const int U_Combining_Right_Arrowhead_Above = 0x0350; // U+0350 Combining Right Arrowhead Above + public const int U_Combining_Left_Half_Ring_Above = 0x0351; // U+0351 Combining Left Half Ring Above + public const int U_Combining_Fermata = 0x0352; // U+0352 Combining Fermata + public const int U_Combining_X_Below = 0x0353; // U+0353 Combining X Below + public const int U_Combining_Left_Arrowhead_Below = 0x0354; // U+0354 Combining Left Arrowhead Below + public const int U_Combining_Right_Arrowhead_Below = 0x0355; // U+0355 Combining Right Arrowhead Below + public const int U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below = 0x0356; // U+0356 Combining Right Arrowhead And Up Arrowhead Below + public const int U_Combining_Right_Half_Ring_Above = 0x0357; // U+0357 Combining Right Half Ring Above + public const int U_Combining_Dot_Above_Right = 0x0358; // U+0358 Combining Dot Above Right + public const int U_Combining_Asterisk_Below = 0x0359; // U+0359 Combining Asterisk Below + public const int U_Combining_Double_Ring_Below = 0x035A; // U+035A Combining Double Ring Below + public const int U_Combining_Zigzag_Above = 0x035B; // U+035B Combining Zigzag Above + public const int U_Combining_Double_Breve_Below = 0x035C; // U+035C Combining Double Breve Below + public const int U_Combining_Double_Breve = 0x035D; // U+035D Combining Double Breve + public const int U_Combining_Double_Macron = 0x035E; // U+035E Combining Double Macron + public const int U_Combining_Double_Macron_Below = 0x035F; // U+035F Combining Double Macron Below + public const int U_Combining_Double_Tilde = 0x0360; // U+0360 Combining Double Tilde + public const int U_Combining_Double_Inverted_Breve = 0x0361; // U+0361 Combining Double Inverted Breve + public const int U_Combining_Double_Rightwards_Arrow_Below = 0x0362; // U+0362 Combining Double Rightwards Arrow Below + public const int U_Combining_Latin_Small_Letter_A = 0x0363; // U+0363 Combining Latin Small Letter A + public const int U_Combining_Latin_Small_Letter_E = 0x0364; // U+0364 Combining Latin Small Letter E + public const int U_Combining_Latin_Small_Letter_I = 0x0365; // U+0365 Combining Latin Small Letter I + public const int U_Combining_Latin_Small_Letter_O = 0x0366; // U+0366 Combining Latin Small Letter O + public const int U_Combining_Latin_Small_Letter_U = 0x0367; // U+0367 Combining Latin Small Letter U + public const int U_Combining_Latin_Small_Letter_C = 0x0368; // U+0368 Combining Latin Small Letter C + public const int U_Combining_Latin_Small_Letter_D = 0x0369; // U+0369 Combining Latin Small Letter D + public const int U_Combining_Latin_Small_Letter_H = 0x036A; // U+036A Combining Latin Small Letter H + public const int U_Combining_Latin_Small_Letter_M = 0x036B; // U+036B Combining Latin Small Letter M + public const int U_Combining_Latin_Small_Letter_R = 0x036C; // U+036C Combining Latin Small Letter R + public const int U_Combining_Latin_Small_Letter_T = 0x036D; // U+036D Combining Latin Small Letter T + public const int U_Combining_Latin_Small_Letter_V = 0x036E; // U+036E Combining Latin Small Letter V + public const int U_Combining_Latin_Small_Letter_X = 0x036F; // U+036F Combining Latin Small Letter X /// /// Unicode Character "LINE SEPARATOR" (U+2028) @@ -333,73 +366,73 @@ static class CharCode public const int LINE_SEPARATOR_2028 = 8232; // http://www.fileformat.info/info/unicode/category/Sk/list.htm - public const int U_CIRCUMFLEX = 0x005E; // U+005E CIRCUMFLEX - public const int U_GRAVE_ACCENT = 0x0060; // U+0060 GRAVE ACCENT - public const int U_DIAERESIS = 0x00A8; // U+00A8 DIAERESIS - public const int U_MACRON = 0x00AF; // U+00AF MACRON - public const int U_ACUTE_ACCENT = 0x00B4; // U+00B4 ACUTE ACCENT - public const int U_CEDILLA = 0x00B8; // U+00B8 CEDILLA - public const int U_MODIFIER_LETTER_LEFT_ARROWHEAD = 0x02C2; // U+02C2 MODIFIER LETTER LEFT ARROWHEAD - public const int U_MODIFIER_LETTER_RIGHT_ARROWHEAD = 0x02C3; // U+02C3 MODIFIER LETTER RIGHT ARROWHEAD - public const int U_MODIFIER_LETTER_UP_ARROWHEAD = 0x02C4; // U+02C4 MODIFIER LETTER UP ARROWHEAD - public const int U_MODIFIER_LETTER_DOWN_ARROWHEAD = 0x02C5; // U+02C5 MODIFIER LETTER DOWN ARROWHEAD - public const int U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING = 0x02D2; // U+02D2 MODIFIER LETTER CENTRED RIGHT HALF RING - public const int U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING = 0x02D3; // U+02D3 MODIFIER LETTER CENTRED LEFT HALF RING - public const int U_MODIFIER_LETTER_UP_TACK = 0x02D4; // U+02D4 MODIFIER LETTER UP TACK - public const int U_MODIFIER_LETTER_DOWN_TACK = 0x02D5; // U+02D5 MODIFIER LETTER DOWN TACK - public const int U_MODIFIER_LETTER_PLUS_SIGN = 0x02D6; // U+02D6 MODIFIER LETTER PLUS SIGN - public const int U_MODIFIER_LETTER_MINUS_SIGN = 0x02D7; // U+02D7 MODIFIER LETTER MINUS SIGN - public const int U_BREVE = 0x02D8; // U+02D8 BREVE - public const int U_DOT_ABOVE = 0x02D9; // U+02D9 DOT ABOVE - public const int U_RING_ABOVE = 0x02DA; // U+02DA RING ABOVE - public const int U_OGONEK = 0x02DB; // U+02DB OGONEK - public const int U_SMALL_TILDE = 0x02DC; // U+02DC SMALL TILDE - public const int U_DOUBLE_ACUTE_ACCENT = 0x02DD; // U+02DD DOUBLE ACUTE ACCENT - public const int U_MODIFIER_LETTER_RHOTIC_HOOK = 0x02DE; // U+02DE MODIFIER LETTER RHOTIC HOOK - public const int U_MODIFIER_LETTER_CROSS_ACCENT = 0x02DF; // U+02DF MODIFIER LETTER CROSS ACCENT - public const int U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR = 0x02E5; // U+02E5 MODIFIER LETTER EXTRA-HIGH TONE BAR - public const int U_MODIFIER_LETTER_HIGH_TONE_BAR = 0x02E6; // U+02E6 MODIFIER LETTER HIGH TONE BAR - public const int U_MODIFIER_LETTER_MID_TONE_BAR = 0x02E7; // U+02E7 MODIFIER LETTER MID TONE BAR - public const int U_MODIFIER_LETTER_LOW_TONE_BAR = 0x02E8; // U+02E8 MODIFIER LETTER LOW TONE BAR - public const int U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR = 0x02E9; // U+02E9 MODIFIER LETTER EXTRA-LOW TONE BAR - public const int U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK = 0x02EA; // U+02EA MODIFIER LETTER YIN DEPARTING TONE MARK - public const int U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK = 0x02EB; // U+02EB MODIFIER LETTER YANG DEPARTING TONE MARK - public const int U_MODIFIER_LETTER_UNASPIRATED = 0x02ED; // U+02ED MODIFIER LETTER UNASPIRATED - public const int U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD = 0x02EF; // U+02EF MODIFIER LETTER LOW DOWN ARROWHEAD - public const int U_MODIFIER_LETTER_LOW_UP_ARROWHEAD = 0x02F0; // U+02F0 MODIFIER LETTER LOW UP ARROWHEAD - public const int U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD = 0x02F1; // U+02F1 MODIFIER LETTER LOW LEFT ARROWHEAD - public const int U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD = 0x02F2; // U+02F2 MODIFIER LETTER LOW RIGHT ARROWHEAD - public const int U_MODIFIER_LETTER_LOW_RING = 0x02F3; // U+02F3 MODIFIER LETTER LOW RING - public const int U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT = 0x02F4; // U+02F4 MODIFIER LETTER MIDDLE GRAVE ACCENT + public const int U_CIRCUMFLEX = 0x005E; // U+005E CIRCUMFLEX + public const int U_GRAVE_ACCENT = 0x0060; // U+0060 GRAVE ACCENT + public const int U_DIAERESIS = 0x00A8; // U+00A8 DIAERESIS + public const int U_MACRON = 0x00AF; // U+00AF MACRON + public const int U_ACUTE_ACCENT = 0x00B4; // U+00B4 ACUTE ACCENT + public const int U_CEDILLA = 0x00B8; // U+00B8 CEDILLA + public const int U_MODIFIER_LETTER_LEFT_ARROWHEAD = 0x02C2; // U+02C2 MODIFIER LETTER LEFT ARROWHEAD + public const int U_MODIFIER_LETTER_RIGHT_ARROWHEAD = 0x02C3; // U+02C3 MODIFIER LETTER RIGHT ARROWHEAD + public const int U_MODIFIER_LETTER_UP_ARROWHEAD = 0x02C4; // U+02C4 MODIFIER LETTER UP ARROWHEAD + public const int U_MODIFIER_LETTER_DOWN_ARROWHEAD = 0x02C5; // U+02C5 MODIFIER LETTER DOWN ARROWHEAD + public const int U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING = 0x02D2; // U+02D2 MODIFIER LETTER CENTRED RIGHT HALF RING + public const int U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING = 0x02D3; // U+02D3 MODIFIER LETTER CENTRED LEFT HALF RING + public const int U_MODIFIER_LETTER_UP_TACK = 0x02D4; // U+02D4 MODIFIER LETTER UP TACK + public const int U_MODIFIER_LETTER_DOWN_TACK = 0x02D5; // U+02D5 MODIFIER LETTER DOWN TACK + public const int U_MODIFIER_LETTER_PLUS_SIGN = 0x02D6; // U+02D6 MODIFIER LETTER PLUS SIGN + public const int U_MODIFIER_LETTER_MINUS_SIGN = 0x02D7; // U+02D7 MODIFIER LETTER MINUS SIGN + public const int U_BREVE = 0x02D8; // U+02D8 BREVE + public const int U_DOT_ABOVE = 0x02D9; // U+02D9 DOT ABOVE + public const int U_RING_ABOVE = 0x02DA; // U+02DA RING ABOVE + public const int U_OGONEK = 0x02DB; // U+02DB OGONEK + public const int U_SMALL_TILDE = 0x02DC; // U+02DC SMALL TILDE + public const int U_DOUBLE_ACUTE_ACCENT = 0x02DD; // U+02DD DOUBLE ACUTE ACCENT + public const int U_MODIFIER_LETTER_RHOTIC_HOOK = 0x02DE; // U+02DE MODIFIER LETTER RHOTIC HOOK + public const int U_MODIFIER_LETTER_CROSS_ACCENT = 0x02DF; // U+02DF MODIFIER LETTER CROSS ACCENT + public const int U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR = 0x02E5; // U+02E5 MODIFIER LETTER EXTRA-HIGH TONE BAR + public const int U_MODIFIER_LETTER_HIGH_TONE_BAR = 0x02E6; // U+02E6 MODIFIER LETTER HIGH TONE BAR + public const int U_MODIFIER_LETTER_MID_TONE_BAR = 0x02E7; // U+02E7 MODIFIER LETTER MID TONE BAR + public const int U_MODIFIER_LETTER_LOW_TONE_BAR = 0x02E8; // U+02E8 MODIFIER LETTER LOW TONE BAR + public const int U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR = 0x02E9; // U+02E9 MODIFIER LETTER EXTRA-LOW TONE BAR + public const int U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK = 0x02EA; // U+02EA MODIFIER LETTER YIN DEPARTING TONE MARK + public const int U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK = 0x02EB; // U+02EB MODIFIER LETTER YANG DEPARTING TONE MARK + public const int U_MODIFIER_LETTER_UNASPIRATED = 0x02ED; // U+02ED MODIFIER LETTER UNASPIRATED + public const int U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD = 0x02EF; // U+02EF MODIFIER LETTER LOW DOWN ARROWHEAD + public const int U_MODIFIER_LETTER_LOW_UP_ARROWHEAD = 0x02F0; // U+02F0 MODIFIER LETTER LOW UP ARROWHEAD + public const int U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD = 0x02F1; // U+02F1 MODIFIER LETTER LOW LEFT ARROWHEAD + public const int U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD = 0x02F2; // U+02F2 MODIFIER LETTER LOW RIGHT ARROWHEAD + public const int U_MODIFIER_LETTER_LOW_RING = 0x02F3; // U+02F3 MODIFIER LETTER LOW RING + public const int U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT = 0x02F4; // U+02F4 MODIFIER LETTER MIDDLE GRAVE ACCENT public const int U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT = 0x02F5; // U+02F5 MODIFIER LETTER MIDDLE DOUBLE GRAVE ACCENT public const int U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT = 0x02F6; // U+02F6 MODIFIER LETTER MIDDLE DOUBLE ACUTE ACCENT - public const int U_MODIFIER_LETTER_LOW_TILDE = 0x02F7; // U+02F7 MODIFIER LETTER LOW TILDE - public const int U_MODIFIER_LETTER_RAISED_COLON = 0x02F8; // U+02F8 MODIFIER LETTER RAISED COLON - public const int U_MODIFIER_LETTER_BEGIN_HIGH_TONE = 0x02F9; // U+02F9 MODIFIER LETTER BEGIN HIGH TONE - public const int U_MODIFIER_LETTER_END_HIGH_TONE = 0x02FA; // U+02FA MODIFIER LETTER END HIGH TONE - public const int U_MODIFIER_LETTER_BEGIN_LOW_TONE = 0x02FB; // U+02FB MODIFIER LETTER BEGIN LOW TONE - public const int U_MODIFIER_LETTER_END_LOW_TONE = 0x02FC; // U+02FC MODIFIER LETTER END LOW TONE - public const int U_MODIFIER_LETTER_SHELF = 0x02FD; // U+02FD MODIFIER LETTER SHELF - public const int U_MODIFIER_LETTER_OPEN_SHELF = 0x02FE; // U+02FE MODIFIER LETTER OPEN SHELF - public const int U_MODIFIER_LETTER_LOW_LEFT_ARROW = 0x02FF; // U+02FF MODIFIER LETTER LOW LEFT ARROW - public const int U_GREEK_LOWER_NUMERAL_SIGN = 0x0375; // U+0375 GREEK LOWER NUMERAL SIGN - public const int U_GREEK_TONOS = 0x0384; // U+0384 GREEK TONOS - public const int U_GREEK_DIALYTIKA_TONOS = 0x0385; // U+0385 GREEK DIALYTIKA TONOS - public const int U_GREEK_KORONIS = 0x1FBD; // U+1FBD GREEK KORONIS - public const int U_GREEK_PSILI = 0x1FBF; // U+1FBF GREEK PSILI - public const int U_GREEK_PERISPOMENI = 0x1FC0; // U+1FC0 GREEK PERISPOMENI - public const int U_GREEK_DIALYTIKA_AND_PERISPOMENI = 0x1FC1; // U+1FC1 GREEK DIALYTIKA AND PERISPOMENI - public const int U_GREEK_PSILI_AND_VARIA = 0x1FCD; // U+1FCD GREEK PSILI AND VARIA - public const int U_GREEK_PSILI_AND_OXIA = 0x1FCE; // U+1FCE GREEK PSILI AND OXIA - public const int U_GREEK_PSILI_AND_PERISPOMENI = 0x1FCF; // U+1FCF GREEK PSILI AND PERISPOMENI - public const int U_GREEK_DASIA_AND_VARIA = 0x1FDD; // U+1FDD GREEK DASIA AND VARIA - public const int U_GREEK_DASIA_AND_OXIA = 0x1FDE; // U+1FDE GREEK DASIA AND OXIA - public const int U_GREEK_DASIA_AND_PERISPOMENI = 0x1FDF; // U+1FDF GREEK DASIA AND PERISPOMENI - public const int U_GREEK_DIALYTIKA_AND_VARIA = 0x1FED; // U+1FED GREEK DIALYTIKA AND VARIA - public const int U_GREEK_DIALYTIKA_AND_OXIA = 0x1FEE; // U+1FEE GREEK DIALYTIKA AND OXIA - public const int U_GREEK_VARIA = 0x1FEF; // U+1FEF GREEK VARIA - public const int U_GREEK_OXIA = 0x1FFD; // U+1FFD GREEK OXIA - public const int U_GREEK_DASIA = 0x1FFE; // U+1FFE GREEK DASIA + public const int U_MODIFIER_LETTER_LOW_TILDE = 0x02F7; // U+02F7 MODIFIER LETTER LOW TILDE + public const int U_MODIFIER_LETTER_RAISED_COLON = 0x02F8; // U+02F8 MODIFIER LETTER RAISED COLON + public const int U_MODIFIER_LETTER_BEGIN_HIGH_TONE = 0x02F9; // U+02F9 MODIFIER LETTER BEGIN HIGH TONE + public const int U_MODIFIER_LETTER_END_HIGH_TONE = 0x02FA; // U+02FA MODIFIER LETTER END HIGH TONE + public const int U_MODIFIER_LETTER_BEGIN_LOW_TONE = 0x02FB; // U+02FB MODIFIER LETTER BEGIN LOW TONE + public const int U_MODIFIER_LETTER_END_LOW_TONE = 0x02FC; // U+02FC MODIFIER LETTER END LOW TONE + public const int U_MODIFIER_LETTER_SHELF = 0x02FD; // U+02FD MODIFIER LETTER SHELF + public const int U_MODIFIER_LETTER_OPEN_SHELF = 0x02FE; // U+02FE MODIFIER LETTER OPEN SHELF + public const int U_MODIFIER_LETTER_LOW_LEFT_ARROW = 0x02FF; // U+02FF MODIFIER LETTER LOW LEFT ARROW + public const int U_GREEK_LOWER_NUMERAL_SIGN = 0x0375; // U+0375 GREEK LOWER NUMERAL SIGN + public const int U_GREEK_TONOS = 0x0384; // U+0384 GREEK TONOS + public const int U_GREEK_DIALYTIKA_TONOS = 0x0385; // U+0385 GREEK DIALYTIKA TONOS + public const int U_GREEK_KORONIS = 0x1FBD; // U+1FBD GREEK KORONIS + public const int U_GREEK_PSILI = 0x1FBF; // U+1FBF GREEK PSILI + public const int U_GREEK_PERISPOMENI = 0x1FC0; // U+1FC0 GREEK PERISPOMENI + public const int U_GREEK_DIALYTIKA_AND_PERISPOMENI = 0x1FC1; // U+1FC1 GREEK DIALYTIKA AND PERISPOMENI + public const int U_GREEK_PSILI_AND_VARIA = 0x1FCD; // U+1FCD GREEK PSILI AND VARIA + public const int U_GREEK_PSILI_AND_OXIA = 0x1FCE; // U+1FCE GREEK PSILI AND OXIA + public const int U_GREEK_PSILI_AND_PERISPOMENI = 0x1FCF; // U+1FCF GREEK PSILI AND PERISPOMENI + public const int U_GREEK_DASIA_AND_VARIA = 0x1FDD; // U+1FDD GREEK DASIA AND VARIA + public const int U_GREEK_DASIA_AND_OXIA = 0x1FDE; // U+1FDE GREEK DASIA AND OXIA + public const int U_GREEK_DASIA_AND_PERISPOMENI = 0x1FDF; // U+1FDF GREEK DASIA AND PERISPOMENI + public const int U_GREEK_DIALYTIKA_AND_VARIA = 0x1FED; // U+1FED GREEK DIALYTIKA AND VARIA + public const int U_GREEK_DIALYTIKA_AND_OXIA = 0x1FEE; // U+1FEE GREEK DIALYTIKA AND OXIA + public const int U_GREEK_VARIA = 0x1FEF; // U+1FEF GREEK VARIA + public const int U_GREEK_OXIA = 0x1FFD; // U+1FFD GREEK OXIA + public const int U_GREEK_DASIA = 0x1FFE; // U+1FFE GREEK DASIA public const int U_OVERLINE = 0x203E; // Unicode Character "OVERLINE" diff --git a/src/Protocol/Client/Capabilities/CallHierarchyCapability.cs b/src/Protocol/Client/Capabilities/CallHierarchyCapability.cs index 7e0204f13..e0b6ff253 100644 --- a/src/Protocol/Client/Capabilities/CallHierarchyCapability.cs +++ b/src/Protocol/Client/Capabilities/CallHierarchyCapability.cs @@ -10,7 +10,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities /// [Obsolete(Constants.Proposal)] public class CallHierarchyCapability : DynamicCapability, ConnectedCapability, - ConnectedCapability, ConnectedCapability + ConnectedCapability, ConnectedCapability { } } diff --git a/src/Protocol/Client/Capabilities/ClientCapabilitiesExtensions.cs b/src/Protocol/Client/Capabilities/ClientCapabilitiesExtensions.cs index 97ccb670c..36d3b0804 100644 --- a/src/Protocol/Client/Capabilities/ClientCapabilitiesExtensions.cs +++ b/src/Protocol/Client/Capabilities/ClientCapabilitiesExtensions.cs @@ -4,15 +4,15 @@ public static class ClientCapabilitiesExtensions { /// /// Best attempt to determine if the hosting client supports a specific protocol version - /// + /// /// Capability are new as of 3.0, but the field existed before so it's possible - /// it could be passed as an empty object + /// it could be passed as an empty object /// /// The capabilities. /// ClientVersion. public static ClientVersion GetClientVersion(this ClientCapabilities clientCapabilities) { - if (clientCapabilities == null || (clientCapabilities.TextDocument == null && clientCapabilities.Workspace == null)) + if (clientCapabilities == null || clientCapabilities.TextDocument == null && clientCapabilities.Workspace == null) return ClientVersion.Lsp2; return ClientVersion.Lsp3; } diff --git a/src/Protocol/Client/Capabilities/CodeLensCapability.cs b/src/Protocol/Client/Capabilities/CodeLensCapability.cs index f7d22e0c9..d716b5465 100644 --- a/src/Protocol/Client/Capabilities/CodeLensCapability.cs +++ b/src/Protocol/Client/Capabilities/CodeLensCapability.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class CodeLensCapability : DynamicCapability, ConnectedCapability { } + public class CodeLensCapability : DynamicCapability, ConnectedCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/ColorProviderCapability.cs b/src/Protocol/Client/Capabilities/ColorProviderCapability.cs index b89654280..277431aa4 100644 --- a/src/Protocol/Client/Capabilities/ColorProviderCapability.cs +++ b/src/Protocol/Client/Capabilities/ColorProviderCapability.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class ColorProviderCapability : DynamicCapability, ConnectedCapability, ConnectedCapability { } + public class ColorProviderCapability : DynamicCapability, ConnectedCapability, ConnectedCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/CompletionCapability.cs b/src/Protocol/Client/Capabilities/CompletionCapability.cs index 896c5359c..072563f18 100644 --- a/src/Protocol/Client/Capabilities/CompletionCapability.cs +++ b/src/Protocol/Client/Capabilities/CompletionCapability.cs @@ -19,7 +19,7 @@ public class CompletionCapability : DynamicCapability, ConnectedCapability - /// The client supports to send additional context information for a `textDocument/completion` request. + /// The client supports to send additional context information for a `textDocument/completion` request. /// [Optional] public bool ContextSupport { get; set; } diff --git a/src/Protocol/Client/Capabilities/ConnectedCapability.cs b/src/Protocol/Client/Capabilities/ConnectedCapability.cs index 8e1b74282..a30280b7a 100644 --- a/src/Protocol/Client/Capabilities/ConnectedCapability.cs +++ b/src/Protocol/Client/Capabilities/ConnectedCapability.cs @@ -4,5 +4,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { internal interface ConnectedCapability : ICapability where T : IJsonRpcHandler - { } + { + } } diff --git a/src/Protocol/Client/Capabilities/DeclarationCapability.cs b/src/Protocol/Client/Capabilities/DeclarationCapability.cs index 49a32d7af..f23ccfeec 100644 --- a/src/Protocol/Client/Capabilities/DeclarationCapability.cs +++ b/src/Protocol/Client/Capabilities/DeclarationCapability.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class DeclarationCapability : LinkSupportCapability, ConnectedCapability { } + public class DeclarationCapability : LinkSupportCapability, ConnectedCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/DefinitionCapability.cs b/src/Protocol/Client/Capabilities/DefinitionCapability.cs index 980bffbf6..db3d240be 100644 --- a/src/Protocol/Client/Capabilities/DefinitionCapability.cs +++ b/src/Protocol/Client/Capabilities/DefinitionCapability.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class DefinitionCapability : LinkSupportCapability, ConnectedCapability { } + public class DefinitionCapability : LinkSupportCapability, ConnectedCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/DidChangeConfigurationCapability.cs b/src/Protocol/Client/Capabilities/DidChangeConfigurationCapability.cs index dbc2360d4..13e8268c7 100644 --- a/src/Protocol/Client/Capabilities/DidChangeConfigurationCapability.cs +++ b/src/Protocol/Client/Capabilities/DidChangeConfigurationCapability.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class DidChangeConfigurationCapability : DynamicCapability { } + public class DidChangeConfigurationCapability : DynamicCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/DidChangeWatchedFilesCapability.cs b/src/Protocol/Client/Capabilities/DidChangeWatchedFilesCapability.cs index 6f8112da3..421436594 100644 --- a/src/Protocol/Client/Capabilities/DidChangeWatchedFilesCapability.cs +++ b/src/Protocol/Client/Capabilities/DidChangeWatchedFilesCapability.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class DidChangeWatchedFilesCapability : DynamicCapability { } + public class DidChangeWatchedFilesCapability : DynamicCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/DocumentFormattingCapability.cs b/src/Protocol/Client/Capabilities/DocumentFormattingCapability.cs index d3e7b990e..f87410675 100644 --- a/src/Protocol/Client/Capabilities/DocumentFormattingCapability.cs +++ b/src/Protocol/Client/Capabilities/DocumentFormattingCapability.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class DocumentFormattingCapability : DynamicCapability, ConnectedCapability { } + public class DocumentFormattingCapability : DynamicCapability, ConnectedCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/DocumentHighlightCapability.cs b/src/Protocol/Client/Capabilities/DocumentHighlightCapability.cs index aa6cc7bba..899dbfd13 100644 --- a/src/Protocol/Client/Capabilities/DocumentHighlightCapability.cs +++ b/src/Protocol/Client/Capabilities/DocumentHighlightCapability.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class DocumentHighlightCapability : DynamicCapability, ConnectedCapability { } + public class DocumentHighlightCapability : DynamicCapability, ConnectedCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/DocumentOnTypeFormattingCapability.cs b/src/Protocol/Client/Capabilities/DocumentOnTypeFormattingCapability.cs index e6584e1cb..fd95c6066 100644 --- a/src/Protocol/Client/Capabilities/DocumentOnTypeFormattingCapability.cs +++ b/src/Protocol/Client/Capabilities/DocumentOnTypeFormattingCapability.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class DocumentOnTypeFormattingCapability : DynamicCapability, ConnectedCapability { } + public class DocumentOnTypeFormattingCapability : DynamicCapability, ConnectedCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/DocumentRangeFormattingCapability.cs b/src/Protocol/Client/Capabilities/DocumentRangeFormattingCapability.cs index 5b578f7d1..f8429aa19 100644 --- a/src/Protocol/Client/Capabilities/DocumentRangeFormattingCapability.cs +++ b/src/Protocol/Client/Capabilities/DocumentRangeFormattingCapability.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class DocumentRangeFormattingCapability : DynamicCapability, ConnectedCapability { } + public class DocumentRangeFormattingCapability : DynamicCapability, ConnectedCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/DocumentSymbolCapability.cs b/src/Protocol/Client/Capabilities/DocumentSymbolCapability.cs index db88573a6..935715ca8 100644 --- a/src/Protocol/Client/Capabilities/DocumentSymbolCapability.cs +++ b/src/Protocol/Client/Capabilities/DocumentSymbolCapability.cs @@ -13,7 +13,7 @@ public class DocumentSymbolCapability : DynamicCapability, ConnectedCapability - /// Whether document symbol supports hierarchical `DocumentSymbol`s. + /// Whether document symbol supports hierarchical `DocumentSymbol`s. /// [Optional] public bool? HierarchicalDocumentSymbolSupport { get; set; } diff --git a/src/Protocol/Client/Capabilities/DynamicCapability.cs b/src/Protocol/Client/Capabilities/DynamicCapability.cs index d5019acf7..77b96966e 100644 --- a/src/Protocol/Client/Capabilities/DynamicCapability.cs +++ b/src/Protocol/Client/Capabilities/DynamicCapability.cs @@ -8,7 +8,8 @@ public class DynamicCapability : IDynamicCapability /// /// Whether completion supports dynamic registration. /// - [Optional, EditorBrowsable(EditorBrowsableState.Never)] + [Optional] + [EditorBrowsable(EditorBrowsableState.Never)] public bool DynamicRegistration { get; set; } } } diff --git a/src/Protocol/Client/Capabilities/ExecuteCommandCapability.cs b/src/Protocol/Client/Capabilities/ExecuteCommandCapability.cs index c0a78a594..bdb18ce5e 100644 --- a/src/Protocol/Client/Capabilities/ExecuteCommandCapability.cs +++ b/src/Protocol/Client/Capabilities/ExecuteCommandCapability.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class ExecuteCommandCapability : DynamicCapability, ConnectedCapability { } + public class ExecuteCommandCapability : DynamicCapability, ConnectedCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/ICapability.cs b/src/Protocol/Client/Capabilities/ICapability.cs index aedb6abf6..ae30c5a9c 100644 --- a/src/Protocol/Client/Capabilities/ICapability.cs +++ b/src/Protocol/Client/Capabilities/ICapability.cs @@ -2,6 +2,5 @@ { public interface ICapability { - } } diff --git a/src/Protocol/Client/Capabilities/ImplementationCapability.cs b/src/Protocol/Client/Capabilities/ImplementationCapability.cs index 59ece36ee..b3d6dd8bf 100644 --- a/src/Protocol/Client/Capabilities/ImplementationCapability.cs +++ b/src/Protocol/Client/Capabilities/ImplementationCapability.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class ImplementationCapability : LinkSupportCapability, ConnectedCapability { } + public class ImplementationCapability : LinkSupportCapability, ConnectedCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/LinkSupportCapability.cs b/src/Protocol/Client/Capabilities/LinkSupportCapability.cs index ed7e24b66..410aad3bd 100644 --- a/src/Protocol/Client/Capabilities/LinkSupportCapability.cs +++ b/src/Protocol/Client/Capabilities/LinkSupportCapability.cs @@ -4,7 +4,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { public abstract class LinkSupportCapability : DynamicCapability { - [Optional] - public bool LinkSupport { get; set; } + [Optional] public bool LinkSupport { get; set; } } } diff --git a/src/Protocol/Client/Capabilities/PublishDiagnosticsCapability.cs b/src/Protocol/Client/Capabilities/PublishDiagnosticsCapability.cs index 848026c67..a69af0326 100644 --- a/src/Protocol/Client/Capabilities/PublishDiagnosticsCapability.cs +++ b/src/Protocol/Client/Capabilities/PublishDiagnosticsCapability.cs @@ -5,7 +5,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities /// /// Capabilities specific to `textDocument/publishDiagnostics`. /// - public class PublishDiagnosticsCapability: ICapability + public class PublishDiagnosticsCapability : ICapability { /// /// Whether the clients accepts diagnostics with related information. diff --git a/src/Protocol/Client/Capabilities/ReferenceCapability.cs b/src/Protocol/Client/Capabilities/ReferenceCapability.cs index a759d372a..1c54f2c45 100644 --- a/src/Protocol/Client/Capabilities/ReferenceCapability.cs +++ b/src/Protocol/Client/Capabilities/ReferenceCapability.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class ReferenceCapability : DynamicCapability, ConnectedCapability { } + public class ReferenceCapability : DynamicCapability, ConnectedCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/SemanticTokensCapability.cs b/src/Protocol/Client/Capabilities/SemanticTokensCapability.cs index 401e248bd..0afefb118 100644 --- a/src/Protocol/Client/Capabilities/SemanticTokensCapability.cs +++ b/src/Protocol/Client/Capabilities/SemanticTokensCapability.cs @@ -12,7 +12,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities /// [Obsolete(Constants.Proposal)] public class SemanticTokensCapability : DynamicCapability, ConnectedCapability, - ConnectedCapability, ConnectedCapability + ConnectedCapability, ConnectedCapability { /// /// Which requests the client supports and might send to the server. diff --git a/src/Protocol/Client/Capabilities/SemanticTokensCapabilityRequestFull.cs b/src/Protocol/Client/Capabilities/SemanticTokensCapabilityRequestFull.cs index fbba5f343..d6de1af4b 100644 --- a/src/Protocol/Client/Capabilities/SemanticTokensCapabilityRequestFull.cs +++ b/src/Protocol/Client/Capabilities/SemanticTokensCapabilityRequestFull.cs @@ -15,4 +15,4 @@ public class SemanticTokensCapabilityRequestFull [Optional] public bool Delta { get; set; } } -} \ No newline at end of file +} diff --git a/src/Protocol/Client/Capabilities/SemanticTokensCapabilityRequestRange.cs b/src/Protocol/Client/Capabilities/SemanticTokensCapabilityRequestRange.cs index 25456bf4c..eec213e54 100644 --- a/src/Protocol/Client/Capabilities/SemanticTokensCapabilityRequestRange.cs +++ b/src/Protocol/Client/Capabilities/SemanticTokensCapabilityRequestRange.cs @@ -7,4 +7,4 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities public class SemanticTokensCapabilityRequestRange { } -} \ No newline at end of file +} diff --git a/src/Protocol/Client/Capabilities/SemanticTokensCapabilityRequests.cs b/src/Protocol/Client/Capabilities/SemanticTokensCapabilityRequests.cs index dc97bae4b..6edead047 100644 --- a/src/Protocol/Client/Capabilities/SemanticTokensCapabilityRequests.cs +++ b/src/Protocol/Client/Capabilities/SemanticTokensCapabilityRequests.cs @@ -1,4 +1,3 @@ -using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities diff --git a/src/Protocol/Client/Capabilities/SynchronizationCapability.cs b/src/Protocol/Client/Capabilities/SynchronizationCapability.cs index 8c43d74c2..13c9d3d81 100644 --- a/src/Protocol/Client/Capabilities/SynchronizationCapability.cs +++ b/src/Protocol/Client/Capabilities/SynchronizationCapability.cs @@ -4,12 +4,12 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { public class SynchronizationCapability : DynamicCapability, - ConnectedCapability, - ConnectedCapability, - ConnectedCapability, - ConnectedCapability, - ConnectedCapability, - ConnectedCapability + ConnectedCapability, + ConnectedCapability, + ConnectedCapability, + ConnectedCapability, + ConnectedCapability, + ConnectedCapability { /// /// The client supports sending will save notifications. diff --git a/src/Protocol/Client/Capabilities/TypeDefinitionCapability.cs b/src/Protocol/Client/Capabilities/TypeDefinitionCapability.cs index 1f4d58d20..ee62d0660 100644 --- a/src/Protocol/Client/Capabilities/TypeDefinitionCapability.cs +++ b/src/Protocol/Client/Capabilities/TypeDefinitionCapability.cs @@ -2,5 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class TypeDefinitionCapability : LinkSupportCapability, ConnectedCapability { } + public class TypeDefinitionCapability : LinkSupportCapability, ConnectedCapability + { + } } diff --git a/src/Protocol/Client/Capabilities/WorkspaceEditCapability.cs b/src/Protocol/Client/Capabilities/WorkspaceEditCapability.cs index 419b53a60..21fa88738 100644 --- a/src/Protocol/Client/Capabilities/WorkspaceEditCapability.cs +++ b/src/Protocol/Client/Capabilities/WorkspaceEditCapability.cs @@ -3,22 +3,24 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities { - public class WorkspaceEditCapability: ICapability + public class WorkspaceEditCapability : ICapability { /// /// The client supports versioned document changes in `WorkspaceEdit`s /// [Optional] public bool DocumentChanges { get; set; } + /// - /// The resource operations the client supports. Clients should at least - /// support 'create', 'rename' and 'delete' files and folders. + /// The resource operations the client supports. Clients should at least + /// support 'create', 'rename' and 'delete' files and folders. /// [Optional] public ResourceOperationKind[] ResourceOperations { get; set; } + /// - /// The failure handling strategy of a client if applying the workspace edit - /// fails. + /// The failure handling strategy of a client if applying the workspace edit + /// fails. /// [Optional] public FailureHandlingKind? FailureHandling { get; set; } diff --git a/src/Protocol/Client/ClientLanguageClient.cs b/src/Protocol/Client/ClientLanguageClient.cs index 39db8418f..ee48cd282 100644 --- a/src/Protocol/Client/ClientLanguageClient.cs +++ b/src/Protocol/Client/ClientLanguageClient.cs @@ -1,14 +1,15 @@ using System; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { internal class ClientLanguageClient : LanguageProtocolProxy, IClientLanguageClient { - public ClientLanguageClient(IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, - ILanguageProtocolSettings languageProtocolSettings) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) + public ClientLanguageClient( + IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, + ILanguageProtocolSettings languageProtocolSettings + ) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) { } } diff --git a/src/Protocol/Client/GeneralLanguageClient.cs b/src/Protocol/Client/GeneralLanguageClient.cs index 5e637c93c..5b4af69ea 100644 --- a/src/Protocol/Client/GeneralLanguageClient.cs +++ b/src/Protocol/Client/GeneralLanguageClient.cs @@ -1,14 +1,15 @@ using System; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { internal class GeneralLanguageClient : LanguageProtocolProxy, IGeneralLanguageClient { - public GeneralLanguageClient(IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, - ILanguageProtocolSettings languageProtocolSettings) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) + public GeneralLanguageClient( + IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, + ILanguageProtocolSettings languageProtocolSettings + ) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) { } } diff --git a/src/Protocol/Client/IClientLanguageClient.cs b/src/Protocol/Client/IClientLanguageClient.cs index 1aa4878ca..e7593796a 100644 --- a/src/Protocol/Client/IClientLanguageClient.cs +++ b/src/Protocol/Client/IClientLanguageClient.cs @@ -1,6 +1,6 @@ -using OmniSharp.Extensions.JsonRpc; - namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { - public interface IClientLanguageClient : ILanguageClientProxy { } + public interface IClientLanguageClient : ILanguageClientProxy + { + } } diff --git a/src/Protocol/Client/IGeneralLanguageClient.cs b/src/Protocol/Client/IGeneralLanguageClient.cs index d3df50ea5..e80ba607e 100644 --- a/src/Protocol/Client/IGeneralLanguageClient.cs +++ b/src/Protocol/Client/IGeneralLanguageClient.cs @@ -1,6 +1,6 @@ -using OmniSharp.Extensions.JsonRpc; - -namespace OmniSharp.Extensions.LanguageServer.Protocol.Client +namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { - public interface IGeneralLanguageClient : ILanguageClientProxy { } + public interface IGeneralLanguageClient : ILanguageClientProxy + { + } } diff --git a/src/Protocol/Client/ILanguageClient.cs b/src/Protocol/Client/ILanguageClient.cs index e8c756eec..158f82398 100644 --- a/src/Protocol/Client/ILanguageClient.cs +++ b/src/Protocol/Client/ILanguageClient.cs @@ -4,7 +4,6 @@ using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Progress; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { diff --git a/src/Protocol/Client/ILogTraceHandler.cs b/src/Protocol/Client/ILogTraceHandler.cs index 5cbfcc928..c7973b4f9 100644 --- a/src/Protocol/Client/ILogTraceHandler.cs +++ b/src/Protocol/Client/ILogTraceHandler.cs @@ -8,9 +8,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { - [Parallel, Method(GeneralNames.LogTrace, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IClientLanguageServer), typeof(ILanguageServer))] - public interface ILogTraceHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(GeneralNames.LogTrace, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IClientLanguageServer), typeof(ILanguageServer))] + public interface ILogTraceHandler : IJsonRpcNotificationHandler + { + } public abstract class LogTraceHandler : ILogTraceHandler { diff --git a/src/Protocol/Client/IOnLanguageClientInitialize.cs b/src/Protocol/Client/IOnLanguageClientInitialize.cs index dfe984ca2..95e2c26fa 100644 --- a/src/Protocol/Client/IOnLanguageClientInitialize.cs +++ b/src/Protocol/Client/IOnLanguageClientInitialize.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { /// /// Gives your class or handler an opportunity to interact with - /// the before it is sent to the server + /// the before it is sent to the server /// public interface IOnLanguageClientInitialize : IEventingHandler { diff --git a/src/Protocol/Client/IOnLanguageClientInitialized.cs b/src/Protocol/Client/IOnLanguageClientInitialized.cs index 2589a458b..cccff19b4 100644 --- a/src/Protocol/Client/IOnLanguageClientInitialized.cs +++ b/src/Protocol/Client/IOnLanguageClientInitialized.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { /// /// Gives your class or handler an opportunity to interact with - /// the and before it is processed by the client. + /// the and before it is processed by the client. /// public interface IOnLanguageClientInitialized : IEventingHandler { diff --git a/src/Protocol/Client/IOnLanguageClientStarted.cs b/src/Protocol/Client/IOnLanguageClientStarted.cs index 89778cc42..e8e57ad1f 100644 --- a/src/Protocol/Client/IOnLanguageClientStarted.cs +++ b/src/Protocol/Client/IOnLanguageClientStarted.cs @@ -1,13 +1,12 @@ using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { /// /// Gives your class or handler an opportunity to interact with - /// the after the connection has been established. + /// the after the connection has been established. /// public interface IOnLanguageClientStarted : IEventingHandler { diff --git a/src/Protocol/Client/IRegisterCapabilityHandler.cs b/src/Protocol/Client/IRegisterCapabilityHandler.cs index ff0a10b67..080929a44 100644 --- a/src/Protocol/Client/IRegisterCapabilityHandler.cs +++ b/src/Protocol/Client/IRegisterCapabilityHandler.cs @@ -8,8 +8,10 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { - [Parallel, Method(ClientNames.RegisterCapability, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IClientLanguageServer), typeof(ILanguageServer))] + [Parallel] + [Method(ClientNames.RegisterCapability, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IClientLanguageServer), typeof(ILanguageServer))] public interface IRegisterCapabilityHandler : IJsonRpcRequestHandler { } diff --git a/src/Protocol/Client/ITextDocumentLanguageClient.cs b/src/Protocol/Client/ITextDocumentLanguageClient.cs index d6248ada3..a156a7afc 100644 --- a/src/Protocol/Client/ITextDocumentLanguageClient.cs +++ b/src/Protocol/Client/ITextDocumentLanguageClient.cs @@ -1,6 +1,6 @@ -using OmniSharp.Extensions.JsonRpc; - namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { - public interface ITextDocumentLanguageClient : ILanguageClientProxy { } + public interface ITextDocumentLanguageClient : ILanguageClientProxy + { + } } diff --git a/src/Protocol/Client/IUnregisterCapabilityHandler.cs b/src/Protocol/Client/IUnregisterCapabilityHandler.cs index ee163eb86..b905ae39f 100644 --- a/src/Protocol/Client/IUnregisterCapabilityHandler.cs +++ b/src/Protocol/Client/IUnregisterCapabilityHandler.cs @@ -8,9 +8,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { - [Parallel, Method(ClientNames.UnregisterCapability, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IClientLanguageServer), typeof(ILanguageServer))] - public interface IUnregisterCapabilityHandler : IJsonRpcRequestHandler { } + [Parallel] + [Method(ClientNames.UnregisterCapability, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IClientLanguageServer), typeof(ILanguageServer))] + public interface IUnregisterCapabilityHandler : IJsonRpcRequestHandler + { + } public abstract class UnregisterCapabilityHandler : IUnregisterCapabilityHandler { diff --git a/src/Protocol/Client/IWindowLanguageClient.cs b/src/Protocol/Client/IWindowLanguageClient.cs index 11b7c9dd9..09e129f19 100644 --- a/src/Protocol/Client/IWindowLanguageClient.cs +++ b/src/Protocol/Client/IWindowLanguageClient.cs @@ -1,5 +1,3 @@ -using OmniSharp.Extensions.JsonRpc; - namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { public interface IWindowLanguageClient : ILanguageClientProxy diff --git a/src/Protocol/Client/IWorkspaceLanguageClient.cs b/src/Protocol/Client/IWorkspaceLanguageClient.cs index 820276428..c2401d94a 100644 --- a/src/Protocol/Client/IWorkspaceLanguageClient.cs +++ b/src/Protocol/Client/IWorkspaceLanguageClient.cs @@ -1,6 +1,6 @@ -using OmniSharp.Extensions.JsonRpc; - namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { - public interface IWorkspaceLanguageClient : ILanguageClientProxy { } + public interface IWorkspaceLanguageClient : ILanguageClientProxy + { + } } diff --git a/src/Protocol/Client/OnLanguageClientInitializeDelegate.cs b/src/Protocol/Client/OnLanguageClientInitializeDelegate.cs index 7aebe8711..c5d2ed668 100644 --- a/src/Protocol/Client/OnLanguageClientInitializeDelegate.cs +++ b/src/Protocol/Client/OnLanguageClientInitializeDelegate.cs @@ -1,13 +1,12 @@ using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { /// /// Gives your class or handler an opportunity to interact with - /// the before it is sent to the server + /// the before it is sent to the server /// public delegate Task OnLanguageClientInitializeDelegate(ILanguageClient client, InitializeParams request, CancellationToken cancellationToken); } diff --git a/src/Protocol/Client/OnLanguageClientInitializedDelegate.cs b/src/Protocol/Client/OnLanguageClientInitializedDelegate.cs index 37505b477..51b4ec806 100644 --- a/src/Protocol/Client/OnLanguageClientInitializedDelegate.cs +++ b/src/Protocol/Client/OnLanguageClientInitializedDelegate.cs @@ -1,13 +1,12 @@ using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { /// /// Gives your class or handler an opportunity to interact with - /// the and before it is processed by the client. + /// the and before it is processed by the client. /// public delegate Task OnLanguageClientInitializedDelegate(ILanguageClient client, InitializeParams request, InitializeResult response, CancellationToken cancellationToken); } diff --git a/src/Protocol/Client/OnLanguageClientStartedDelegate.cs b/src/Protocol/Client/OnLanguageClientStartedDelegate.cs index b67a653d2..4e267bc6f 100644 --- a/src/Protocol/Client/OnLanguageClientStartedDelegate.cs +++ b/src/Protocol/Client/OnLanguageClientStartedDelegate.cs @@ -1,12 +1,11 @@ using System.Threading; using System.Threading.Tasks; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { /// /// Gives your class or handler an opportunity to interact with - /// the after the connection has been established. + /// the after the connection has been established. /// public delegate Task OnLanguageClientStartedDelegate(ILanguageClient client, CancellationToken cancellationToken); } diff --git a/src/Protocol/Client/TextDocumentLanguageClient.cs b/src/Protocol/Client/TextDocumentLanguageClient.cs index d0c49e7b2..8b3f31a78 100644 --- a/src/Protocol/Client/TextDocumentLanguageClient.cs +++ b/src/Protocol/Client/TextDocumentLanguageClient.cs @@ -1,14 +1,15 @@ using System; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { internal class TextDocumentLanguageClient : LanguageProtocolProxy, ITextDocumentLanguageClient { - public TextDocumentLanguageClient(IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, - ILanguageProtocolSettings languageProtocolSettings) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) + public TextDocumentLanguageClient( + IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, + ILanguageProtocolSettings languageProtocolSettings + ) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) { } } diff --git a/src/Protocol/Client/WindowLanguageClient.cs b/src/Protocol/Client/WindowLanguageClient.cs index f4cd9e9e4..cc9d743cc 100644 --- a/src/Protocol/Client/WindowLanguageClient.cs +++ b/src/Protocol/Client/WindowLanguageClient.cs @@ -1,14 +1,15 @@ using System; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { internal class WindowLanguageClient : LanguageProtocolProxy, IWindowLanguageClient { - public WindowLanguageClient(IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, - ILanguageProtocolSettings languageProtocolSettings) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) + public WindowLanguageClient( + IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, + ILanguageProtocolSettings languageProtocolSettings + ) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) { } } diff --git a/src/Protocol/Client/WorkDone/LanguageClientWorkDoneManager.cs b/src/Protocol/Client/WorkDone/LanguageClientWorkDoneManager.cs index 93cf73f0c..eb0dc9b01 100644 --- a/src/Protocol/Client/WorkDone/LanguageClientWorkDoneManager.cs +++ b/src/Protocol/Client/WorkDone/LanguageClientWorkDoneManager.cs @@ -13,12 +13,11 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone { - class LanguageClientWorkDoneManager : IClientWorkDoneManager, IWorkDoneProgressCreateHandler + internal class LanguageClientWorkDoneManager : IClientWorkDoneManager, IWorkDoneProgressCreateHandler { private readonly IWindowLanguageClient _router; private readonly ISerializer _serializer; private readonly IProgressManager _progressManager; - private bool _supported; private readonly ConcurrentDictionary> _pendingWork; public LanguageClientWorkDoneManager(IWindowLanguageClient router, ISerializer serializer, IProgressManager progressManager) @@ -29,13 +28,11 @@ public LanguageClientWorkDoneManager(IWindowLanguageClient router, ISerializer s _pendingWork = new ConcurrentDictionary>(); } - public void Initialize(WindowClientCapabilities windowClientCapabilities) - { - _supported = windowClientCapabilities.WorkDoneProgress.IsSupported && - windowClientCapabilities.WorkDoneProgress.Value; - } + public void Initialize(WindowClientCapabilities windowClientCapabilities) => + IsSupported = windowClientCapabilities.WorkDoneProgress.IsSupported && + windowClientCapabilities.WorkDoneProgress.Value; - public bool IsSupported => _supported; + public bool IsSupported { get; private set; } public IProgressObservable Monitor(ProgressToken progressToken) { @@ -49,12 +46,14 @@ public IProgressObservable Monitor(ProgressToken progressToken Disposable.Create(() => _router.SendWorkDoneProgressCancel(progressToken)) ); _pendingWork.AddOrUpdate(progressToken, x => data, (a, b) => data); - data.Subscribe(_ => { }, () => { - if (_pendingWork.TryRemove(data.ProgressToken, out var item)) - { - item.Dispose(); + data.Subscribe( + _ => { }, () => { + if (_pendingWork.TryRemove(data.ProgressToken, out var item)) + { + item.Dispose(); + } } - }); + ); return data; } @@ -66,17 +65,17 @@ Task IRequestHandler.Handle(WorkDonePr private WorkDoneProgress Parse(JToken token) { - if (!(token is JObject obj) || !obj.TryGetValue("kind", out var kind)) throw new NotSupportedException("Unknown work done progress event"); + if (!( token is JObject obj ) || !obj.TryGetValue("kind", out var kind)) throw new NotSupportedException("Unknown work done progress event"); return kind.Value() switch { - "begin" => token.ToObject(_serializer.JsonSerializer), - "end" => token.ToObject(_serializer.JsonSerializer), + "begin" => token.ToObject(_serializer.JsonSerializer), + "end" => token.ToObject(_serializer.JsonSerializer), "report" => token.ToObject(_serializer.JsonSerializer), - _ => throw new NotSupportedException("Unknown work done progress event") + _ => throw new NotSupportedException("Unknown work done progress event") }; } } - class WorkDoneObservable : IProgressObservable + internal class WorkDoneObservable : IProgressObservable { private readonly IProgressObservable _progressObservable; private readonly IDisposable _triggerCancellation; diff --git a/src/Protocol/Client/WorkDone/WorkDoneProxyExtensions.cs b/src/Protocol/Client/WorkDone/WorkDoneProxyExtensions.cs index 45d7f6f2c..213388dc3 100644 --- a/src/Protocol/Client/WorkDone/WorkDoneProxyExtensions.cs +++ b/src/Protocol/Client/WorkDone/WorkDoneProxyExtensions.cs @@ -6,70 +6,90 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone { public static class WorkDoneProxyExtensions { - public static TResult ObserveWorkDone(this IClientLanguageClient proxy, T @params, Func func, IObserver observer) + public static TResult ObserveWorkDone( + this IClientLanguageClient proxy, T @params, Func func, IObserver observer + ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } - public static TResult ObserveWorkDone(this IClientLanguageClient proxy, T @params, Func func, IWorkDoneProgressObserver observer) + public static TResult ObserveWorkDone( + this IClientLanguageClient proxy, T @params, Func func, IWorkDoneProgressObserver observer + ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } - public static TResult ObserveWorkDone(this IGeneralLanguageClient proxy, T @params, Func func, IObserver observer) + public static TResult ObserveWorkDone( + this IGeneralLanguageClient proxy, T @params, Func func, IObserver observer + ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } - public static TResult ObserveWorkDone(this IGeneralLanguageClient proxy, T @params, Func func, IWorkDoneProgressObserver observer) + public static TResult ObserveWorkDone( + this IGeneralLanguageClient proxy, T @params, Func func, IWorkDoneProgressObserver observer + ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } - public static TResult ObserveWorkDone(this ITextDocumentLanguageClient proxy, T @params, Func func, IObserver observer) + public static TResult ObserveWorkDone( + this ITextDocumentLanguageClient proxy, T @params, Func func, IObserver observer + ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } - public static TResult ObserveWorkDone(this ITextDocumentLanguageClient proxy, T @params, Func func, IWorkDoneProgressObserver observer) + public static TResult ObserveWorkDone( + this ITextDocumentLanguageClient proxy, T @params, Func func, IWorkDoneProgressObserver observer + ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } - public static TResult ObserveWorkDone(this IWindowLanguageClient proxy, T @params, Func func, IObserver observer) + public static TResult ObserveWorkDone( + this IWindowLanguageClient proxy, T @params, Func func, IObserver observer + ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } - public static TResult ObserveWorkDone(this IWindowLanguageClient proxy, T @params, Func func, IWorkDoneProgressObserver observer) + public static TResult ObserveWorkDone( + this IWindowLanguageClient proxy, T @params, Func func, IWorkDoneProgressObserver observer + ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } - public static TResult ObserveWorkDone(this IWorkspaceLanguageClient proxy, T @params, Func func, IObserver observer) + public static TResult ObserveWorkDone( + this IWorkspaceLanguageClient proxy, T @params, Func func, IObserver observer + ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } - public static TResult ObserveWorkDone(this IWorkspaceLanguageClient proxy, T @params, Func func, IWorkDoneProgressObserver observer) + public static TResult ObserveWorkDone( + this IWorkspaceLanguageClient proxy, T @params, Func func, IWorkDoneProgressObserver observer + ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); @@ -102,7 +122,8 @@ private static void DoObserveWorkDone(ILanguageProtocolProxy proxy, IWorkDonePro } }, observer.OnError, - observer.OnCompleted); + observer.OnCompleted + ); } } } diff --git a/src/Protocol/Client/WorkspaceLanguageClient.cs b/src/Protocol/Client/WorkspaceLanguageClient.cs index 8917d31c5..995024097 100644 --- a/src/Protocol/Client/WorkspaceLanguageClient.cs +++ b/src/Protocol/Client/WorkspaceLanguageClient.cs @@ -1,14 +1,15 @@ using System; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client { internal class WorkspaceLanguageClient : LanguageProtocolProxy, IWorkspaceLanguageClient { - public WorkspaceLanguageClient(IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, - ILanguageProtocolSettings languageProtocolSettings) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) + public WorkspaceLanguageClient( + IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, + ILanguageProtocolSettings languageProtocolSettings + ) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) { } } diff --git a/src/Protocol/Document/ICodeActionHandler.cs b/src/Protocol/Document/ICodeActionHandler.cs index 504ca48c1..0182cd7b9 100644 --- a/src/Protocol/Document/ICodeActionHandler.cs +++ b/src/Protocol/Document/ICodeActionHandler.cs @@ -8,10 +8,12 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.CodeAction, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [Parallel] + [Method(TextDocumentNames.CodeAction, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface ICodeActionHandler : IJsonRpcRequestHandler, - IRegistration, ICapability + IRegistration, ICapability { } @@ -19,15 +21,14 @@ public abstract class CodeActionHandler : ICodeActionHandler { private readonly CodeActionRegistrationOptions _options; - public CodeActionHandler(CodeActionRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public CodeActionHandler(CodeActionRegistrationOptions registrationOptions) => _options = registrationOptions; public CodeActionRegistrationOptions GetRegistrationOptions() => _options; - public abstract Task Handle(CodeActionParams request, - CancellationToken cancellationToken); + public abstract Task Handle( + CodeActionParams request, + CancellationToken cancellationToken + ); public virtual void SetCapability(CodeActionCapability capability) => Capability = capability; protected CodeActionCapability Capability { get; private set; } diff --git a/src/Protocol/Document/ICodeLensHandler.cs b/src/Protocol/Document/ICodeLensHandler.cs index 4d3666c22..c5ac2840a 100644 --- a/src/Protocol/Document/ICodeLensHandler.cs +++ b/src/Protocol/Document/ICodeLensHandler.cs @@ -16,13 +16,15 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.CodeLens, Direction.ClientToServer)] + [Parallel] + [Method(TextDocumentNames.CodeLens, Direction.ClientToServer)] [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface ICodeLensHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } - [Parallel, Method(TextDocumentNames.CodeLensResolve, Direction.ClientToServer)] + [Parallel] + [Method(TextDocumentNames.CodeLensResolve, Direction.ClientToServer)] [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface ICodeLensResolveHandler : ICanBeResolvedHandler { @@ -49,8 +51,10 @@ public CodeLensHandler(CodeLensRegistrationOptions registrationOptions) public abstract class PartialCodeLensHandlerBase : AbstractHandlers.PartialResults, ICodeLensHandler, ICodeLensResolveHandler { - protected PartialCodeLensHandlerBase(CodeLensRegistrationOptions registrationOptions, IProgressManager progressManager) : base(registrationOptions, progressManager, - lenses => new CodeLensContainer(lenses)) + protected PartialCodeLensHandlerBase(CodeLensRegistrationOptions registrationOptions, IProgressManager progressManager) : base( + registrationOptions, progressManager, + lenses => new CodeLensContainer(lenses) + ) { } @@ -62,10 +66,7 @@ protected PartialCodeLensHandlerBase(CodeLensRegistrationOptions registrationOpt { private readonly ISerializer _serializer; - public CodeLensHandlerBase(CodeLensRegistrationOptions registrationOptions, ISerializer serializer) : base(registrationOptions) - { - _serializer = serializer; - } + public CodeLensHandlerBase(CodeLensRegistrationOptions registrationOptions, ISerializer serializer) : base(registrationOptions) => _serializer = serializer; public sealed override async Task Handle(CodeLensParams request, CancellationToken cancellationToken) @@ -88,19 +89,20 @@ public sealed override async Task Handle(CodeLens request, Cancellatio { private readonly ISerializer _serializer; - protected PartialCodeLensHandlerBase(CodeLensRegistrationOptions registrationOptions, IProgressManager progressManager, ISerializer serializer) : base(registrationOptions, - progressManager) - { + protected PartialCodeLensHandlerBase(CodeLensRegistrationOptions registrationOptions, IProgressManager progressManager, ISerializer serializer) : base( + registrationOptions, + progressManager + ) => _serializer = serializer; - } protected sealed override void Handle(CodeLensParams request, IObserver> results, CancellationToken cancellationToken) => Handle( request, Observer.Create>>( - x => results.OnNext(x.Select(z => (CodeLens)z)), + x => results.OnNext(x.Select(z => (CodeLens) z)), results.OnError, results.OnCompleted - ), cancellationToken); + ), cancellationToken + ); public sealed override async Task Handle(CodeLens request, CancellationToken cancellationToken) { @@ -114,161 +116,199 @@ public sealed override async Task Handle(CodeLens request, Cancellatio public static partial class CodeLensExtensions { - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Func> handler, - CodeLensRegistrationOptions registrationOptions) - { - return OnCodeLens(registry, handler, null, registrationOptions); - } + CodeLensRegistrationOptions registrationOptions + ) => + OnCodeLens(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Func> handler, Func> resolveHandler, - CodeLensRegistrationOptions registrationOptions) + CodeLensRegistrationOptions registrationOptions + ) { registrationOptions ??= new CodeLensRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (link, cap, token) => Task.FromResult(link); var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.CodeLens, - new LanguageProtocolDelegatingHandlers.Request( - id, - handler, - registrationOptions)) - .AddHandler(TextDocumentNames.CodeLensResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.CodeLens, + new LanguageProtocolDelegatingHandlers.Request( + id, + handler, + registrationOptions + ) + ) + .AddHandler( + TextDocumentNames.CodeLensResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Func>> handler, Func, CodeLensCapability, CancellationToken, Task>> resolveHandler, - CodeLensRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + CodeLensRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new CodeLensRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (link, c, token) => Task.FromResult(link); - return registry.AddHandler(_ => new DelegatingCodeLensHandler( - registrationOptions, - _.GetRequiredService(), - handler, - resolveHandler) + return registry.AddHandler( + _ => new DelegatingCodeLensHandler( + registrationOptions, + _.GetRequiredService(), + handler, + resolveHandler + ) ); } - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Func> handler, - CodeLensRegistrationOptions registrationOptions) - { - return OnCodeLens(registry, handler, null, registrationOptions); - } + CodeLensRegistrationOptions registrationOptions + ) => + OnCodeLens(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Func> handler, Func> resolveHandler, - CodeLensRegistrationOptions registrationOptions) + CodeLensRegistrationOptions registrationOptions + ) { registrationOptions ??= new CodeLensRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (link, token) => Task.FromResult(link); var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.CodeLens, - new LanguageProtocolDelegatingHandlers.RequestRegistration( - id, - handler, - registrationOptions)) - .AddHandler(TextDocumentNames.CodeLensResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.CodeLens, + new LanguageProtocolDelegatingHandlers.RequestRegistration( + id, + handler, + registrationOptions + ) + ) + .AddHandler( + TextDocumentNames.CodeLensResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Func>> handler, Func, CancellationToken, Task>> resolveHandler, - CodeLensRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + CodeLensRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new CodeLensRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (link, token) => Task.FromResult(link); - return registry.AddHandler(_ => new DelegatingCodeLensHandler( - registrationOptions, - _.GetRequiredService(), - (@params, capability, token) => handler(@params, token), - (lens, capability, token) => resolveHandler(lens, token)) + return registry.AddHandler( + _ => new DelegatingCodeLensHandler( + registrationOptions, + _.GetRequiredService(), + (@params, capability, token) => handler(@params, token), + (lens, capability, token) => resolveHandler(lens, token) + ) ); } - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Func> handler, - CodeLensRegistrationOptions registrationOptions) - { - return OnCodeLens(registry, handler, null, registrationOptions); - } + CodeLensRegistrationOptions registrationOptions + ) => + OnCodeLens(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Func> handler, Func> resolveHandler, - CodeLensRegistrationOptions registrationOptions) + CodeLensRegistrationOptions registrationOptions + ) { registrationOptions ??= new CodeLensRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= Task.FromResult; var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.CodeLens, - new LanguageProtocolDelegatingHandlers.RequestRegistration( - id, - handler, - registrationOptions)) - .AddHandler(TextDocumentNames.CodeLensResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.CodeLens, + new LanguageProtocolDelegatingHandlers.RequestRegistration( + id, + handler, + registrationOptions + ) + ) + .AddHandler( + TextDocumentNames.CodeLensResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Func>> handler, Func, Task>> resolveHandler, - CodeLensRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + CodeLensRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new CodeLensRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= Task.FromResult; - return registry.AddHandler(_ => new DelegatingCodeLensHandler( - registrationOptions, - _.GetRequiredService(), - (@params, capability, token) => handler(@params), - (lens, capability, token) => resolveHandler(lens)) + return registry.AddHandler( + _ => new DelegatingCodeLensHandler( + registrationOptions, + _.GetRequiredService(), + (@params, capability, token) => handler(@params), + (lens, capability, token) => resolveHandler(lens) + ) ); } - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Action>, CodeLensCapability, CancellationToken> handler, - CodeLensRegistrationOptions registrationOptions) - { - return OnCodeLens(registry, handler, null, registrationOptions); - } + CodeLensRegistrationOptions registrationOptions + ) => + OnCodeLens(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Action>, CodeLensCapability, CancellationToken> handler, Func> resolveHandler, - CodeLensRegistrationOptions registrationOptions) + CodeLensRegistrationOptions registrationOptions + ) { registrationOptions ??= new CodeLensRegistrationOptions(); registrationOptions.ResolveProvider = true; @@ -276,143 +316,177 @@ public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry re var id = Guid.NewGuid(); return - registry.AddHandler(TextDocumentNames.CodeLens, - _ => new LanguageProtocolDelegatingHandlers.PartialResults( - id, - handler, - registrationOptions, - _.GetRequiredService(), - x => new CodeLensContainer(x))) - .AddHandler(TextDocumentNames.CodeLensResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + registry.AddHandler( + TextDocumentNames.CodeLens, + _ => new LanguageProtocolDelegatingHandlers.PartialResults( + id, + handler, + registrationOptions, + _.GetRequiredService(), + x => new CodeLensContainer(x) + ) + ) + .AddHandler( + TextDocumentNames.CodeLensResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Action>>, CodeLensCapability, CancellationToken> handler, Func, CodeLensCapability, CancellationToken, Task>> resolveHandler, - CodeLensRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + CodeLensRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new CodeLensRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (lens, capability, token) => Task.FromResult(lens); - return registry.AddHandler(_ => new DelegatingPartialCodeLensHandler( - registrationOptions, - _.GetRequiredService(), - _.GetRequiredService(), - handler, - resolveHandler) + return registry.AddHandler( + _ => new DelegatingPartialCodeLensHandler( + registrationOptions, + _.GetRequiredService(), + _.GetRequiredService(), + handler, + resolveHandler + ) ); } - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Action>, CancellationToken> handler, - CodeLensRegistrationOptions registrationOptions) - { - return OnCodeLens(registry, handler, null, registrationOptions); - } + CodeLensRegistrationOptions registrationOptions + ) => + OnCodeLens(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Action>, CancellationToken> handler, Func> resolveHandler, - CodeLensRegistrationOptions registrationOptions) + CodeLensRegistrationOptions registrationOptions + ) { registrationOptions ??= new CodeLensRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (lens, token) => Task.FromResult(lens); var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.CodeLens, - _ => new LanguageProtocolDelegatingHandlers.PartialResults( - id, - handler, - registrationOptions, - _.GetRequiredService(), - x => new CodeLensContainer(x))) - .AddHandler(TextDocumentNames.CodeLensResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.CodeLens, + _ => new LanguageProtocolDelegatingHandlers.PartialResults( + id, + handler, + registrationOptions, + _.GetRequiredService(), + x => new CodeLensContainer(x) + ) + ) + .AddHandler( + TextDocumentNames.CodeLensResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Action>>, CancellationToken> handler, Func, CancellationToken, Task>> resolveHandler, - CodeLensRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + CodeLensRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new CodeLensRegistrationOptions(); registrationOptions.ResolveProvider = true; - resolveHandler ??= (lens, token) => Task.FromResult(lens); - - return registry.AddHandler(_ => new DelegatingPartialCodeLensHandler( - registrationOptions, - _.GetRequiredService(), - _.GetRequiredService(), - (@params, observer, capability, token) => handler(@params, observer, token), - (lens, capability, token) => resolveHandler(lens, token)) + resolveHandler ??= (lens, token) => Task.FromResult(lens); + + return registry.AddHandler( + _ => new DelegatingPartialCodeLensHandler( + registrationOptions, + _.GetRequiredService(), + _.GetRequiredService(), + (@params, observer, capability, token) => handler(@params, observer, token), + (lens, capability, token) => resolveHandler(lens, token) + ) ); } - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Action>> handler, - CodeLensRegistrationOptions registrationOptions) - { - return OnCodeLens(registry, handler, null, registrationOptions); - } + CodeLensRegistrationOptions registrationOptions + ) => + OnCodeLens(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Action>> handler, Func> resolveHandler, - CodeLensRegistrationOptions registrationOptions) + CodeLensRegistrationOptions registrationOptions + ) { registrationOptions ??= new CodeLensRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= Task.FromResult; var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.CodeLens, - _ => new LanguageProtocolDelegatingHandlers.PartialResults( - id, - handler, - registrationOptions, - _.GetRequiredService(), - x => new CodeLensContainer(x))) - .AddHandler(TextDocumentNames.CodeLensResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.CodeLens, + _ => new LanguageProtocolDelegatingHandlers.PartialResults( + id, + handler, + registrationOptions, + _.GetRequiredService(), + x => new CodeLensContainer(x) + ) + ) + .AddHandler( + TextDocumentNames.CodeLensResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnCodeLens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCodeLens( + this ILanguageServerRegistry registry, Action>>> handler, Func, Task>> resolveHandler, - CodeLensRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + CodeLensRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new CodeLensRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= Task.FromResult; - return registry.AddHandler(_ => new DelegatingPartialCodeLensHandler( - registrationOptions, - _.GetRequiredService(), - _.GetRequiredService(), - (@params, observer, capability, token) => handler(@params, observer), - (lens, capability, token) => resolveHandler(lens)) + return registry.AddHandler( + _ => new DelegatingPartialCodeLensHandler( + registrationOptions, + _.GetRequiredService(), + _.GetRequiredService(), + (@params, observer, capability, token) => handler(@params, observer), + (lens, capability, token) => resolveHandler(lens) + ) ); } - class DelegatingCodeLensHandler : CodeLensHandlerBase where T : HandlerIdentity, new() + private class DelegatingCodeLensHandler : CodeLensHandlerBase where T : HandlerIdentity, new() { private readonly Func>> _handleParams; private readonly Func, CodeLensCapability, CancellationToken, Task>> _handleResolve; @@ -434,7 +508,7 @@ protected override Task> HandleParams(CodeLensParams reques protected override Task> HandleResolve(CodeLens request, CancellationToken cancellationToken) => _handleResolve(request, Capability, cancellationToken); } - class DelegatingPartialCodeLensHandler : PartialCodeLensHandlerBase where T : HandlerIdentity, new() + private class DelegatingPartialCodeLensHandler : PartialCodeLensHandlerBase where T : HandlerIdentity, new() { private readonly Action>>, CodeLensCapability, CancellationToken> _handleParams; private readonly Func, CodeLensCapability, CancellationToken, Task>> _handleResolve; diff --git a/src/Protocol/Document/IColorPresentationHandler.cs b/src/Protocol/Document/IColorPresentationHandler.cs index bfeb7d16d..1e15e011b 100644 --- a/src/Protocol/Document/IColorPresentationHandler.cs +++ b/src/Protocol/Document/IColorPresentationHandler.cs @@ -8,17 +8,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.ColorPresentation, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IColorPresentationHandler : IJsonRpcRequestHandler>, IRegistration, ICapability { } + [Parallel] + [Method(TextDocumentNames.ColorPresentation, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IColorPresentationHandler : IJsonRpcRequestHandler>, IRegistration, + ICapability + { + } public abstract class ColorPresentationHandler : IColorPresentationHandler { private readonly DocumentColorRegistrationOptions _options; - public ColorPresentationHandler(DocumentColorRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public ColorPresentationHandler(DocumentColorRegistrationOptions registrationOptions) => _options = registrationOptions; public DocumentColorRegistrationOptions GetRegistrationOptions() => _options; public abstract Task> Handle(ColorPresentationParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/ICompletionHandler.cs b/src/Protocol/Document/ICompletionHandler.cs index 5f6470a5a..d4152b160 100644 --- a/src/Protocol/Document/ICompletionHandler.cs +++ b/src/Protocol/Document/ICompletionHandler.cs @@ -16,13 +16,15 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.Completion, Direction.ClientToServer)] + [Parallel] + [Method(TextDocumentNames.Completion, Direction.ClientToServer)] [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface ICompletionHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } - [Parallel, Method(TextDocumentNames.CompletionResolve, Direction.ClientToServer)] + [Parallel] + [Method(TextDocumentNames.CompletionResolve, Direction.ClientToServer)] [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface ICompletionResolveHandler : ICanBeResolvedHandler { @@ -47,10 +49,13 @@ public CompletionHandler(CompletionRegistrationOptions registrationOptions) } public abstract class PartialCompletionHandlerBase : - AbstractHandlers.PartialResults, ICompletionHandler, ICompletionResolveHandler + AbstractHandlers.PartialResults, ICompletionHandler, + ICompletionResolveHandler { - protected PartialCompletionHandlerBase(CompletionRegistrationOptions registrationOptions, IProgressManager progressManager) : base(registrationOptions, progressManager, - lenses => new CompletionList(lenses)) + protected PartialCompletionHandlerBase(CompletionRegistrationOptions registrationOptions, IProgressManager progressManager) : base( + registrationOptions, progressManager, + lenses => new CompletionList(lenses) + ) { } @@ -62,10 +67,7 @@ protected PartialCompletionHandlerBase(CompletionRegistrationOptions registratio { private readonly ISerializer _serializer; - public CompletionHandlerBase(CompletionRegistrationOptions registrationOptions, ISerializer serializer) : base(registrationOptions) - { - _serializer = serializer; - } + public CompletionHandlerBase(CompletionRegistrationOptions registrationOptions, ISerializer serializer) : base(registrationOptions) => _serializer = serializer; public sealed override async Task Handle(CompletionParams request, CancellationToken cancellationToken) @@ -88,19 +90,20 @@ public sealed override async Task Handle(CompletionItem request, { private readonly ISerializer _serializer; - protected PartialCompletionHandlerBase(CompletionRegistrationOptions registrationOptions, IProgressManager progressManager, ISerializer serializer) : base(registrationOptions, - progressManager) - { + protected PartialCompletionHandlerBase(CompletionRegistrationOptions registrationOptions, IProgressManager progressManager, ISerializer serializer) : base( + registrationOptions, + progressManager + ) => _serializer = serializer; - } protected sealed override void Handle(CompletionParams request, IObserver> results, CancellationToken cancellationToken) => Handle( request, Observer.Create>>( - x => results.OnNext(x.Select(z => (CompletionItem)z)), + x => results.OnNext(x.Select(z => (CompletionItem) z)), results.OnError, results.OnCompleted - ), cancellationToken); + ), cancellationToken + ); public sealed override async Task Handle(CompletionItem request, CancellationToken cancellationToken) { @@ -114,161 +117,199 @@ public sealed override async Task Handle(CompletionItem request, public static partial class CompletionExtensions { - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Func> handler, - CompletionRegistrationOptions registrationOptions) - { - return OnCompletion(registry, handler, null, registrationOptions); - } + CompletionRegistrationOptions registrationOptions + ) => + OnCompletion(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Func> handler, Func> resolveHandler, - CompletionRegistrationOptions registrationOptions) + CompletionRegistrationOptions registrationOptions + ) { registrationOptions ??= new CompletionRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (link, cap, token) => Task.FromResult(link); var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.Completion, - new LanguageProtocolDelegatingHandlers.Request( - id, - handler, - registrationOptions)) - .AddHandler(TextDocumentNames.CompletionResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.Completion, + new LanguageProtocolDelegatingHandlers.Request( + id, + handler, + registrationOptions + ) + ) + .AddHandler( + TextDocumentNames.CompletionResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Func>> handler, Func, CompletionCapability, CancellationToken, Task>> resolveHandler, - CompletionRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + CompletionRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new CompletionRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (link, c, token) => Task.FromResult(link); - return registry.AddHandler(_ => new DelegatingCompletionHandler( - registrationOptions, - _.GetRequiredService(), - handler, - resolveHandler) + return registry.AddHandler( + _ => new DelegatingCompletionHandler( + registrationOptions, + _.GetRequiredService(), + handler, + resolveHandler + ) ); } - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Func> handler, - CompletionRegistrationOptions registrationOptions) - { - return OnCompletion(registry, handler, null, registrationOptions); - } + CompletionRegistrationOptions registrationOptions + ) => + OnCompletion(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Func> handler, Func> resolveHandler, - CompletionRegistrationOptions registrationOptions) + CompletionRegistrationOptions registrationOptions + ) { registrationOptions ??= new CompletionRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (link, token) => Task.FromResult(link); var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.Completion, - new LanguageProtocolDelegatingHandlers.RequestRegistration( - id, - handler, - registrationOptions)) - .AddHandler(TextDocumentNames.CompletionResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.Completion, + new LanguageProtocolDelegatingHandlers.RequestRegistration( + id, + handler, + registrationOptions + ) + ) + .AddHandler( + TextDocumentNames.CompletionResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Func>> handler, Func, CancellationToken, Task>> resolveHandler, - CompletionRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + CompletionRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new CompletionRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (link, token) => Task.FromResult(link); - return registry.AddHandler(_ => new DelegatingCompletionHandler( - registrationOptions, - _.GetRequiredService(), - (@params, capability, token) => handler(@params, token), - (lens, capability, token) => resolveHandler(lens, token)) + return registry.AddHandler( + _ => new DelegatingCompletionHandler( + registrationOptions, + _.GetRequiredService(), + (@params, capability, token) => handler(@params, token), + (lens, capability, token) => resolveHandler(lens, token) + ) ); } - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Func> handler, - CompletionRegistrationOptions registrationOptions) - { - return OnCompletion(registry, handler, null, registrationOptions); - } + CompletionRegistrationOptions registrationOptions + ) => + OnCompletion(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Func> handler, Func> resolveHandler, - CompletionRegistrationOptions registrationOptions) + CompletionRegistrationOptions registrationOptions + ) { registrationOptions ??= new CompletionRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= Task.FromResult; var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.Completion, - new LanguageProtocolDelegatingHandlers.RequestRegistration( - id, - handler, - registrationOptions)) - .AddHandler(TextDocumentNames.CompletionResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.Completion, + new LanguageProtocolDelegatingHandlers.RequestRegistration( + id, + handler, + registrationOptions + ) + ) + .AddHandler( + TextDocumentNames.CompletionResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Func>> handler, Func, Task>> resolveHandler, - CompletionRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + CompletionRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new CompletionRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= Task.FromResult; - return registry.AddHandler(_ => new DelegatingCompletionHandler( - registrationOptions, - _.GetRequiredService(), - (@params, capability, token) => handler(@params), - (lens, capability, token) => resolveHandler(lens)) + return registry.AddHandler( + _ => new DelegatingCompletionHandler( + registrationOptions, + _.GetRequiredService(), + (@params, capability, token) => handler(@params), + (lens, capability, token) => resolveHandler(lens) + ) ); } - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Action>, CompletionCapability, CancellationToken> handler, - CompletionRegistrationOptions registrationOptions) - { - return OnCompletion(registry, handler, null, registrationOptions); - } + CompletionRegistrationOptions registrationOptions + ) => + OnCompletion(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Action>, CompletionCapability, CancellationToken> handler, Func> resolveHandler, - CompletionRegistrationOptions registrationOptions) + CompletionRegistrationOptions registrationOptions + ) { registrationOptions ??= new CompletionRegistrationOptions(); registrationOptions.ResolveProvider = true; @@ -276,143 +317,177 @@ public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry var id = Guid.NewGuid(); return - registry.AddHandler(TextDocumentNames.Completion, - _ => new LanguageProtocolDelegatingHandlers.PartialResults( - id, - handler, - registrationOptions, - _.GetRequiredService(), - x => new CompletionList(x))) - .AddHandler(TextDocumentNames.CompletionResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + registry.AddHandler( + TextDocumentNames.Completion, + _ => new LanguageProtocolDelegatingHandlers.PartialResults( + id, + handler, + registrationOptions, + _.GetRequiredService(), + x => new CompletionList(x) + ) + ) + .AddHandler( + TextDocumentNames.CompletionResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Action>>, CompletionCapability, CancellationToken> handler, Func, CompletionCapability, CancellationToken, Task>> resolveHandler, - CompletionRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + CompletionRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new CompletionRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (lens, capability, token) => Task.FromResult(lens); - return registry.AddHandler(_ => new DelegatingPartialCompletionHandler( - registrationOptions, - _.GetRequiredService(), - _.GetRequiredService(), - handler, - resolveHandler) + return registry.AddHandler( + _ => new DelegatingPartialCompletionHandler( + registrationOptions, + _.GetRequiredService(), + _.GetRequiredService(), + handler, + resolveHandler + ) ); } - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Action>, CancellationToken> handler, - CompletionRegistrationOptions registrationOptions) - { - return OnCompletion(registry, handler, null, registrationOptions); - } + CompletionRegistrationOptions registrationOptions + ) => + OnCompletion(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Action>, CancellationToken> handler, Func> resolveHandler, - CompletionRegistrationOptions registrationOptions) + CompletionRegistrationOptions registrationOptions + ) { registrationOptions ??= new CompletionRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (lens, token) => Task.FromResult(lens); var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.Completion, - _ => new LanguageProtocolDelegatingHandlers.PartialResults( - id, - handler, - registrationOptions, - _.GetRequiredService(), - x => new CompletionList(x))) - .AddHandler(TextDocumentNames.CompletionResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.Completion, + _ => new LanguageProtocolDelegatingHandlers.PartialResults( + id, + handler, + registrationOptions, + _.GetRequiredService(), + x => new CompletionList(x) + ) + ) + .AddHandler( + TextDocumentNames.CompletionResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Action>>, CancellationToken> handler, Func, CancellationToken, Task>> resolveHandler, - CompletionRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + CompletionRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new CompletionRegistrationOptions(); registrationOptions.ResolveProvider = true; - resolveHandler ??= (lens, token) => Task.FromResult(lens); - - return registry.AddHandler(_ => new DelegatingPartialCompletionHandler( - registrationOptions, - _.GetRequiredService(), - _.GetRequiredService(), - (@params, observer, capability, token) => handler(@params, observer, token), - (lens, capability, token) => resolveHandler(lens, token)) + resolveHandler ??= (lens, token) => Task.FromResult(lens); + + return registry.AddHandler( + _ => new DelegatingPartialCompletionHandler( + registrationOptions, + _.GetRequiredService(), + _.GetRequiredService(), + (@params, observer, capability, token) => handler(@params, observer, token), + (lens, capability, token) => resolveHandler(lens, token) + ) ); } - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Action>> handler, - CompletionRegistrationOptions registrationOptions) - { - return OnCompletion(registry, handler, null, registrationOptions); - } + CompletionRegistrationOptions registrationOptions + ) => + OnCompletion(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Action>> handler, Func> resolveHandler, - CompletionRegistrationOptions registrationOptions) + CompletionRegistrationOptions registrationOptions + ) { registrationOptions ??= new CompletionRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= Task.FromResult; var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.Completion, - _ => new LanguageProtocolDelegatingHandlers.PartialResults( - id, - handler, - registrationOptions, - _.GetRequiredService(), - x => new CompletionList(x))) - .AddHandler(TextDocumentNames.CompletionResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.Completion, + _ => new LanguageProtocolDelegatingHandlers.PartialResults( + id, + handler, + registrationOptions, + _.GetRequiredService(), + x => new CompletionList(x) + ) + ) + .AddHandler( + TextDocumentNames.CompletionResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnCompletion(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCompletion( + this ILanguageServerRegistry registry, Action>>> handler, Func, Task>> resolveHandler, - CompletionRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + CompletionRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new CompletionRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= Task.FromResult; - return registry.AddHandler(_ => new DelegatingPartialCompletionHandler( - registrationOptions, - _.GetRequiredService(), - _.GetRequiredService(), - (@params, observer, capability, token) => handler(@params, observer), - (lens, capability, token) => resolveHandler(lens)) + return registry.AddHandler( + _ => new DelegatingPartialCompletionHandler( + registrationOptions, + _.GetRequiredService(), + _.GetRequiredService(), + (@params, observer, capability, token) => handler(@params, observer), + (lens, capability, token) => resolveHandler(lens) + ) ); } - class DelegatingCompletionHandler : CompletionHandlerBase where T : HandlerIdentity, new() + private class DelegatingCompletionHandler : CompletionHandlerBase where T : HandlerIdentity, new() { private readonly Func>> _handleParams; private readonly Func, CompletionCapability, CancellationToken, Task>> _handleResolve; @@ -431,10 +506,11 @@ Func, CompletionCapability, CancellationToken, Task> HandleParams(CompletionParams request, CancellationToken cancellationToken) => _handleParams(request, Capability, cancellationToken); - protected override Task> HandleResolve(CompletionItem request, CancellationToken cancellationToken) => _handleResolve(request, Capability, cancellationToken); + protected override Task> HandleResolve(CompletionItem request, CancellationToken cancellationToken) => + _handleResolve(request, Capability, cancellationToken); } - class DelegatingPartialCompletionHandler : PartialCompletionHandlerBase where T : HandlerIdentity, new() + private class DelegatingPartialCompletionHandler : PartialCompletionHandlerBase where T : HandlerIdentity, new() { private readonly Action>>, CompletionCapability, CancellationToken> _handleParams; private readonly Func, CompletionCapability, CancellationToken, Task>> _handleResolve; @@ -454,7 +530,8 @@ Func, CompletionCapability, CancellationToken, Task>> results, CancellationToken cancellationToken) => _handleParams(request, results, Capability, cancellationToken); - protected override Task> HandleResolve(CompletionItem request, CancellationToken cancellationToken) => _handleResolve(request, Capability, cancellationToken); + protected override Task> HandleResolve(CompletionItem request, CancellationToken cancellationToken) => + _handleResolve(request, Capability, cancellationToken); } } } diff --git a/src/Protocol/Document/IDeclarationHandler.cs b/src/Protocol/Document/IDeclarationHandler.cs index 7d415bcdf..31e1bf272 100644 --- a/src/Protocol/Document/IDeclarationHandler.cs +++ b/src/Protocol/Document/IDeclarationHandler.cs @@ -8,17 +8,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.Declaration, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IDeclarationHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Parallel] + [Method(TextDocumentNames.Declaration, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IDeclarationHandler : IJsonRpcRequestHandler, IRegistration, + ICapability + { + } public abstract class DeclarationHandler : IDeclarationHandler { private readonly DeclarationRegistrationOptions _options; - public DeclarationHandler(DeclarationRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public DeclarationHandler(DeclarationRegistrationOptions registrationOptions) => _options = registrationOptions; public DeclarationRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(DeclarationParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IDefinitionHandler.cs b/src/Protocol/Document/IDefinitionHandler.cs index 1c097f018..819128139 100644 --- a/src/Protocol/Document/IDefinitionHandler.cs +++ b/src/Protocol/Document/IDefinitionHandler.cs @@ -1,22 +1,19 @@ -using System; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Progress; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.Definition, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [Parallel] + [Method(TextDocumentNames.Definition, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface IDefinitionHandler : IJsonRpcRequestHandler, IRegistration, - ICapability + ICapability { } @@ -24,10 +21,7 @@ public abstract class DefinitionHandler : IDefinitionHandler { private readonly DefinitionRegistrationOptions _options; - public DefinitionHandler(DefinitionRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public DefinitionHandler(DefinitionRegistrationOptions registrationOptions) => _options = registrationOptions; public DefinitionRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(DefinitionParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IDidChangeTextDocumentHandler.cs b/src/Protocol/Document/IDidChangeTextDocumentHandler.cs index e2a07430b..476bccd42 100644 --- a/src/Protocol/Document/IDidChangeTextDocumentHandler.cs +++ b/src/Protocol/Document/IDidChangeTextDocumentHandler.cs @@ -9,19 +9,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Serial, Method(TextDocumentNames.DidChange, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [Serial] + [Method(TextDocumentNames.DidChange, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface IDidChangeTextDocumentHandler : IJsonRpcNotificationHandler, - IRegistration, ICapability - { } + IRegistration, ICapability + { + } public abstract class DidChangeTextDocumentHandler : IDidChangeTextDocumentHandler { private readonly TextDocumentChangeRegistrationOptions _options; - public DidChangeTextDocumentHandler(TextDocumentChangeRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public DidChangeTextDocumentHandler(TextDocumentChangeRegistrationOptions registrationOptions) => _options = registrationOptions; public TextDocumentChangeRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(DidChangeTextDocumentParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IDidCloseTextDocumentHandler.cs b/src/Protocol/Document/IDidCloseTextDocumentHandler.cs index 927e5fd2f..5e8fa2e44 100644 --- a/src/Protocol/Document/IDidCloseTextDocumentHandler.cs +++ b/src/Protocol/Document/IDidCloseTextDocumentHandler.cs @@ -9,17 +9,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.DidClose, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IDidCloseTextDocumentHandler : IJsonRpcNotificationHandler, IRegistration, ICapability { } + [Parallel] + [Method(TextDocumentNames.DidClose, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IDidCloseTextDocumentHandler : IJsonRpcNotificationHandler, IRegistration, + ICapability + { + } public abstract class DidCloseTextDocumentHandler : IDidCloseTextDocumentHandler { private readonly TextDocumentRegistrationOptions _options; - public DidCloseTextDocumentHandler(TextDocumentRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public DidCloseTextDocumentHandler(TextDocumentRegistrationOptions registrationOptions) => _options = registrationOptions; public TextDocumentRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(DidCloseTextDocumentParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IDidOpenTextDocumentHandler.cs b/src/Protocol/Document/IDidOpenTextDocumentHandler.cs index d68aae46b..8a2fbed15 100644 --- a/src/Protocol/Document/IDidOpenTextDocumentHandler.cs +++ b/src/Protocol/Document/IDidOpenTextDocumentHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Threading; using System.Threading.Tasks; using MediatR; @@ -7,14 +6,15 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Serial, Method(TextDocumentNames.DidOpen, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [Serial] + [Method(TextDocumentNames.DidOpen, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface IDidOpenTextDocumentHandler : IJsonRpcNotificationHandler, IRegistration, - ICapability + ICapability { } @@ -22,10 +22,7 @@ public abstract class DidOpenTextDocumentHandler : IDidOpenTextDocumentHandler { private readonly TextDocumentRegistrationOptions _options; - public DidOpenTextDocumentHandler(TextDocumentRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public DidOpenTextDocumentHandler(TextDocumentRegistrationOptions registrationOptions) => _options = registrationOptions; public TextDocumentRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(DidOpenTextDocumentParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IDidSaveTextDocumentHandler.cs b/src/Protocol/Document/IDidSaveTextDocumentHandler.cs index e30fae169..2cf654655 100644 --- a/src/Protocol/Document/IDidSaveTextDocumentHandler.cs +++ b/src/Protocol/Document/IDidSaveTextDocumentHandler.cs @@ -9,17 +9,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Serial, Method(TextDocumentNames.DidSave, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IDidSaveTextDocumentHandler : IJsonRpcNotificationHandler, IRegistration, ICapability { } + [Serial] + [Method(TextDocumentNames.DidSave, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IDidSaveTextDocumentHandler : IJsonRpcNotificationHandler, IRegistration, + ICapability + { + } public abstract class DidSaveTextDocumentHandler : IDidSaveTextDocumentHandler { private readonly TextDocumentSaveRegistrationOptions _options; - public DidSaveTextDocumentHandler(TextDocumentSaveRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public DidSaveTextDocumentHandler(TextDocumentSaveRegistrationOptions registrationOptions) => _options = registrationOptions; public TextDocumentSaveRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(DidSaveTextDocumentParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IDocumentColorHandler.cs b/src/Protocol/Document/IDocumentColorHandler.cs index d3f559d75..5552a186c 100644 --- a/src/Protocol/Document/IDocumentColorHandler.cs +++ b/src/Protocol/Document/IDocumentColorHandler.cs @@ -1,29 +1,26 @@ -using System; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Progress; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.DocumentColor, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IDocumentColorHandler : IJsonRpcRequestHandler>, IRegistration, ICapability { } + [Parallel] + [Method(TextDocumentNames.DocumentColor, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IDocumentColorHandler : IJsonRpcRequestHandler>, IRegistration, + ICapability + { + } public abstract class DocumentColorHandler : IDocumentColorHandler { private readonly DocumentColorRegistrationOptions _options; - public DocumentColorHandler(DocumentColorRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public DocumentColorHandler(DocumentColorRegistrationOptions registrationOptions) => _options = registrationOptions; public DocumentColorRegistrationOptions GetRegistrationOptions() => _options; public abstract Task> Handle(DocumentColorParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IDocumentFormattingHandler.cs b/src/Protocol/Document/IDocumentFormattingHandler.cs index af450b5a5..318d8f0dc 100644 --- a/src/Protocol/Document/IDocumentFormattingHandler.cs +++ b/src/Protocol/Document/IDocumentFormattingHandler.cs @@ -8,17 +8,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Serial, Method(TextDocumentNames.DocumentFormatting, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IDocumentFormattingHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Serial] + [Method(TextDocumentNames.DocumentFormatting, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IDocumentFormattingHandler : IJsonRpcRequestHandler, IRegistration, + ICapability + { + } public abstract class DocumentFormattingHandler : IDocumentFormattingHandler { private readonly DocumentFormattingRegistrationOptions _options; - public DocumentFormattingHandler(DocumentFormattingRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public DocumentFormattingHandler(DocumentFormattingRegistrationOptions registrationOptions) => _options = registrationOptions; public DocumentFormattingRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(DocumentFormattingParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IDocumentHighlightHandler.cs b/src/Protocol/Document/IDocumentHighlightHandler.cs index ff142aab6..68f743748 100644 --- a/src/Protocol/Document/IDocumentHighlightHandler.cs +++ b/src/Protocol/Document/IDocumentHighlightHandler.cs @@ -1,29 +1,26 @@ -using System; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Progress; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.DocumentHighlight, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IDocumentHighlightHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Parallel] + [Method(TextDocumentNames.DocumentHighlight, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IDocumentHighlightHandler : IJsonRpcRequestHandler, IRegistration, + ICapability + { + } public abstract class DocumentHighlightHandler : IDocumentHighlightHandler { private readonly DocumentHighlightRegistrationOptions _options; - public DocumentHighlightHandler(DocumentHighlightRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public DocumentHighlightHandler(DocumentHighlightRegistrationOptions registrationOptions) => _options = registrationOptions; public DocumentHighlightRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(DocumentHighlightParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IDocumentLinkHandler.cs b/src/Protocol/Document/IDocumentLinkHandler.cs index 690795de7..a4e787e7d 100644 --- a/src/Protocol/Document/IDocumentLinkHandler.cs +++ b/src/Protocol/Document/IDocumentLinkHandler.cs @@ -16,14 +16,16 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.DocumentLink, Direction.ClientToServer)] + [Parallel] + [Method(TextDocumentNames.DocumentLink, Direction.ClientToServer)] [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface IDocumentLinkHandler : IJsonRpcRequestHandler, - IRegistration, ICapability + IRegistration, ICapability { } - [Parallel, Method(TextDocumentNames.DocumentLinkResolve, Direction.ClientToServer)] + [Parallel] + [Method(TextDocumentNames.DocumentLinkResolve, Direction.ClientToServer)] [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface IDocumentLinkResolveHandler : ICanBeResolvedHandler, ICanBeIdentifiedHandler { @@ -51,8 +53,10 @@ public abstract class PartialDocumentLinkHandlerBase : AbstractHandlers.PartialResults, IDocumentLinkHandler, IDocumentLinkResolveHandler { - protected PartialDocumentLinkHandlerBase(DocumentLinkRegistrationOptions registrationOptions, IProgressManager progressManager) : base(registrationOptions, progressManager, - lenses => new DocumentLinkContainer(lenses)) + protected PartialDocumentLinkHandlerBase(DocumentLinkRegistrationOptions registrationOptions, IProgressManager progressManager) : base( + registrationOptions, progressManager, + lenses => new DocumentLinkContainer(lenses) + ) { } @@ -64,10 +68,7 @@ protected PartialDocumentLinkHandlerBase(DocumentLinkRegistrationOptions registr { private readonly ISerializer _serializer; - public DocumentLinkHandlerBase(DocumentLinkRegistrationOptions registrationOptions, ISerializer serializer) : base(registrationOptions) - { - _serializer = serializer; - } + public DocumentLinkHandlerBase(DocumentLinkRegistrationOptions registrationOptions, ISerializer serializer) : base(registrationOptions) => _serializer = serializer; public sealed override async Task Handle(DocumentLinkParams request, CancellationToken cancellationToken) @@ -92,10 +93,9 @@ public sealed override async Task Handle(DocumentLink request, Can protected PartialDocumentLinkHandlerBase(DocumentLinkRegistrationOptions registrationOptions, IProgressManager progressManager, ISerializer serializer) : base( registrationOptions, - progressManager) - { + progressManager + ) => _serializer = serializer; - } protected sealed override void Handle(DocumentLinkParams request, IObserver> results, CancellationToken cancellationToken) => Handle( request, @@ -103,7 +103,8 @@ protected sealed override void Handle(DocumentLinkParams request, IObserver results.OnNext(x.Select(z => (DocumentLink) z)), results.OnError, results.OnCompleted - ), cancellationToken); + ), cancellationToken + ); public sealed override async Task Handle(DocumentLink request, CancellationToken cancellationToken) { @@ -117,161 +118,199 @@ public sealed override async Task Handle(DocumentLink request, Can public static partial class DocumentLinkExtensions { - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Func> handler, - DocumentLinkRegistrationOptions registrationOptions) - { - return OnDocumentLink(registry, handler, null, registrationOptions); - } + DocumentLinkRegistrationOptions registrationOptions + ) => + OnDocumentLink(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Func> handler, Func> resolveHandler, - DocumentLinkRegistrationOptions registrationOptions) + DocumentLinkRegistrationOptions registrationOptions + ) { registrationOptions ??= new DocumentLinkRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (link, cap, token) => Task.FromResult(link); var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.DocumentLink, - new LanguageProtocolDelegatingHandlers.Request( - id, - handler, - registrationOptions)) - .AddHandler(TextDocumentNames.DocumentLinkResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.DocumentLink, + new LanguageProtocolDelegatingHandlers.Request( + id, + handler, + registrationOptions + ) + ) + .AddHandler( + TextDocumentNames.DocumentLinkResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Func>> handler, Func, DocumentLinkCapability, CancellationToken, Task>> resolveHandler, - DocumentLinkRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + DocumentLinkRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new DocumentLinkRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (link, c, token) => Task.FromResult(link); - return registry.AddHandler(_ => new DelegatingDocumentLinkHandler( - registrationOptions, - _.GetRequiredService(), - handler, - resolveHandler) + return registry.AddHandler( + _ => new DelegatingDocumentLinkHandler( + registrationOptions, + _.GetRequiredService(), + handler, + resolveHandler + ) ); } - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Func> handler, - DocumentLinkRegistrationOptions registrationOptions) - { - return OnDocumentLink(registry, handler, null, registrationOptions); - } + DocumentLinkRegistrationOptions registrationOptions + ) => + OnDocumentLink(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Func> handler, Func> resolveHandler, - DocumentLinkRegistrationOptions registrationOptions) + DocumentLinkRegistrationOptions registrationOptions + ) { registrationOptions ??= new DocumentLinkRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (link, token) => Task.FromResult(link); var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.DocumentLink, - new LanguageProtocolDelegatingHandlers.RequestRegistration( - id, - handler, - registrationOptions)) - .AddHandler(TextDocumentNames.DocumentLinkResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.DocumentLink, + new LanguageProtocolDelegatingHandlers.RequestRegistration( + id, + handler, + registrationOptions + ) + ) + .AddHandler( + TextDocumentNames.DocumentLinkResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Func>> handler, Func, CancellationToken, Task>> resolveHandler, - DocumentLinkRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + DocumentLinkRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new DocumentLinkRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (link, token) => Task.FromResult(link); - return registry.AddHandler(_ => new DelegatingDocumentLinkHandler( - registrationOptions, - _.GetRequiredService(), - (@params, capability, token) => handler(@params, token), - (lens, capability, token) => resolveHandler(lens, token)) + return registry.AddHandler( + _ => new DelegatingDocumentLinkHandler( + registrationOptions, + _.GetRequiredService(), + (@params, capability, token) => handler(@params, token), + (lens, capability, token) => resolveHandler(lens, token) + ) ); } - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Func> handler, - DocumentLinkRegistrationOptions registrationOptions) - { - return OnDocumentLink(registry, handler, null, registrationOptions); - } + DocumentLinkRegistrationOptions registrationOptions + ) => + OnDocumentLink(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Func> handler, Func> resolveHandler, - DocumentLinkRegistrationOptions registrationOptions) + DocumentLinkRegistrationOptions registrationOptions + ) { registrationOptions ??= new DocumentLinkRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= Task.FromResult; var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.DocumentLink, - new LanguageProtocolDelegatingHandlers.RequestRegistration( - id, - handler, - registrationOptions)) - .AddHandler(TextDocumentNames.DocumentLinkResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.DocumentLink, + new LanguageProtocolDelegatingHandlers.RequestRegistration( + id, + handler, + registrationOptions + ) + ) + .AddHandler( + TextDocumentNames.DocumentLinkResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Func>> handler, Func, Task>> resolveHandler, - DocumentLinkRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + DocumentLinkRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new DocumentLinkRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= Task.FromResult; - return registry.AddHandler(_ => new DelegatingDocumentLinkHandler( - registrationOptions, - _.GetRequiredService(), - (@params, capability, token) => handler(@params), - (lens, capability, token) => resolveHandler(lens)) + return registry.AddHandler( + _ => new DelegatingDocumentLinkHandler( + registrationOptions, + _.GetRequiredService(), + (@params, capability, token) => handler(@params), + (lens, capability, token) => resolveHandler(lens) + ) ); } - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Action>, DocumentLinkCapability, CancellationToken> handler, - DocumentLinkRegistrationOptions registrationOptions) - { - return OnDocumentLink(registry, handler, null, registrationOptions); - } + DocumentLinkRegistrationOptions registrationOptions + ) => + OnDocumentLink(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Action>, DocumentLinkCapability, CancellationToken> handler, Func> resolveHandler, - DocumentLinkRegistrationOptions registrationOptions) + DocumentLinkRegistrationOptions registrationOptions + ) { registrationOptions ??= new DocumentLinkRegistrationOptions(); registrationOptions.ResolveProvider = true; @@ -279,143 +318,177 @@ public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistr var id = Guid.NewGuid(); return - registry.AddHandler(TextDocumentNames.DocumentLink, - _ => new LanguageProtocolDelegatingHandlers.PartialResults( - id, - handler, - registrationOptions, - _.GetRequiredService(), - x => new DocumentLinkContainer(x))) - .AddHandler(TextDocumentNames.DocumentLinkResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + registry.AddHandler( + TextDocumentNames.DocumentLink, + _ => new LanguageProtocolDelegatingHandlers.PartialResults( + id, + handler, + registrationOptions, + _.GetRequiredService(), + x => new DocumentLinkContainer(x) + ) + ) + .AddHandler( + TextDocumentNames.DocumentLinkResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Action>>, DocumentLinkCapability, CancellationToken> handler, Func, DocumentLinkCapability, CancellationToken, Task>> resolveHandler, - DocumentLinkRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + DocumentLinkRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new DocumentLinkRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (lens, capability, token) => Task.FromResult(lens); - return registry.AddHandler(_ => new DelegatingPartialDocumentLinkHandler( - registrationOptions, - _.GetRequiredService(), - _.GetRequiredService(), - handler, - resolveHandler) + return registry.AddHandler( + _ => new DelegatingPartialDocumentLinkHandler( + registrationOptions, + _.GetRequiredService(), + _.GetRequiredService(), + handler, + resolveHandler + ) ); } - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Action>, CancellationToken> handler, - DocumentLinkRegistrationOptions registrationOptions) - { - return OnDocumentLink(registry, handler, null, registrationOptions); - } + DocumentLinkRegistrationOptions registrationOptions + ) => + OnDocumentLink(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Action>, CancellationToken> handler, Func> resolveHandler, - DocumentLinkRegistrationOptions registrationOptions) + DocumentLinkRegistrationOptions registrationOptions + ) { registrationOptions ??= new DocumentLinkRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (lens, token) => Task.FromResult(lens); var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.DocumentLink, - _ => new LanguageProtocolDelegatingHandlers.PartialResults( - id, - handler, - registrationOptions, - _.GetRequiredService(), - x => new DocumentLinkContainer(x))) - .AddHandler(TextDocumentNames.DocumentLinkResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.DocumentLink, + _ => new LanguageProtocolDelegatingHandlers.PartialResults( + id, + handler, + registrationOptions, + _.GetRequiredService(), + x => new DocumentLinkContainer(x) + ) + ) + .AddHandler( + TextDocumentNames.DocumentLinkResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Action>>, CancellationToken> handler, Func, CancellationToken, Task>> resolveHandler, - DocumentLinkRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + DocumentLinkRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new DocumentLinkRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= (lens, token) => Task.FromResult(lens); - return registry.AddHandler(_ => new DelegatingPartialDocumentLinkHandler( - registrationOptions, - _.GetRequiredService(), - _.GetRequiredService(), - (@params, observer, capability, token) => handler(@params, observer, token), - (lens, capability, token) => resolveHandler(lens, token)) + return registry.AddHandler( + _ => new DelegatingPartialDocumentLinkHandler( + registrationOptions, + _.GetRequiredService(), + _.GetRequiredService(), + (@params, observer, capability, token) => handler(@params, observer, token), + (lens, capability, token) => resolveHandler(lens, token) + ) ); } - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Action>> handler, - DocumentLinkRegistrationOptions registrationOptions) - { - return OnDocumentLink(registry, handler, null, registrationOptions); - } + DocumentLinkRegistrationOptions registrationOptions + ) => + OnDocumentLink(registry, handler, null, registrationOptions); - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Action>> handler, Func> resolveHandler, - DocumentLinkRegistrationOptions registrationOptions) + DocumentLinkRegistrationOptions registrationOptions + ) { registrationOptions ??= new DocumentLinkRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= Task.FromResult; var id = Guid.NewGuid(); - return registry.AddHandler(TextDocumentNames.DocumentLink, - _ => new LanguageProtocolDelegatingHandlers.PartialResults( - id, - handler, - registrationOptions, - _.GetRequiredService(), - x => new DocumentLinkContainer(x))) - .AddHandler(TextDocumentNames.DocumentLinkResolve, - new LanguageProtocolDelegatingHandlers.CanBeResolved( - id, - resolveHandler, - registrationOptions)) + return registry.AddHandler( + TextDocumentNames.DocumentLink, + _ => new LanguageProtocolDelegatingHandlers.PartialResults( + id, + handler, + registrationOptions, + _.GetRequiredService(), + x => new DocumentLinkContainer(x) + ) + ) + .AddHandler( + TextDocumentNames.DocumentLinkResolve, + new LanguageProtocolDelegatingHandlers.CanBeResolved( + id, + resolveHandler, + registrationOptions + ) + ) ; } - public static ILanguageServerRegistry OnDocumentLink(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnDocumentLink( + this ILanguageServerRegistry registry, Action>>> handler, Func, Task>> resolveHandler, - DocumentLinkRegistrationOptions registrationOptions) where T : HandlerIdentity, new() + DocumentLinkRegistrationOptions registrationOptions + ) where T : HandlerIdentity, new() { registrationOptions ??= new DocumentLinkRegistrationOptions(); registrationOptions.ResolveProvider = true; resolveHandler ??= Task.FromResult; - return registry.AddHandler(_ => new DelegatingPartialDocumentLinkHandler( - registrationOptions, - _.GetRequiredService(), - _.GetRequiredService(), - (@params, observer, capability, token) => handler(@params, observer), - (lens, capability, token) => resolveHandler(lens)) + return registry.AddHandler( + _ => new DelegatingPartialDocumentLinkHandler( + registrationOptions, + _.GetRequiredService(), + _.GetRequiredService(), + (@params, observer, capability, token) => handler(@params, observer), + (lens, capability, token) => resolveHandler(lens) + ) ); } - class DelegatingDocumentLinkHandler : DocumentLinkHandlerBase where T : HandlerIdentity, new() + private class DelegatingDocumentLinkHandler : DocumentLinkHandlerBase where T : HandlerIdentity, new() { private readonly Func>> _handleParams; private readonly Func, DocumentLinkCapability, CancellationToken, Task>> _handleResolve; @@ -438,7 +511,7 @@ protected override Task> HandleResolve(DocumentLink request, _handleResolve(request, Capability, cancellationToken); } - class DelegatingPartialDocumentLinkHandler : PartialDocumentLinkHandlerBase where T : HandlerIdentity, new() + private class DelegatingPartialDocumentLinkHandler : PartialDocumentLinkHandlerBase where T : HandlerIdentity, new() { private readonly Action>>, DocumentLinkCapability, CancellationToken> _handleParams; private readonly Func, DocumentLinkCapability, CancellationToken, Task>> _handleResolve; diff --git a/src/Protocol/Document/IDocumentOnTypeFormattingHandler.cs b/src/Protocol/Document/IDocumentOnTypeFormattingHandler.cs index 2a3144404..60a4ba206 100644 --- a/src/Protocol/Document/IDocumentOnTypeFormattingHandler.cs +++ b/src/Protocol/Document/IDocumentOnTypeFormattingHandler.cs @@ -8,17 +8,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Serial, Method(TextDocumentNames.OnTypeFormatting, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IDocumentOnTypeFormattingHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Serial] + [Method(TextDocumentNames.OnTypeFormatting, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IDocumentOnTypeFormattingHandler : IJsonRpcRequestHandler, + IRegistration, ICapability + { + } public abstract class DocumentOnTypeFormattingHandler : IDocumentOnTypeFormattingHandler { private readonly DocumentOnTypeFormattingRegistrationOptions _options; - public DocumentOnTypeFormattingHandler(DocumentOnTypeFormattingRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public DocumentOnTypeFormattingHandler(DocumentOnTypeFormattingRegistrationOptions registrationOptions) => _options = registrationOptions; public DocumentOnTypeFormattingRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(DocumentOnTypeFormattingParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IDocumentRangeFormattingHandler.cs b/src/Protocol/Document/IDocumentRangeFormattingHandler.cs index eec9f05ac..a8c4ff379 100644 --- a/src/Protocol/Document/IDocumentRangeFormattingHandler.cs +++ b/src/Protocol/Document/IDocumentRangeFormattingHandler.cs @@ -8,17 +8,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Serial, Method(TextDocumentNames.RangeFormatting, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IDocumentRangeFormattingHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Serial] + [Method(TextDocumentNames.RangeFormatting, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IDocumentRangeFormattingHandler : IJsonRpcRequestHandler, + IRegistration, ICapability + { + } public abstract class DocumentRangeFormattingHandler : IDocumentRangeFormattingHandler { private readonly DocumentRangeFormattingRegistrationOptions _options; - public DocumentRangeFormattingHandler(DocumentRangeFormattingRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public DocumentRangeFormattingHandler(DocumentRangeFormattingRegistrationOptions registrationOptions) => _options = registrationOptions; public DocumentRangeFormattingRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(DocumentRangeFormattingParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IDocumentSymbolHandler.cs b/src/Protocol/Document/IDocumentSymbolHandler.cs index f994ea2dc..eb38ea570 100644 --- a/src/Protocol/Document/IDocumentSymbolHandler.cs +++ b/src/Protocol/Document/IDocumentSymbolHandler.cs @@ -8,17 +8,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.DocumentSymbol, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IDocumentSymbolHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Parallel] + [Method(TextDocumentNames.DocumentSymbol, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IDocumentSymbolHandler : IJsonRpcRequestHandler, + IRegistration, ICapability + { + } public abstract class DocumentSymbolHandler : IDocumentSymbolHandler { private readonly DocumentSymbolRegistrationOptions _options; - public DocumentSymbolHandler(DocumentSymbolRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public DocumentSymbolHandler(DocumentSymbolRegistrationOptions registrationOptions) => _options = registrationOptions; public DocumentSymbolRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(DocumentSymbolParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IFoldingRangeHandler.cs b/src/Protocol/Document/IFoldingRangeHandler.cs index c942949e1..77d0a89a5 100644 --- a/src/Protocol/Document/IFoldingRangeHandler.cs +++ b/src/Protocol/Document/IFoldingRangeHandler.cs @@ -8,10 +8,12 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.FoldingRange, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [Parallel] + [Method(TextDocumentNames.FoldingRange, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface IFoldingRangeHandler : IJsonRpcRequestHandler>, - IRegistration, ICapability + IRegistration, ICapability { } @@ -19,16 +21,14 @@ public abstract class FoldingRangeHandler : IFoldingRangeHandler { private readonly FoldingRangeRegistrationOptions _options; - public FoldingRangeHandler(FoldingRangeRegistrationOptions registrationOptions) - - { - _options = registrationOptions; - } + public FoldingRangeHandler(FoldingRangeRegistrationOptions registrationOptions) => _options = registrationOptions; public FoldingRangeRegistrationOptions GetRegistrationOptions() => _options; - public abstract Task> Handle(FoldingRangeRequestParam request, - CancellationToken cancellationToken); + public abstract Task> Handle( + FoldingRangeRequestParam request, + CancellationToken cancellationToken + ); public virtual void SetCapability(FoldingRangeCapability capability) => Capability = capability; protected FoldingRangeCapability Capability { get; private set; } diff --git a/src/Protocol/Document/IHoverHandler.cs b/src/Protocol/Document/IHoverHandler.cs index b41872cc3..cbdaf8a4c 100644 --- a/src/Protocol/Document/IHoverHandler.cs +++ b/src/Protocol/Document/IHoverHandler.cs @@ -8,17 +8,18 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.Hover, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IHoverHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Parallel] + [Method(TextDocumentNames.Hover, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IHoverHandler : IJsonRpcRequestHandler, IRegistration, ICapability + { + } public abstract class HoverHandler : IHoverHandler { private readonly HoverRegistrationOptions _options; - public HoverHandler(HoverRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public HoverHandler(HoverRegistrationOptions registrationOptions) => _options = registrationOptions; public HoverRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(HoverParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IImplementationHandler.cs b/src/Protocol/Document/IImplementationHandler.cs index 097cf624a..9aa1fba75 100644 --- a/src/Protocol/Document/IImplementationHandler.cs +++ b/src/Protocol/Document/IImplementationHandler.cs @@ -6,19 +6,21 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.Implementation, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [Parallel] + [Method(TextDocumentNames.Implementation, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface IImplementationHandler : IJsonRpcRequestHandler, - IRegistration, ICapability + IRegistration, ICapability { } - public abstract class ImplementationHandler : - AbstractHandlers.Request, IImplementationHandler + public abstract class ImplementationHandler : AbstractHandlers.Request, IImplementationHandler { protected ImplementationHandler(ImplementationRegistrationOptions registrationOptions) : base( - registrationOptions) + registrationOptions + ) { } } diff --git a/src/Protocol/Document/IPrepareRenameHandler.cs b/src/Protocol/Document/IPrepareRenameHandler.cs index 70c02ec64..4214c1b82 100644 --- a/src/Protocol/Document/IPrepareRenameHandler.cs +++ b/src/Protocol/Document/IPrepareRenameHandler.cs @@ -8,17 +8,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Serial, Method(TextDocumentNames.PrepareRename, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IPrepareRenameHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Serial] + [Method(TextDocumentNames.PrepareRename, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IPrepareRenameHandler : IJsonRpcRequestHandler, IRegistration, + ICapability + { + } public abstract class PrepareRenameHandler : IPrepareRenameHandler { private readonly TextDocumentRegistrationOptions _options; - public PrepareRenameHandler(TextDocumentRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public PrepareRenameHandler(TextDocumentRegistrationOptions registrationOptions) => _options = registrationOptions; public TextDocumentRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(PrepareRenameParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IPublishDiagnosticsHandler.cs b/src/Protocol/Document/IPublishDiagnosticsHandler.cs index 6db77ba24..c33501bb7 100644 --- a/src/Protocol/Document/IPublishDiagnosticsHandler.cs +++ b/src/Protocol/Document/IPublishDiagnosticsHandler.cs @@ -8,10 +8,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - - [Parallel, Method(TextDocumentNames.PublishDiagnostics, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageServer), typeof(ILanguageServer))] - public interface IPublishDiagnosticsHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(TextDocumentNames.PublishDiagnostics, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageServer), typeof(ILanguageServer))] + public interface IPublishDiagnosticsHandler : IJsonRpcNotificationHandler + { + } public abstract class PublishDiagnosticsHandler : IPublishDiagnosticsHandler { diff --git a/src/Protocol/Document/IReferencesHandler.cs b/src/Protocol/Document/IReferencesHandler.cs index 96b1fa83a..c5d123724 100644 --- a/src/Protocol/Document/IReferencesHandler.cs +++ b/src/Protocol/Document/IReferencesHandler.cs @@ -8,17 +8,18 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.References, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IReferencesHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Parallel] + [Method(TextDocumentNames.References, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IReferencesHandler : IJsonRpcRequestHandler, IRegistration, ICapability + { + } public abstract class ReferencesHandler : IReferencesHandler { private readonly ReferenceRegistrationOptions _options; - public ReferencesHandler(ReferenceRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public ReferencesHandler(ReferenceRegistrationOptions registrationOptions) => _options = registrationOptions; public ReferenceRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(ReferenceParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IRenameHandler.cs b/src/Protocol/Document/IRenameHandler.cs index 8eb88267a..a2ba6bbff 100644 --- a/src/Protocol/Document/IRenameHandler.cs +++ b/src/Protocol/Document/IRenameHandler.cs @@ -8,17 +8,18 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Serial, Method(TextDocumentNames.Rename, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IRenameHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Serial] + [Method(TextDocumentNames.Rename, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IRenameHandler : IJsonRpcRequestHandler, IRegistration, ICapability + { + } public abstract class RenameHandler : IRenameHandler { private readonly RenameRegistrationOptions _options; - public RenameHandler(RenameRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public RenameHandler(RenameRegistrationOptions registrationOptions) => _options = registrationOptions; public RenameRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(RenameParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/ISelectionRangeHandler.cs b/src/Protocol/Document/ISelectionRangeHandler.cs index 56e1e25b1..73eb61a4f 100644 --- a/src/Protocol/Document/ISelectionRangeHandler.cs +++ b/src/Protocol/Document/ISelectionRangeHandler.cs @@ -8,10 +8,12 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.SelectionRange, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [Parallel] + [Method(TextDocumentNames.SelectionRange, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface ISelectionRangeHandler : IJsonRpcRequestHandler>, - IRegistration, ICapability + IRegistration, ICapability { } @@ -19,15 +21,14 @@ public abstract class SelectionRangeHandler : ISelectionRangeHandler { private readonly SelectionRangeRegistrationOptions _options; - public SelectionRangeHandler(SelectionRangeRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public SelectionRangeHandler(SelectionRangeRegistrationOptions registrationOptions) => _options = registrationOptions; public SelectionRangeRegistrationOptions GetRegistrationOptions() => _options; - public abstract Task> Handle(SelectionRangeParams request, - CancellationToken cancellationToken); + public abstract Task> Handle( + SelectionRangeParams request, + CancellationToken cancellationToken + ); public virtual void SetCapability(SelectionRangeCapability capability) => Capability = capability; protected SelectionRangeCapability Capability { get; private set; } diff --git a/src/Protocol/Document/ISignatureHelpHandler.cs b/src/Protocol/Document/ISignatureHelpHandler.cs index 83a54a1a1..fe6f7bcdc 100644 --- a/src/Protocol/Document/ISignatureHelpHandler.cs +++ b/src/Protocol/Document/ISignatureHelpHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc; @@ -6,21 +5,22 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.SignatureHelp, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface ISignatureHelpHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Parallel] + [Method(TextDocumentNames.SignatureHelp, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface ISignatureHelpHandler : IJsonRpcRequestHandler, IRegistration, + ICapability + { + } public abstract class SignatureHelpHandler : ISignatureHelpHandler { private readonly SignatureHelpRegistrationOptions _options; - public SignatureHelpHandler(SignatureHelpRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public SignatureHelpHandler(SignatureHelpRegistrationOptions registrationOptions) => _options = registrationOptions; public SignatureHelpRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(SignatureHelpParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/ITextDocumentIdentifier.cs b/src/Protocol/Document/ITextDocumentIdentifier.cs index fdcf61ea8..907c903f7 100644 --- a/src/Protocol/Document/ITextDocumentIdentifier.cs +++ b/src/Protocol/Document/ITextDocumentIdentifier.cs @@ -36,12 +36,14 @@ public IDisposable Add(params ITextDocumentIdentifier[] identifiers) { foreach (var item in identifiers) _textDocumentIdentifiers.Add(item); - return Disposable.Create(() => { - foreach (var textDocumentIdentifier in identifiers) - { - _textDocumentIdentifiers.Remove(textDocumentIdentifier); + return Disposable.Create( + () => { + foreach (var textDocumentIdentifier in identifiers) + { + _textDocumentIdentifiers.Remove(textDocumentIdentifier); + } } - }); + ); } } } diff --git a/src/Protocol/Document/ITextDocumentSyncHandler.cs b/src/Protocol/Document/ITextDocumentSyncHandler.cs index af026271f..45010f367 100644 --- a/src/Protocol/Document/ITextDocumentSyncHandler.cs +++ b/src/Protocol/Document/ITextDocumentSyncHandler.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MediatR; @@ -11,7 +10,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { public interface ITextDocumentSyncHandler : IDidChangeTextDocumentHandler, IDidOpenTextDocumentHandler, - IDidCloseTextDocumentHandler, IDidSaveTextDocumentHandler, ITextDocumentIdentifier + IDidCloseTextDocumentHandler, IDidSaveTextDocumentHandler, ITextDocumentIdentifier { } @@ -20,11 +19,13 @@ public abstract class TextDocumentSyncHandler : ITextDocumentSyncHandler private readonly TextDocumentSaveRegistrationOptions _options; private readonly TextDocumentChangeRegistrationOptions _changeOptions; - public TextDocumentSyncHandler(TextDocumentSyncKind kind, - TextDocumentSaveRegistrationOptions registrationOptions) + public TextDocumentSyncHandler( + TextDocumentSyncKind kind, + TextDocumentSaveRegistrationOptions registrationOptions + ) { _options = registrationOptions; - _changeOptions = new TextDocumentChangeRegistrationOptions() { + _changeOptions = new TextDocumentChangeRegistrationOptions { DocumentSelector = registrationOptions.DocumentSelector, SyncKind = kind }; @@ -50,125 +51,162 @@ TextDocumentChangeRegistrationOptions IRegistration getTextDocumentAttributes, Func onOpenHandler, Func onCloseHandler, Func onChangeHandler, Func onSaveHandler, - TextDocumentSaveRegistrationOptions registrationOptions) + TextDocumentSaveRegistrationOptions registrationOptions + ) { registrationOptions ??= new TextDocumentSaveRegistrationOptions(); - return registry.AddHandlers(new DelegatingHandler(onOpenHandler, onCloseHandler, onChangeHandler, - onSaveHandler, getTextDocumentAttributes, registrationOptions, kind)); + return registry.AddHandlers( + new DelegatingHandler( + onOpenHandler, onCloseHandler, onChangeHandler, + onSaveHandler, getTextDocumentAttributes, registrationOptions, kind + ) + ); } - public static ILanguageServerRegistry OnTextDocumentSync(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnTextDocumentSync( + this ILanguageServerRegistry registry, TextDocumentSyncKind kind, Func getTextDocumentAttributes, Action onOpenHandler, Action onCloseHandler, Action onChangeHandler, Action onSaveHandler, - TextDocumentSaveRegistrationOptions registrationOptions) + TextDocumentSaveRegistrationOptions registrationOptions + ) { registrationOptions ??= new TextDocumentSaveRegistrationOptions(); - return registry.AddHandlers(new DelegatingHandler(onOpenHandler, onCloseHandler, onChangeHandler, - onSaveHandler, getTextDocumentAttributes, registrationOptions, kind)); + return registry.AddHandlers( + new DelegatingHandler( + onOpenHandler, onCloseHandler, onChangeHandler, + onSaveHandler, getTextDocumentAttributes, registrationOptions, kind + ) + ); } - public static ILanguageServerRegistry OnTextDocumentSync(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnTextDocumentSync( + this ILanguageServerRegistry registry, TextDocumentSyncKind kind, Func getTextDocumentAttributes, Action onOpenHandler, Action onCloseHandler, Action onChangeHandler, Action onSaveHandler, - TextDocumentSaveRegistrationOptions registrationOptions) + TextDocumentSaveRegistrationOptions registrationOptions + ) { registrationOptions ??= new TextDocumentSaveRegistrationOptions(); - return registry.AddHandlers(new DelegatingHandler( - (r, c, ct) => onOpenHandler(r, c), - (r, c, ct) => onCloseHandler(r, c), - (r, c, ct) => onChangeHandler(r, c), - (r, c, ct) => onSaveHandler(r, c), - getTextDocumentAttributes, registrationOptions, kind)); + return registry.AddHandlers( + new DelegatingHandler( + (r, c, ct) => onOpenHandler(r, c), + (r, c, ct) => onCloseHandler(r, c), + (r, c, ct) => onChangeHandler(r, c), + (r, c, ct) => onSaveHandler(r, c), + getTextDocumentAttributes, registrationOptions, kind + ) + ); } - public static ILanguageServerRegistry OnTextDocumentSync(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnTextDocumentSync( + this ILanguageServerRegistry registry, TextDocumentSyncKind kind, Func getTextDocumentAttributes, Func onOpenHandler, Func onCloseHandler, Func onChangeHandler, Func onSaveHandler, - TextDocumentSaveRegistrationOptions registrationOptions) + TextDocumentSaveRegistrationOptions registrationOptions + ) { registrationOptions ??= new TextDocumentSaveRegistrationOptions(); - return registry.AddHandlers(new DelegatingHandler( - (r, c, ct) => onOpenHandler(r, ct), - (r, c, ct) => onCloseHandler(r, ct), - (r, c, ct) => onChangeHandler(r, ct), - (r, c, ct) => onSaveHandler(r, ct), - getTextDocumentAttributes, registrationOptions, kind)); + return registry.AddHandlers( + new DelegatingHandler( + (r, c, ct) => onOpenHandler(r, ct), + (r, c, ct) => onCloseHandler(r, ct), + (r, c, ct) => onChangeHandler(r, ct), + (r, c, ct) => onSaveHandler(r, ct), + getTextDocumentAttributes, registrationOptions, kind + ) + ); } - public static ILanguageServerRegistry OnTextDocumentSync(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnTextDocumentSync( + this ILanguageServerRegistry registry, TextDocumentSyncKind kind, Func getTextDocumentAttributes, Action onOpenHandler, Action onCloseHandler, Action onChangeHandler, Action onSaveHandler, - TextDocumentSaveRegistrationOptions registrationOptions) + TextDocumentSaveRegistrationOptions registrationOptions + ) { registrationOptions ??= new TextDocumentSaveRegistrationOptions(); - return registry.AddHandlers(new DelegatingHandler( - (r, c, ct) => onOpenHandler(r, ct), - (r, c, ct) => onCloseHandler(r, ct), - (r, c, ct) => onChangeHandler(r, ct), - (r, c, ct) => onSaveHandler(r, ct), - getTextDocumentAttributes, registrationOptions, kind)); + return registry.AddHandlers( + new DelegatingHandler( + (r, c, ct) => onOpenHandler(r, ct), + (r, c, ct) => onCloseHandler(r, ct), + (r, c, ct) => onChangeHandler(r, ct), + (r, c, ct) => onSaveHandler(r, ct), + getTextDocumentAttributes, registrationOptions, kind + ) + ); } - public static ILanguageServerRegistry OnTextDocumentSync(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnTextDocumentSync( + this ILanguageServerRegistry registry, TextDocumentSyncKind kind, Func getTextDocumentAttributes, Func onOpenHandler, Func onCloseHandler, Func onChangeHandler, Func onSaveHandler, - TextDocumentSaveRegistrationOptions registrationOptions) + TextDocumentSaveRegistrationOptions registrationOptions + ) { registrationOptions ??= new TextDocumentSaveRegistrationOptions(); - return registry.AddHandlers(new DelegatingHandler( - (r, c, ct) => onOpenHandler(r), - (r, c, ct) => onCloseHandler(r), - (r, c, ct) => onChangeHandler(r), - (r, c, ct) => onSaveHandler(r), - getTextDocumentAttributes, registrationOptions, kind)); + return registry.AddHandlers( + new DelegatingHandler( + (r, c, ct) => onOpenHandler(r), + (r, c, ct) => onCloseHandler(r), + (r, c, ct) => onChangeHandler(r), + (r, c, ct) => onSaveHandler(r), + getTextDocumentAttributes, registrationOptions, kind + ) + ); } - public static ILanguageServerRegistry OnTextDocumentSync(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnTextDocumentSync( + this ILanguageServerRegistry registry, TextDocumentSyncKind kind, Func getTextDocumentAttributes, Action onOpenHandler, Action onCloseHandler, Action onChangeHandler, Action onSaveHandler, - TextDocumentSaveRegistrationOptions registrationOptions) + TextDocumentSaveRegistrationOptions registrationOptions + ) { registrationOptions ??= new TextDocumentSaveRegistrationOptions(); - return registry.AddHandlers(new DelegatingHandler( - (r, c, ct) => onOpenHandler(r), - (r, c, ct) => onCloseHandler(r), - (r, c, ct) => onChangeHandler(r), - (r, c, ct) => onSaveHandler(r), - getTextDocumentAttributes, registrationOptions, kind)); + return registry.AddHandlers( + new DelegatingHandler( + (r, c, ct) => onOpenHandler(r), + (r, c, ct) => onCloseHandler(r), + (r, c, ct) => onChangeHandler(r), + (r, c, ct) => onSaveHandler(r), + getTextDocumentAttributes, registrationOptions, kind + ) + ); } - class DelegatingHandler : TextDocumentSyncHandler + private class DelegatingHandler : TextDocumentSyncHandler { private readonly Func _onOpenHandler; @@ -192,7 +230,8 @@ public DelegatingHandler( Func onSaveHandler, Func getTextDocumentAttributes, TextDocumentSaveRegistrationOptions registrationOptions, - TextDocumentSyncKind kind) : base(kind, registrationOptions) + TextDocumentSyncKind kind + ) : base(kind, registrationOptions) { _onOpenHandler = onOpenHandler; _onSaveHandler = onSaveHandler; @@ -208,7 +247,8 @@ public DelegatingHandler( Action onSaveHandler, Func getTextDocumentAttributes, TextDocumentSaveRegistrationOptions registrationOptions, - TextDocumentSyncKind kind) : this( + TextDocumentSyncKind kind + ) : this( (r, c, ct) => { onOpenHandler(r, c, ct); return Task.CompletedTask; @@ -227,33 +267,42 @@ public DelegatingHandler( }, getTextDocumentAttributes, registrationOptions, - kind) + kind + ) { } - public override async Task Handle(DidOpenTextDocumentParams request, - CancellationToken cancellationToken) + public override async Task Handle( + DidOpenTextDocumentParams request, + CancellationToken cancellationToken + ) { await _onOpenHandler.Invoke(request, _capability, cancellationToken); return Unit.Value; } - public override async Task Handle(DidChangeTextDocumentParams request, - CancellationToken cancellationToken) + public override async Task Handle( + DidChangeTextDocumentParams request, + CancellationToken cancellationToken + ) { await _onChangeHandler.Invoke(request, _capability, cancellationToken); return Unit.Value; } - public override async Task Handle(DidSaveTextDocumentParams request, - CancellationToken cancellationToken) + public override async Task Handle( + DidSaveTextDocumentParams request, + CancellationToken cancellationToken + ) { await _onSaveHandler.Invoke(request, _capability, cancellationToken); return Unit.Value; } - public override async Task Handle(DidCloseTextDocumentParams request, - CancellationToken cancellationToken) + public override async Task Handle( + DidCloseTextDocumentParams request, + CancellationToken cancellationToken + ) { await _onCloseHandler.Invoke(request, _capability, cancellationToken); return Unit.Value; @@ -262,10 +311,7 @@ public override async Task Handle(DidCloseTextDocumentParams request, public override TextDocumentAttributes GetTextDocumentAttributes(DocumentUri uri) => _getTextDocumentAttributes.Invoke(uri); - public override void SetCapability(SynchronizationCapability capability) - { - _capability = capability; - } + public override void SetCapability(SynchronizationCapability capability) => _capability = capability; } } } diff --git a/src/Protocol/Document/ITypeDefinitionHandler.cs b/src/Protocol/Document/ITypeDefinitionHandler.cs index e5445ba49..49b58bfd0 100644 --- a/src/Protocol/Document/ITypeDefinitionHandler.cs +++ b/src/Protocol/Document/ITypeDefinitionHandler.cs @@ -8,17 +8,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.TypeDefinition, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface ITypeDefinitionHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Parallel] + [Method(TextDocumentNames.TypeDefinition, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface ITypeDefinitionHandler : IJsonRpcRequestHandler, IRegistration, + ICapability + { + } public abstract class TypeDefinitionHandler : ITypeDefinitionHandler { private readonly TypeDefinitionRegistrationOptions _options; - public TypeDefinitionHandler(TypeDefinitionRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public TypeDefinitionHandler(TypeDefinitionRegistrationOptions registrationOptions) => _options = registrationOptions; public TypeDefinitionRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(TypeDefinitionParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IWillSaveTextDocumentHandler.cs b/src/Protocol/Document/IWillSaveTextDocumentHandler.cs index 4f5221cfc..93bd23899 100644 --- a/src/Protocol/Document/IWillSaveTextDocumentHandler.cs +++ b/src/Protocol/Document/IWillSaveTextDocumentHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Threading; using System.Threading.Tasks; using MediatR; @@ -7,21 +6,22 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Parallel, Method(TextDocumentNames.WillSave, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IWillSaveTextDocumentHandler : IJsonRpcNotificationHandler, IRegistration, ICapability { } + [Parallel] + [Method(TextDocumentNames.WillSave, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IWillSaveTextDocumentHandler : IJsonRpcNotificationHandler, IRegistration, + ICapability + { + } public abstract class WillSaveTextDocumentHandler : IWillSaveTextDocumentHandler { private readonly TextDocumentRegistrationOptions _options; - public WillSaveTextDocumentHandler(TextDocumentRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public WillSaveTextDocumentHandler(TextDocumentRegistrationOptions registrationOptions) => _options = registrationOptions; public TextDocumentRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(WillSaveTextDocumentParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/IWillSaveWaitUntilTextDocumentHandler.cs b/src/Protocol/Document/IWillSaveWaitUntilTextDocumentHandler.cs index 1ef780351..e90f934f8 100644 --- a/src/Protocol/Document/IWillSaveWaitUntilTextDocumentHandler.cs +++ b/src/Protocol/Document/IWillSaveWaitUntilTextDocumentHandler.cs @@ -8,17 +8,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { - [Serial, Method(TextDocumentNames.WillSaveWaitUntil, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IWillSaveWaitUntilTextDocumentHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Serial] + [Method(TextDocumentNames.WillSaveWaitUntil, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IWillSaveWaitUntilTextDocumentHandler : IJsonRpcRequestHandler, + IRegistration, ICapability + { + } public abstract class WillSaveWaitUntilTextDocumentHandler : IWillSaveWaitUntilTextDocumentHandler { private readonly TextDocumentRegistrationOptions _options; - public WillSaveWaitUntilTextDocumentHandler(TextDocumentRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public WillSaveWaitUntilTextDocumentHandler(TextDocumentRegistrationOptions registrationOptions) => _options = registrationOptions; public TextDocumentRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(WillSaveWaitUntilTextDocumentParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Document/Proposals/ICallHierarchyHandler.cs b/src/Protocol/Document/Proposals/ICallHierarchyHandler.cs index 2d98f6c12..bcf87a33d 100644 --- a/src/Protocol/Document/Proposals/ICallHierarchyHandler.cs +++ b/src/Protocol/Document/Proposals/ICallHierarchyHandler.cs @@ -15,8 +15,10 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document.Proposals { [Obsolete(Constants.Proposal)] - [Parallel, Method(TextDocumentNames.PrepareCallHierarchy, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [Parallel] + [Method(TextDocumentNames.PrepareCallHierarchy, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface ICallHierarchyHandler : IJsonRpcRequestHandler>, IRegistration, ICapability @@ -24,44 +26,51 @@ public interface ICallHierarchyHandler : } [Obsolete(Constants.Proposal)] - [Parallel, Method(TextDocumentNames.CallHierarchyIncoming, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [Parallel] + [Method(TextDocumentNames.CallHierarchyIncoming, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface ICallHierarchyIncomingHandler : IJsonRpcRequestHandler>, - IRegistration, ICapability + Container>, + IRegistration, ICapability { } [Obsolete(Constants.Proposal)] - [Parallel, Method(TextDocumentNames.CallHierarchyOutgoing, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [Parallel] + [Method(TextDocumentNames.CallHierarchyOutgoing, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface ICallHierarchyOutgoingHandler : IJsonRpcRequestHandler>, - IRegistration, ICapability + Container>, + IRegistration, ICapability { } [Obsolete(Constants.Proposal)] public abstract class CallHierarchyHandler : ICallHierarchyHandler, ICallHierarchyIncomingHandler, - ICallHierarchyOutgoingHandler + ICallHierarchyOutgoingHandler { private readonly CallHierarchyRegistrationOptions _options; - public CallHierarchyHandler(CallHierarchyRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public CallHierarchyHandler(CallHierarchyRegistrationOptions registrationOptions) => _options = registrationOptions; public CallHierarchyRegistrationOptions GetRegistrationOptions() => _options; - public abstract Task> Handle(CallHierarchyPrepareParams request, - CancellationToken cancellationToken); + public abstract Task> Handle( + CallHierarchyPrepareParams request, + CancellationToken cancellationToken + ); - public abstract Task> Handle(CallHierarchyIncomingCallsParams request, - CancellationToken cancellationToken); + public abstract Task> Handle( + CallHierarchyIncomingCallsParams request, + CancellationToken cancellationToken + ); - public abstract Task> Handle(CallHierarchyOutgoingCallsParams request, - CancellationToken cancellationToken); + public abstract Task> Handle( + CallHierarchyOutgoingCallsParams request, + CancellationToken cancellationToken + ); public virtual void SetCapability(CallHierarchyCapability capability) => Capability = capability; protected CallHierarchyCapability Capability { get; private set; } @@ -75,201 +84,280 @@ public static ILanguageServerRegistry OnCallHierarchy( Func>> handler, Func>> incomingHandler, Func>> outgoingHandler, - CallHierarchyRegistrationOptions registrationOptions) + CallHierarchyRegistrationOptions registrationOptions + ) { registrationOptions ??= new CallHierarchyRegistrationOptions(); - return registry.AddHandler(TextDocumentNames.PrepareCallHierarchy, - new LanguageProtocolDelegatingHandlers.Request, - CallHierarchyCapability, - CallHierarchyRegistrationOptions>(handler, registrationOptions)) - .AddHandler(TextDocumentNames.CallHierarchyIncoming, - new LanguageProtocolDelegatingHandlers.Request, - CallHierarchyCapability, - CallHierarchyRegistrationOptions>(incomingHandler, registrationOptions)) - .AddHandler(TextDocumentNames.CallHierarchyOutgoing, - new LanguageProtocolDelegatingHandlers.Request, - CallHierarchyCapability, - CallHierarchyRegistrationOptions>(outgoingHandler, registrationOptions)) + return registry.AddHandler( + TextDocumentNames.PrepareCallHierarchy, + new LanguageProtocolDelegatingHandlers.Request, + CallHierarchyCapability, + CallHierarchyRegistrationOptions>(handler, registrationOptions) + ) + .AddHandler( + TextDocumentNames.CallHierarchyIncoming, + new LanguageProtocolDelegatingHandlers.Request, + CallHierarchyCapability, + CallHierarchyRegistrationOptions>(incomingHandler, registrationOptions) + ) + .AddHandler( + TextDocumentNames.CallHierarchyOutgoing, + new LanguageProtocolDelegatingHandlers.Request, + CallHierarchyCapability, + CallHierarchyRegistrationOptions>(outgoingHandler, registrationOptions) + ) ; } - public static ILanguageServerRegistry OnCallHierarchy(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCallHierarchy( + this ILanguageServerRegistry registry, Func>> handler, Func>> incomingHandler, Func>> outgoingHandler, - CallHierarchyRegistrationOptions registrationOptions) + CallHierarchyRegistrationOptions registrationOptions + ) { registrationOptions ??= new CallHierarchyRegistrationOptions(); - return registry.AddHandler(TextDocumentNames.PrepareCallHierarchy, - new LanguageProtocolDelegatingHandlers.Request, - CallHierarchyCapability, - CallHierarchyRegistrationOptions>(handler, registrationOptions)) - .AddHandler(TextDocumentNames.CallHierarchyIncoming, - new LanguageProtocolDelegatingHandlers.Request, - CallHierarchyCapability, - CallHierarchyRegistrationOptions>(incomingHandler, registrationOptions)) - .AddHandler(TextDocumentNames.CallHierarchyOutgoing, - new LanguageProtocolDelegatingHandlers.Request, - CallHierarchyCapability, - CallHierarchyRegistrationOptions>(outgoingHandler, registrationOptions)) + return registry.AddHandler( + TextDocumentNames.PrepareCallHierarchy, + new LanguageProtocolDelegatingHandlers.Request, + CallHierarchyCapability, + CallHierarchyRegistrationOptions>(handler, registrationOptions) + ) + .AddHandler( + TextDocumentNames.CallHierarchyIncoming, + new LanguageProtocolDelegatingHandlers.Request, + CallHierarchyCapability, + CallHierarchyRegistrationOptions>(incomingHandler, registrationOptions) + ) + .AddHandler( + TextDocumentNames.CallHierarchyOutgoing, + new LanguageProtocolDelegatingHandlers.Request, + CallHierarchyCapability, + CallHierarchyRegistrationOptions>(outgoingHandler, registrationOptions) + ) ; } - public static ILanguageServerRegistry OnCallHierarchy(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCallHierarchy( + this ILanguageServerRegistry registry, Func>> handler, Func>> incomingHandler, Func>> outgoingHandler, - CallHierarchyRegistrationOptions registrationOptions) + CallHierarchyRegistrationOptions registrationOptions + ) { registrationOptions ??= new CallHierarchyRegistrationOptions(); return - registry.AddHandler(TextDocumentNames.PrepareCallHierarchy, - new LanguageProtocolDelegatingHandlers.RequestRegistration, - CallHierarchyRegistrationOptions>(handler, registrationOptions)) - .AddHandler(TextDocumentNames.CallHierarchyIncoming, - new LanguageProtocolDelegatingHandlers.RequestRegistration, - CallHierarchyRegistrationOptions>(incomingHandler, registrationOptions)) - .AddHandler(TextDocumentNames.CallHierarchyOutgoing, - new LanguageProtocolDelegatingHandlers.RequestRegistration, - CallHierarchyRegistrationOptions>(outgoingHandler, registrationOptions)) + registry.AddHandler( + TextDocumentNames.PrepareCallHierarchy, + new LanguageProtocolDelegatingHandlers.RequestRegistration, + CallHierarchyRegistrationOptions>(handler, registrationOptions) + ) + .AddHandler( + TextDocumentNames.CallHierarchyIncoming, + new LanguageProtocolDelegatingHandlers.RequestRegistration, + CallHierarchyRegistrationOptions>(incomingHandler, registrationOptions) + ) + .AddHandler( + TextDocumentNames.CallHierarchyOutgoing, + new LanguageProtocolDelegatingHandlers.RequestRegistration, + CallHierarchyRegistrationOptions>(outgoingHandler, registrationOptions) + ) ; } - public static ILanguageServerRegistry OnCallHierarchy(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCallHierarchy( + this ILanguageServerRegistry registry, Func>> handler, Func>> incomingHandler, Func>> outgoingHandler, - CallHierarchyRegistrationOptions registrationOptions) + CallHierarchyRegistrationOptions registrationOptions + ) { registrationOptions ??= new CallHierarchyRegistrationOptions(); return - registry.AddHandler(TextDocumentNames.PrepareCallHierarchy, - new LanguageProtocolDelegatingHandlers.RequestRegistration, - CallHierarchyRegistrationOptions>(handler, registrationOptions)) - .AddHandler(TextDocumentNames.CallHierarchyIncoming, - new LanguageProtocolDelegatingHandlers.RequestRegistration, - CallHierarchyRegistrationOptions>(incomingHandler, registrationOptions)) - .AddHandler(TextDocumentNames.CallHierarchyOutgoing, - new LanguageProtocolDelegatingHandlers.RequestRegistration, - CallHierarchyRegistrationOptions>(outgoingHandler, registrationOptions)) + registry.AddHandler( + TextDocumentNames.PrepareCallHierarchy, + new LanguageProtocolDelegatingHandlers.RequestRegistration, + CallHierarchyRegistrationOptions>(handler, registrationOptions) + ) + .AddHandler( + TextDocumentNames.CallHierarchyIncoming, + new LanguageProtocolDelegatingHandlers.RequestRegistration, + CallHierarchyRegistrationOptions>(incomingHandler, registrationOptions) + ) + .AddHandler( + TextDocumentNames.CallHierarchyOutgoing, + new LanguageProtocolDelegatingHandlers.RequestRegistration, + CallHierarchyRegistrationOptions>(outgoingHandler, registrationOptions) + ) ; } - public static ILanguageServerRegistry OnCallHierarchy(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCallHierarchy( + this ILanguageServerRegistry registry, Func>> handler, Action>, CallHierarchyCapability, CancellationToken> incomingHandler, Action>, CallHierarchyCapability, CancellationToken> outgoingHandler, - CallHierarchyRegistrationOptions registrationOptions) + CallHierarchyRegistrationOptions registrationOptions + ) { registrationOptions ??= new CallHierarchyRegistrationOptions(); return - registry.AddHandler(TextDocumentNames.PrepareCallHierarchy, - new LanguageProtocolDelegatingHandlers.Request, - CallHierarchyCapability, - CallHierarchyRegistrationOptions>(handler, registrationOptions)) - .AddHandler(TextDocumentNames.CallHierarchyIncoming, - _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyIncomingCall, - CallHierarchyCapability, - CallHierarchyRegistrationOptions>(incomingHandler, registrationOptions, - _.GetRequiredService(), x => new Container(x))) - .AddHandler(TextDocumentNames.CallHierarchyOutgoing, - _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyOutgoingCall, - CallHierarchyCapability, - CallHierarchyRegistrationOptions>(outgoingHandler, registrationOptions, - _.GetRequiredService(), x => new Container(x))) + registry.AddHandler( + TextDocumentNames.PrepareCallHierarchy, + new LanguageProtocolDelegatingHandlers.Request, + CallHierarchyCapability, + CallHierarchyRegistrationOptions>(handler, registrationOptions) + ) + .AddHandler( + TextDocumentNames.CallHierarchyIncoming, + _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyIncomingCall, + CallHierarchyCapability, + CallHierarchyRegistrationOptions>( + incomingHandler, registrationOptions, + _.GetRequiredService(), x => new Container(x) + ) + ) + .AddHandler( + TextDocumentNames.CallHierarchyOutgoing, + _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyOutgoingCall, + CallHierarchyCapability, + CallHierarchyRegistrationOptions>( + outgoingHandler, registrationOptions, + _.GetRequiredService(), x => new Container(x) + ) + ) ; } - public static ILanguageServerRegistry OnCallHierarchy(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCallHierarchy( + this ILanguageServerRegistry registry, Func>> handler, Action>, CallHierarchyCapability> incomingHandler, Action>, CallHierarchyCapability> outgoingHandler, - CallHierarchyRegistrationOptions registrationOptions) + CallHierarchyRegistrationOptions registrationOptions + ) { registrationOptions ??= new CallHierarchyRegistrationOptions(); return - registry.AddHandler(TextDocumentNames.PrepareCallHierarchy, - new LanguageProtocolDelegatingHandlers.Request, - CallHierarchyCapability, - CallHierarchyRegistrationOptions>(handler, registrationOptions)) - .AddHandler(TextDocumentNames.CallHierarchyIncoming, - _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyIncomingCall, - CallHierarchyCapability, - CallHierarchyRegistrationOptions>(incomingHandler, registrationOptions, - _.GetRequiredService(), x => new Container(x))) - .AddHandler(TextDocumentNames.CallHierarchyOutgoing, - _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyOutgoingCall, - CallHierarchyCapability, - CallHierarchyRegistrationOptions>(outgoingHandler, registrationOptions, - _.GetRequiredService(), x => new Container(x))) + registry.AddHandler( + TextDocumentNames.PrepareCallHierarchy, + new LanguageProtocolDelegatingHandlers.Request, + CallHierarchyCapability, + CallHierarchyRegistrationOptions>(handler, registrationOptions) + ) + .AddHandler( + TextDocumentNames.CallHierarchyIncoming, + _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyIncomingCall, + CallHierarchyCapability, + CallHierarchyRegistrationOptions>( + incomingHandler, registrationOptions, + _.GetRequiredService(), x => new Container(x) + ) + ) + .AddHandler( + TextDocumentNames.CallHierarchyOutgoing, + _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyOutgoingCall, + CallHierarchyCapability, + CallHierarchyRegistrationOptions>( + outgoingHandler, registrationOptions, + _.GetRequiredService(), x => new Container(x) + ) + ) ; } - public static ILanguageServerRegistry OnCallHierarchy(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCallHierarchy( + this ILanguageServerRegistry registry, Func>> handler, Action>, CancellationToken> incomingHandler, Action>, CancellationToken> outgoingHandler, - CallHierarchyRegistrationOptions registrationOptions) + CallHierarchyRegistrationOptions registrationOptions + ) { registrationOptions ??= new CallHierarchyRegistrationOptions(); return - registry.AddHandler(TextDocumentNames.PrepareCallHierarchy, - new LanguageProtocolDelegatingHandlers.RequestRegistration, - CallHierarchyRegistrationOptions>(handler, registrationOptions)) - .AddHandler(TextDocumentNames.CallHierarchyIncoming, - _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyIncomingCall, - CallHierarchyRegistrationOptions>(incomingHandler, registrationOptions, - _.GetRequiredService(), x => new Container(x))) - .AddHandler(TextDocumentNames.CallHierarchyOutgoing, - _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyOutgoingCall, - CallHierarchyRegistrationOptions>(outgoingHandler, registrationOptions, - _.GetRequiredService(), x => new Container(x))) + registry.AddHandler( + TextDocumentNames.PrepareCallHierarchy, + new LanguageProtocolDelegatingHandlers.RequestRegistration, + CallHierarchyRegistrationOptions>(handler, registrationOptions) + ) + .AddHandler( + TextDocumentNames.CallHierarchyIncoming, + _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyIncomingCall, + CallHierarchyRegistrationOptions>( + incomingHandler, registrationOptions, + _.GetRequiredService(), x => new Container(x) + ) + ) + .AddHandler( + TextDocumentNames.CallHierarchyOutgoing, + _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyOutgoingCall, + CallHierarchyRegistrationOptions>( + outgoingHandler, registrationOptions, + _.GetRequiredService(), x => new Container(x) + ) + ) ; } - public static ILanguageServerRegistry OnCallHierarchy(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnCallHierarchy( + this ILanguageServerRegistry registry, Func>> handler, Action>> incomingHandler, Action>> outgoingHandler, - CallHierarchyRegistrationOptions registrationOptions) + CallHierarchyRegistrationOptions registrationOptions + ) { registrationOptions ??= new CallHierarchyRegistrationOptions(); return - registry.AddHandler(TextDocumentNames.PrepareCallHierarchy, - new LanguageProtocolDelegatingHandlers.RequestRegistration, - CallHierarchyRegistrationOptions>(handler, registrationOptions)) - .AddHandler(TextDocumentNames.CallHierarchyIncoming, - _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyIncomingCall, - CallHierarchyRegistrationOptions>(incomingHandler, registrationOptions, - _.GetRequiredService(), x => new Container(x))) - .AddHandler(TextDocumentNames.CallHierarchyOutgoing, - _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyOutgoingCall, - CallHierarchyRegistrationOptions>(outgoingHandler, registrationOptions, - _.GetRequiredService(), x => new Container(x))) + registry.AddHandler( + TextDocumentNames.PrepareCallHierarchy, + new LanguageProtocolDelegatingHandlers.RequestRegistration, + CallHierarchyRegistrationOptions>(handler, registrationOptions) + ) + .AddHandler( + TextDocumentNames.CallHierarchyIncoming, + _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyIncomingCall, + CallHierarchyRegistrationOptions>( + incomingHandler, registrationOptions, + _.GetRequiredService(), x => new Container(x) + ) + ) + .AddHandler( + TextDocumentNames.CallHierarchyOutgoing, + _ => new LanguageProtocolDelegatingHandlers.PartialResults, CallHierarchyOutgoingCall, + CallHierarchyRegistrationOptions>( + outgoingHandler, registrationOptions, + _.GetRequiredService(), x => new Container(x) + ) + ) ; } } diff --git a/src/Protocol/Document/Proposals/ISemanticTokensDeltaHandler.cs b/src/Protocol/Document/Proposals/ISemanticTokensDeltaHandler.cs index 431e46e32..4639cfd08 100644 --- a/src/Protocol/Document/Proposals/ISemanticTokensDeltaHandler.cs +++ b/src/Protocol/Document/Proposals/ISemanticTokensDeltaHandler.cs @@ -12,14 +12,16 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Document.Proposals { [Obsolete(Constants.Proposal)] - [Parallel, Method(TextDocumentNames.SemanticTokensFull, Direction.ClientToServer)] + [Parallel] + [Method(TextDocumentNames.SemanticTokensFull, Direction.ClientToServer)] public interface ISemanticTokensHandler : IJsonRpcRequestHandler, - IRegistration, ICapability + IRegistration, ICapability { } [Obsolete(Constants.Proposal)] - [Parallel, Method(TextDocumentNames.SemanticTokensFullDelta, Direction.ClientToServer)] + [Parallel] + [Method(TextDocumentNames.SemanticTokensFullDelta, Direction.ClientToServer)] public interface ISemanticTokensDeltaHandler : IJsonRpcRequestHandler, IRegistration, ICapability, IDoesNotParticipateInRegistration @@ -27,22 +29,20 @@ public interface ISemanticTokensDeltaHandler : } [Obsolete(Constants.Proposal)] - [Parallel, Method(TextDocumentNames.SemanticTokensRange, Direction.ClientToServer)] + [Parallel] + [Method(TextDocumentNames.SemanticTokensRange, Direction.ClientToServer)] public interface ISemanticTokensRangeHandler : IJsonRpcRequestHandler, - IRegistration, ICapability, IDoesNotParticipateInRegistration + IRegistration, ICapability, IDoesNotParticipateInRegistration { } [Obsolete(Constants.Proposal)] public abstract class SemanticTokensHandlerBase : ISemanticTokensHandler, ISemanticTokensDeltaHandler, - ISemanticTokensRangeHandler + ISemanticTokensRangeHandler { private readonly SemanticTokensRegistrationOptions _options; - public SemanticTokensHandlerBase(SemanticTokensRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public SemanticTokensHandlerBase(SemanticTokensRegistrationOptions registrationOptions) => _options = registrationOptions; public SemanticTokensRegistrationOptions GetRegistrationOptions() => _options; @@ -81,12 +81,14 @@ public virtual async Task Handle(SemanticTokensRangeParams reque [Obsolete(Constants.Proposal)] public static class SemanticTokensExtensions { - public static ILanguageServerRegistry OnSemanticTokens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnSemanticTokens( + this ILanguageServerRegistry registry, Func tokenize, Func> getSemanticTokensDocument, - SemanticTokensRegistrationOptions registrationOptions) + SemanticTokensRegistrationOptions registrationOptions + ) { - registrationOptions ??= new SemanticTokensRegistrationOptions() { + registrationOptions ??= new SemanticTokensRegistrationOptions { Full = new SemanticTokensCapabilityRequestFull() }; registrationOptions.Range ??= new SemanticTokensCapabilityRequestRange(); @@ -96,15 +98,18 @@ public static ILanguageServerRegistry OnSemanticTokens(this ILanguageServerRegis } return registry.AddHandlers( - new DelegatingHandlerBase(tokenize, getSemanticTokensDocument, registrationOptions)); + new DelegatingHandlerBase(tokenize, getSemanticTokensDocument, registrationOptions) + ); } - public static ILanguageServerRegistry OnSemanticTokens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnSemanticTokens( + this ILanguageServerRegistry registry, Func tokenize, Func> getSemanticTokensDocument, - SemanticTokensRegistrationOptions registrationOptions) + SemanticTokensRegistrationOptions registrationOptions + ) { - registrationOptions ??= new SemanticTokensRegistrationOptions() { + registrationOptions ??= new SemanticTokensRegistrationOptions { Full = new SemanticTokensCapabilityRequestFull() }; registrationOptions.Range ??= new SemanticTokensCapabilityRequestRange(); @@ -117,15 +122,19 @@ public static ILanguageServerRegistry OnSemanticTokens(this ILanguageServerRegis new DelegatingHandlerBase( (a, t, c, ct) => tokenize(a, t, ct), (a, c, ct) => getSemanticTokensDocument(a, ct), - registrationOptions)); + registrationOptions + ) + ); } - public static ILanguageServerRegistry OnSemanticTokens(this ILanguageServerRegistry registry, + public static ILanguageServerRegistry OnSemanticTokens( + this ILanguageServerRegistry registry, Func tokenize, Func> getSemanticTokensDocument, - SemanticTokensRegistrationOptions registrationOptions) + SemanticTokensRegistrationOptions registrationOptions + ) { - registrationOptions ??= new SemanticTokensRegistrationOptions() { + registrationOptions ??= new SemanticTokensRegistrationOptions { Full = new SemanticTokensCapabilityRequestFull() }; registrationOptions.Range ??= new SemanticTokensCapabilityRequestRange(); @@ -138,10 +147,12 @@ public static ILanguageServerRegistry OnSemanticTokens(this ILanguageServerRegis new DelegatingHandlerBase( (a, t, c, ct) => tokenize(a, t), (a, c, ct) => getSemanticTokensDocument(a), - registrationOptions)); + registrationOptions + ) + ); } - class DelegatingHandlerBase : SemanticTokensHandlerBase + private class DelegatingHandlerBase : SemanticTokensHandlerBase { private readonly Func _tokenize; private readonly Func> _getSemanticTokensDocument; @@ -170,57 +181,69 @@ SemanticTokensRegistrationOptions registrationOptions { } - protected override Task Tokenize(SemanticTokensBuilder builder, ITextDocumentIdentifierParams identifier, - CancellationToken cancellationToken) => + protected override Task Tokenize( + SemanticTokensBuilder builder, ITextDocumentIdentifierParams identifier, + CancellationToken cancellationToken + ) => _tokenize(builder, identifier, _capability, cancellationToken); protected override Task GetSemanticTokensDocument( - ITextDocumentIdentifierParams @params, CancellationToken cancellationToken) => + ITextDocumentIdentifierParams @params, CancellationToken cancellationToken + ) => _getSemanticTokensDocument(@params, _capability, cancellationToken); public override void SetCapability(SemanticTokensCapability capability) => _capability = capability; } - public static IRequestProgressObservable RequestSemanticTokens(this ITextDocumentLanguageClient mediator, - SemanticTokensParams @params, CancellationToken cancellationToken = default) - { - return mediator.ProgressManager.MonitorUntil(@params, (partial, result) => new SemanticTokens() { - Data = partial.Data, - ResultId = result.ResultId - }, cancellationToken); - } + public static IRequestProgressObservable RequestSemanticTokens( + this ITextDocumentLanguageClient mediator, + SemanticTokensParams @params, CancellationToken cancellationToken = default + ) => + mediator.ProgressManager.MonitorUntil( + @params, (partial, result) => new SemanticTokens { + Data = partial.Data, + ResultId = result.ResultId + }, cancellationToken + ); public static IRequestProgressObservable RequestSemanticTokensDelta( - this ITextDocumentLanguageClient mediator, SemanticTokensDeltaParams @params, CancellationToken cancellationToken = default) - { - return mediator.ProgressManager.MonitorUntil(@params, (partial, result) => { - if (partial.IsDelta) - { - return new SemanticTokensFullOrDelta(new SemanticTokensDelta() { - Edits = partial.Delta.Edits, - ResultId = result.Delta?.ResultId ?? result.Full?.ResultId - }); - } - - if (partial.IsFull) - { - return new SemanticTokensFullOrDelta(new SemanticTokens() { - Data = partial.Full.Data, - ResultId = result.Full?.ResultId ?? result.Delta?.ResultId - }); - } - - return new SemanticTokensFullOrDelta(new SemanticTokens()); - }, cancellationToken); - } - - public static IRequestProgressObservable RequestSemanticTokensRange(this ITextDocumentLanguageClient mediator, - SemanticTokensRangeParams @params, CancellationToken cancellationToken = default) - { - return mediator.ProgressManager.MonitorUntil(@params, (partial, result) => new SemanticTokens() { - Data = partial.Data, - ResultId = result.ResultId - }, cancellationToken); - } + this ITextDocumentLanguageClient mediator, SemanticTokensDeltaParams @params, CancellationToken cancellationToken = default + ) => + mediator.ProgressManager.MonitorUntil( + @params, (partial, result) => { + if (partial.IsDelta) + { + return new SemanticTokensFullOrDelta( + new SemanticTokensDelta { + Edits = partial.Delta.Edits, + ResultId = result.Delta?.ResultId ?? result.Full?.ResultId + } + ); + } + + if (partial.IsFull) + { + return new SemanticTokensFullOrDelta( + new SemanticTokens { + Data = partial.Full.Data, + ResultId = result.Full?.ResultId ?? result.Delta?.ResultId + } + ); + } + + return new SemanticTokensFullOrDelta(new SemanticTokens()); + }, cancellationToken + ); + + public static IRequestProgressObservable RequestSemanticTokensRange( + this ITextDocumentLanguageClient mediator, + SemanticTokensRangeParams @params, CancellationToken cancellationToken = default + ) => + mediator.ProgressManager.MonitorUntil( + @params, (partial, result) => new SemanticTokens { + Data = partial.Data, + ResultId = result.ResultId + }, cancellationToken + ); } } diff --git a/src/Protocol/Document/Proposals/SemanticTokensBuilder.cs b/src/Protocol/Document/Proposals/SemanticTokensBuilder.cs index 0679dca35..81ea7f5aa 100644 --- a/src/Protocol/Document/Proposals/SemanticTokensBuilder.cs +++ b/src/Protocol/Document/Proposals/SemanticTokensBuilder.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals; using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; @@ -23,7 +24,8 @@ public class SemanticTokensBuilder public SemanticTokensBuilder( SemanticTokensDocument document, - SemanticTokensLegend legend) + SemanticTokensLegend legend + ) { _document = document; _legend = legend; @@ -38,10 +40,9 @@ public SemanticTokensBuilder( /// /// /// - public void Push(int line, int @char, int length, SemanticTokenType? tokenType, params SemanticTokenModifier[] tokenModifiers) - { - Push(line, @char, length, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers)); - } + public void Push(int line, int @char, int length, SemanticTokenType? tokenType, params SemanticTokenModifier[] tokenModifiers) => Push( + line, @char, length, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers) + ); /// /// Push a token onto the builder @@ -50,10 +51,9 @@ public void Push(int line, int @char, int length, SemanticTokenType? tokenType, /// The range, cannot span multiple lines /// /// - public void Push(Range range, SemanticTokenType? tokenType, params SemanticTokenModifier[] tokenModifiers) - { - Push(range, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers)); - } + public void Push(Range range, SemanticTokenType? tokenType, params SemanticTokenModifier[] tokenModifiers) => Push( + range, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers) + ); /// /// Push a token onto the builder @@ -63,10 +63,9 @@ public void Push(Range range, SemanticTokenType? tokenType, params SemanticToken /// /// /// - public void Push(int line, int @char, int length, SemanticTokenType? tokenType, IEnumerable tokenModifiers) - { - Push(line, @char, length, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers)); - } + public void Push(int line, int @char, int length, SemanticTokenType? tokenType, IEnumerable tokenModifiers) => Push( + line, @char, length, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers) + ); /// /// Push a token onto the builder @@ -75,10 +74,9 @@ public void Push(int line, int @char, int length, SemanticTokenType? tokenType, /// The range, cannot span multiple lines /// /// - public void Push(Range range, SemanticTokenType? tokenType, IEnumerable tokenModifiers) - { - Push(range, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers)); - } + public void Push(Range range, SemanticTokenType? tokenType, IEnumerable tokenModifiers) => Push( + range, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers) + ); /// /// Push a token onto the builder @@ -88,10 +86,9 @@ public void Push(Range range, SemanticTokenType? tokenType, IEnumerable /// /// - public void Push(int line, int @char, int length, string tokenType, params string[] tokenModifiers) - { - Push(line, @char, length, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers)); - } + public void Push(int line, int @char, int length, string tokenType, params string[] tokenModifiers) => Push( + line, @char, length, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers) + ); /// /// Push a token onto the builder @@ -100,10 +97,9 @@ public void Push(int line, int @char, int length, string tokenType, params strin /// The range, cannot span multiple lines /// /// - public void Push(Range range, string tokenType, params string[] tokenModifiers) - { - Push(range, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers)); - } + public void Push(Range range, string tokenType, params string[] tokenModifiers) => Push( + range, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers) + ); /// /// Push a token onto the builder @@ -113,11 +109,11 @@ public void Push(Range range, string tokenType, params string[] tokenModifiers) /// /// /// - public void Push(int line, int @char, int length, string tokenType, IEnumerable tokenModifiers) - { - Push(line, @char, length, _legend.GetTokenTypeIdentity(tokenType), - _legend.GetTokenModifiersIdentity(tokenModifiers)); - } + public void Push(int line, int @char, int length, string tokenType, IEnumerable tokenModifiers) => + Push( + line, @char, length, _legend.GetTokenTypeIdentity(tokenType), + _legend.GetTokenModifiersIdentity(tokenModifiers) + ); /// /// Push a token onto the builder @@ -126,10 +122,9 @@ public void Push(int line, int @char, int length, string tokenType, IEnumerable< /// The range, cannot span multiple lines /// /// - public void Push(Range range, string tokenType, IEnumerable tokenModifiers) - { - Push(range, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers)); - } + public void Push(Range range, string tokenType, IEnumerable tokenModifiers) => Push( + range, _legend.GetTokenTypeIdentity(tokenType), _legend.GetTokenModifiersIdentity(tokenModifiers) + ); /// /// Push a token onto the builder diff --git a/src/Protocol/Document/Proposals/SemanticTokensDocument.cs b/src/Protocol/Document/Proposals/SemanticTokensDocument.cs index 8bc5981ac..0b56e2a3c 100644 --- a/src/Protocol/Document/Proposals/SemanticTokensDocument.cs +++ b/src/Protocol/Document/Proposals/SemanticTokensDocument.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Immutable; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals; using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; @@ -56,7 +57,7 @@ public SemanticTokensBuilder Edit(SemanticTokensDeltaParams @params) public SemanticTokens GetSemanticTokens() { _prevData = null; - return new SemanticTokens() { + return new SemanticTokens { ResultId = Id, Data = _data }; @@ -96,7 +97,7 @@ public SemanticTokens GetSemanticTokens(Range range) if (currentCharOffset + charOffset + length >= range.Start.Character) { capturing = true; - var overlap = ((currentCharOffset + charOffset + length) - range.Start.Character); + var overlap = currentCharOffset + charOffset + length - range.Start.Character; data.AddRange(0, 0, overlap, _data[i + 3], _data[i + 4]); innerOffset = charOffset - overlap; continue; @@ -120,7 +121,7 @@ public SemanticTokens GetSemanticTokens(Range range) if (currentCharOffset + charOffset + length >= range.End.Character) { capturing = false; - var overlap = ((currentCharOffset + charOffset + length) - range.End.Character); + var overlap = currentCharOffset + charOffset + length - range.End.Character; data.AddRange(lineOffset, charOffset, length - overlap, _data[i + 3], _data[i + 4]); break; } @@ -133,8 +134,10 @@ public SemanticTokens GetSemanticTokens(Range range) { if (innerOffset > 0) { - data.AddRange(_data[i], _data[i + 1] - innerOffset, _data[i + 2], _data[i + 3], - _data[i + 4]); + data.AddRange( + _data[i], _data[i + 1] - innerOffset, _data[i + 2], _data[i + 3], + _data[i + 4] + ); innerOffset = 0; } else @@ -145,7 +148,7 @@ public SemanticTokens GetSemanticTokens(Range range) } } - return new SemanticTokens() { + return new SemanticTokens { ResultId = Id, Data = data.ToImmutable() }; diff --git a/src/Protocol/Document/TextDocumentAttributes.cs b/src/Protocol/Document/TextDocumentAttributes.cs index e0e266bdf..0790da773 100644 --- a/src/Protocol/Document/TextDocumentAttributes.cs +++ b/src/Protocol/Document/TextDocumentAttributes.cs @@ -22,18 +22,13 @@ public TextDocumentAttributes(DocumentUri uri, string scheme, string languageId) public string Scheme { get; } public string LanguageId { get; } - public override bool Equals(object obj) - { - return Equals(obj as TextDocumentAttributes); - } + public override bool Equals(object obj) => Equals(obj as TextDocumentAttributes); - public bool Equals(TextDocumentAttributes other) - { - return other != null && - DocumentUri.Comparer.Equals(Uri, other.Uri) && - Scheme == other.Scheme && - LanguageId == other.LanguageId; - } + public bool Equals(TextDocumentAttributes other) => + other != null && + DocumentUri.Comparer.Equals(Uri, other.Uri) && + Scheme == other.Scheme && + LanguageId == other.LanguageId; public override int GetHashCode() { @@ -44,14 +39,9 @@ public override int GetHashCode() return hashCode; } - public static bool operator ==(TextDocumentAttributes attributes1, TextDocumentAttributes attributes2) - { - return EqualityComparer.Default.Equals(attributes1, attributes2); - } + public static bool operator ==(TextDocumentAttributes attributes1, TextDocumentAttributes attributes2) => + EqualityComparer.Default.Equals(attributes1, attributes2); - public static bool operator !=(TextDocumentAttributes attributes1, TextDocumentAttributes attributes2) - { - return !(attributes1 == attributes2); - } + public static bool operator !=(TextDocumentAttributes attributes1, TextDocumentAttributes attributes2) => !( attributes1 == attributes2 ); } } diff --git a/src/Protocol/DocumentUri.Internal.cs b/src/Protocol/DocumentUri.Internal.cs index cd8ef198e..956bd3849 100644 --- a/src/Protocol/DocumentUri.Internal.cs +++ b/src/Protocol/DocumentUri.Internal.cs @@ -14,35 +14,17 @@ public partial class DocumentUri private static readonly Regex SingleSlashStart = new Regex(@"^\/"); private static readonly Regex DoubleSlashStart = new Regex(@"^\/\/"); - private static bool IsHighSurrogate(int charCode) - { - return 0xD800 <= charCode && charCode <= 0xDBFF; - } + private static bool IsHighSurrogate(int charCode) => 0xD800 <= charCode && charCode <= 0xDBFF; - private static bool IsLowSurrogate(int charCode) - { - return 0xDC00 <= charCode && charCode <= 0xDFFF; - } + private static bool IsLowSurrogate(int charCode) => 0xDC00 <= charCode && charCode <= 0xDFFF; - private static bool IsLowerAsciiHex(int code) - { - return code >= CharCode.a && code <= CharCode.f; - } + private static bool IsLowerAsciiHex(int code) => code >= CharCode.a && code <= CharCode.f; - private static bool IsLowerAsciiLetter(int code) - { - return code >= CharCode.a && code <= CharCode.z; - } + private static bool IsLowerAsciiLetter(int code) => code >= CharCode.a && code <= CharCode.z; - private static bool IsUpperAsciiLetter(int code) - { - return code >= CharCode.A && code <= CharCode.Z; - } + private static bool IsUpperAsciiLetter(int code) => code >= CharCode.A && code <= CharCode.Z; - private static bool IsAsciiLetter(int code) - { - return IsLowerAsciiLetter(code) || IsUpperAsciiLetter(code); - } + private static bool IsAsciiLetter(int code) => IsLowerAsciiLetter(code) || IsUpperAsciiLetter(code); private static void _validateUri(DocumentUri ret, bool? strict) { @@ -50,7 +32,8 @@ private static void _validateUri(DocumentUri ret, bool? strict) if (string.IsNullOrWhiteSpace(ret.Scheme) && strict == true) { throw new UriFormatException( - $@"Scheme is missing: {{scheme: "", authority: ""{ret.Authority}"", path: ""{ret.Path}"", query: ""${ret.Query}"", fragment: ""{ret.Fragment}""}}"); + $@"Scheme is missing: {{scheme: "", authority: ""{ret.Authority}"", path: ""{ret.Path}"", query: ""${ret.Query}"", fragment: ""{ret.Fragment}""}}" + ); } // scheme, https://tools.ietf.org/html/rfc3986#section-3.1 @@ -72,7 +55,8 @@ private static void _validateUri(DocumentUri ret, bool? strict) if (!SingleSlashStart.IsMatch(ret.Path)) { throw new UriFormatException( - "If a URI contains an authority component, then the path component must either be empty or begin with a slash (\"/\") character"); + "If a URI contains an authority component, then the path component must either be empty or begin with a slash (\"/\") character" + ); } } else @@ -80,7 +64,8 @@ private static void _validateUri(DocumentUri ret, bool? strict) if (DoubleSlashStart.IsMatch(ret.Path)) { throw new UriFormatException( - "If a URI does not contain an authority component, then the path cannot begin with two slash characters (\"//\")"); + "If a URI does not contain an authority component, then the path cannot begin with two slash characters (\"//\")" + ); } } } @@ -124,7 +109,7 @@ 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", @@ -159,18 +144,18 @@ 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.Dash - || code == CharCode.Period - || code == CharCode.Underline - || code == CharCode.Tilde - || (allowSlash && code == CharCode.Slash) - || allowSlash && (pos == 1 || pos == 2) && ( + 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 + || uriComponent.Length >= 2 && uriComponent[1] == CharCode.Colon ) ) { @@ -265,10 +250,10 @@ 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[2] == CharCode.Colon + && 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[2] == CharCode.Colon ) { if (!keepDriveLetterCasing) @@ -408,10 +393,8 @@ private static string DecodeUriComponentGraceful(string str) { return str.Substring(0, 3) + DecodeUriComponentGraceful(str.Substring(3)); } - else - { - return str; - } + + return str; } } diff --git a/src/Protocol/DocumentUri.cs b/src/Protocol/DocumentUri.cs index 355459275..35057caa8 100644 --- a/src/Protocol/DocumentUri.cs +++ b/src/Protocol/DocumentUri.cs @@ -12,15 +12,15 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol /// This class is a simple parser which creates the basic component parts /// (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation /// and encoding. - /// + /// /// ```txt - /// foo://example.com:8042/over/there?name=ferret#nose - /// \_/ \______________/\_________/ \_________/ \__/ - /// | | | | | - /// scheme authority path query fragment - /// | _____________________|__ - /// / \ / \ - /// urn:example:animal:ferret:nose + /// foo://example.com:8042/over/there?name=ferret#nose + /// \_/ \______________/\_________/ \_________/ \__/ + /// | | | | | + /// scheme authority path query fragment + /// | _____________________|__ + /// / \ / \ + /// urn:example:animal:ferret:nose /// ``` /// /// @@ -58,7 +58,7 @@ public partial class DocumentUri : IEquatable public string Fragment { get; } /// - /// Convert the uri to a + /// Convert the uri to a /// /// /// This will produce a uri where asian and cyrillic characters will be encoded @@ -69,7 +69,7 @@ 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 +79,7 @@ public Uri ToUri() }.Uri; } - return new UriBuilder() { + return new UriBuilder { Scheme = Scheme, Host = Authority, Path = Path, @@ -101,15 +101,9 @@ public Uri ToUri() /// /// @param skipEncoding Do not encode the result, default is `false` /// - public override string ToString() - { - return _asFormatted(this, false); - } + public override string ToString() => _asFormatted(this, false); - public string ToUnencodedString() - { - return _asFormatted(this, true); - } + public string ToUnencodedString() => _asFormatted(this, true); /// /// Gets the file system path prefixed with / for unix platforms @@ -152,10 +146,10 @@ public override int GetHashCode() unchecked { var hashCode = comparer.GetHashCode(Path); - hashCode = (hashCode * 397) ^ comparer.GetHashCode(Scheme); - hashCode = (hashCode * 397) ^ comparer.GetHashCode(Authority); - hashCode = (hashCode * 397) ^ comparer.GetHashCode(Query); - hashCode = (hashCode * 397) ^ comparer.GetHashCode(Fragment); + hashCode = ( hashCode * 397 ) ^ comparer.GetHashCode(Scheme); + hashCode = ( hashCode * 397 ) ^ comparer.GetHashCode(Authority); + hashCode = ( hashCode * 397 ) ^ comparer.GetHashCode(Query); + hashCode = ( hashCode * 397 ) ^ comparer.GetHashCode(Fragment); return hashCode; } } @@ -169,12 +163,14 @@ public override int GetHashCode() /// /// /// - public void Deconstruct(out string scheme, out string authority, out string path, out string query, - out string fragment) + public void Deconstruct( + out string scheme, out string authority, out string path, out string query, + out string fragment + ) { scheme = Scheme; authority = Authority; - path = Path; + path = Path; query = Query; fragment = Fragment; } @@ -196,15 +192,15 @@ public void Deconstruct(out string scheme, out string authority, out string path public static bool operator !=(DocumentUri left, DocumentUri right) => !Equals(left, right); /// - /// Convert this uri into a . + /// 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(); /// - /// Convert this into a . + /// Convert this into a . /// /// /// The uri class has issues with higher level utf8 characters such as asian and cyrillic characters @@ -226,7 +222,7 @@ public void Deconstruct(out string scheme, out string authority, out string path public static implicit operator DocumentUri(Uri uri) => From(uri); /// - /// Create a new document uri from the given + /// Create a new document uri from the given /// /// /// @@ -249,11 +245,12 @@ public static DocumentUri From(Uri uri) /// public static DocumentUri From(string url) { - if (string.IsNullOrWhiteSpace (url)) + if (string.IsNullOrWhiteSpace(url)) { throw new UriFormatException("Given uri is null or empty"); } - if (url.StartsWith(@"\\") || (url.StartsWith("/")) || WindowsPath.IsMatch(url)) + + if (url.StartsWith(@"\\") || url.StartsWith("/") || WindowsPath.IsMatch(url)) { return File(url); } @@ -262,37 +259,37 @@ public static DocumentUri From(string url) } /// - /// Get the local file-system path for the specified document URI. + /// Get the local file-system path for the specified document URI. /// /// - /// The text document params object + /// The text document params object /// /// - /// The file-system path, or null if the URI does not represent a file-system path. + /// 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); /// - /// Get the local file-system path for the specified document URI. + /// Get the local file-system path for the specified document URI. /// /// - /// The text document identifier + /// The text document identifier /// /// - /// The file-system path, or null if the URI does not represent a file-system path. + /// 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); /// - /// Get the local file-system path for the specified document URI. + /// Get the local file-system path for the specified document URI. /// /// - /// The LSP document URI. + /// The LSP document URI. /// /// - /// The file-system path, or null if the URI does not represent a file-system path. + /// The file-system path, or null if the URI does not represent a file-system path. /// public static string GetFileSystemPath(DocumentUri documentUri) { @@ -306,13 +303,13 @@ public static string GetFileSystemPath(DocumentUri documentUri) } /// - /// Convert a file-system path to an LSP document URI. + /// Convert a file-system path to an LSP document URI. /// /// - /// The file-system path. + /// The file-system path. /// /// - /// The LSP document URI. + /// The LSP document URI. /// public static DocumentUri FromFileSystemPath(string fileSystemPath) => File(fileSystemPath); @@ -349,8 +346,10 @@ public bool Equals(DocumentUri x, DocumentUri y) /// /// @internal /// - public DocumentUri(string scheme, string authority, string path, string query, string fragment, - bool? strict = null) + public DocumentUri( + string scheme, string authority, string path, string query, string fragment, + bool? strict = null + ) { Scheme = SchemeFix(scheme, strict); Authority = authority ?? Empty; @@ -371,10 +370,11 @@ public DocumentUri(string scheme, string authority, string path, string query, s /// public static DocumentUri Parse(string value, bool strict = false) { - if (string.IsNullOrWhiteSpace (value)) + if (string.IsNullOrWhiteSpace(value)) { throw new UriFormatException("Given uri is null or empty"); } + var match = Regexp.Match(value); if (!match.Success) { @@ -404,10 +404,11 @@ public static DocumentUri Parse(string value, bool strict = false) /// public static DocumentUri File(string path) { - if (string.IsNullOrWhiteSpace (path)) + if (string.IsNullOrWhiteSpace(path)) { throw new UriFormatException("Given path is null or empty"); } + var authority = Empty; // normalize to fwd-slashes on windows, @@ -441,29 +442,25 @@ public static DocumentUri File(string path) path = path.Replace("%3a", ":").Replace("%3A", ":"); } - return new DocumentUri("file", authority, path, Empty, Empty, null); + return new DocumentUri("file", authority, path, Empty, Empty); } - public DocumentUri With(DocumentUriComponents components) - { - return new DocumentUri( + public DocumentUri With(DocumentUriComponents components) => + new DocumentUri( components.Scheme ?? Scheme, components.Authority ?? Authority, components.Path ?? Path, components.Query ?? Query, components.Fragment ?? Fragment ); - } - public static DocumentUri From(DocumentUriComponents components) - { - return new DocumentUri( + public static DocumentUri From(DocumentUriComponents components) => + 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/General/IExitHandler.cs b/src/Protocol/General/IExitHandler.cs index b9d93e387..376b1fa53 100644 --- a/src/Protocol/General/IExitHandler.cs +++ b/src/Protocol/General/IExitHandler.cs @@ -8,7 +8,10 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.General { - [Serial, Method(GeneralNames.Exit, Direction.ClientToServer), GenerateHandlerMethods, GenerateRequestMethods] + [Serial] + [Method(GeneralNames.Exit, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods] public interface IExitHandler : IJsonRpcNotificationHandler { } @@ -26,9 +29,6 @@ public virtual async Task Handle(ExitParams request, CancellationToken can public static partial class ExitExtensions { - public static void SendExit(this ILanguageClient mediator) - { - mediator.SendNotification(ExitParams.Instance); - } + public static void SendExit(this ILanguageClient mediator) => mediator.SendNotification(ExitParams.Instance); } } diff --git a/src/Protocol/General/ILanguageProtocolInitializeHandler.cs b/src/Protocol/General/ILanguageProtocolInitializeHandler.cs index fda94eac7..c4b635f31 100644 --- a/src/Protocol/General/ILanguageProtocolInitializeHandler.cs +++ b/src/Protocol/General/ILanguageProtocolInitializeHandler.cs @@ -11,8 +11,10 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.General /// /// InitializeError /// - [Serial, Method(GeneralNames.Initialize, Direction.ClientToServer)] - [GenerateHandlerMethods(typeof(ILanguageServerRegistry), MethodName = "OnLanguageProtocolInitialize"), GenerateRequestMethods(typeof(ILanguageClient), MethodName = "RequestLanguageProtocolInitialize")] + [Serial] + [Method(GeneralNames.Initialize, Direction.ClientToServer)] + [GenerateHandlerMethods(typeof(ILanguageServerRegistry), MethodName = "OnLanguageProtocolInitialize")] + [GenerateRequestMethods(typeof(ILanguageClient), MethodName = "RequestLanguageProtocolInitialize")] public interface ILanguageProtocolInitializeHandler : IJsonRpcRequestHandler { } diff --git a/src/Protocol/General/ILanguageProtocolInitializedHandler.cs b/src/Protocol/General/ILanguageProtocolInitializedHandler.cs index be207a051..245f37040 100644 --- a/src/Protocol/General/ILanguageProtocolInitializedHandler.cs +++ b/src/Protocol/General/ILanguageProtocolInitializedHandler.cs @@ -9,9 +9,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.General { - [Serial, Method(GeneralNames.Initialized, Direction.ClientToServer)] - [GenerateHandlerMethods(typeof(ILanguageServerRegistry), MethodName = "OnLanguageProtocolInitialized"), GenerateRequestMethods(typeof(ILanguageClient), MethodName = "SendLanguageProtocolInitialized")] - public interface ILanguageProtocolInitializedHandler : IJsonRpcNotificationHandler { } + [Serial] + [Method(GeneralNames.Initialized, Direction.ClientToServer)] + [GenerateHandlerMethods(typeof(ILanguageServerRegistry), MethodName = "OnLanguageProtocolInitialized")] + [GenerateRequestMethods(typeof(ILanguageClient), MethodName = "SendLanguageProtocolInitialized")] + public interface ILanguageProtocolInitializedHandler : IJsonRpcNotificationHandler + { + } public abstract class LanguageProtocolInitializedHandler : ILanguageProtocolInitializedHandler { diff --git a/src/Protocol/General/IShutdownHandler.cs b/src/Protocol/General/IShutdownHandler.cs index 73fad267e..d19ae984b 100644 --- a/src/Protocol/General/IShutdownHandler.cs +++ b/src/Protocol/General/IShutdownHandler.cs @@ -8,8 +8,10 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.General { - [Serial, Method(GeneralNames.Shutdown, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + [Serial] + [Method(GeneralNames.Shutdown, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface IShutdownHandler : IJsonRpcRequestHandler { } @@ -27,9 +29,7 @@ public virtual async Task Handle(ShutdownParams request, CancellationToken public static partial class ShutdownExtensions { - public static Task RequestShutdown(this ILanguageClient mediator, CancellationToken cancellationToken = default) - { - return mediator.SendRequest(ShutdownParams.Instance, cancellationToken); - } + public static Task RequestShutdown(this ILanguageClient mediator, CancellationToken cancellationToken = default) => + mediator.SendRequest(ShutdownParams.Instance, cancellationToken); } } diff --git a/src/Protocol/ILanguageClientWorkspaceFoldersManager.cs b/src/Protocol/ILanguageClientWorkspaceFoldersManager.cs index 5fc6af620..e7e9a509f 100644 --- a/src/Protocol/ILanguageClientWorkspaceFoldersManager.cs +++ b/src/Protocol/ILanguageClientWorkspaceFoldersManager.cs @@ -5,7 +5,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol { - public interface ILanguageClientWorkspaceFoldersManager: IWorkspaceFoldersHandler + public interface ILanguageClientWorkspaceFoldersManager : IWorkspaceFoldersHandler { void Add(DocumentUri uri, string name); void Add(WorkspaceFolder workspaceFolder, params WorkspaceFolder[] workspaceFolders); diff --git a/src/Protocol/ILanguageProtocolSettings.cs b/src/Protocol/ILanguageProtocolSettings.cs index 14759df2d..54b3b2dd9 100644 --- a/src/Protocol/ILanguageProtocolSettings.cs +++ b/src/Protocol/ILanguageProtocolSettings.cs @@ -4,8 +4,8 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol { public interface ILanguageProtocolSettings { - InitializeParams ClientSettings { get; } + InitializeParams ClientSettings { get; } - InitializeResult ServerSettings { get; } + InitializeResult ServerSettings { get; } } -} \ No newline at end of file +} diff --git a/src/Protocol/IProgressHandler.cs b/src/Protocol/IProgressHandler.cs index a8ec3832e..30bc225d4 100644 --- a/src/Protocol/IProgressHandler.cs +++ b/src/Protocol/IProgressHandler.cs @@ -12,8 +12,10 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol { - [Parallel, Method(GeneralNames.Progress, Direction.Bidirectional)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IGeneralLanguageClient), typeof(ILanguageClient), typeof(IGeneralLanguageServer), typeof(ILanguageServer))] + [Parallel] + [Method(GeneralNames.Progress, Direction.Bidirectional)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IGeneralLanguageClient), typeof(ILanguageClient), typeof(IGeneralLanguageServer), typeof(ILanguageServer))] public interface IProgressHandler : IJsonRpcNotificationHandler { } @@ -25,7 +27,9 @@ public abstract class ProgressHandler : IProgressHandler public static partial class ProgressExtensions { - public static IRequestProgressObservable RequestProgress(this ILanguageProtocolProxy requestRouter, IPartialItemRequest @params, Func factory, CancellationToken cancellationToken = default) + public static IRequestProgressObservable RequestProgress( + this ILanguageProtocolProxy requestRouter, IPartialItemRequest @params, Func factory, CancellationToken cancellationToken = default + ) { var resultToken = new ProgressToken(Guid.NewGuid().ToString()); @params.PartialResultToken = resultToken; @@ -33,7 +37,10 @@ public static IRequestProgressObservable RequestProgress, TResponse> RequestProgress(this ILanguageProtocolProxy requestRouter, IPartialItemsRequest @params, Func, TResponse> factory, CancellationToken cancellationToken = default) + public static IRequestProgressObservable, TResponse> RequestProgress( + this ILanguageProtocolProxy requestRouter, IPartialItemsRequest @params, Func, TResponse> factory, + CancellationToken cancellationToken = default + ) where TResponse : IEnumerable { var resultToken = new ProgressToken(Guid.NewGuid().ToString()); diff --git a/src/Protocol/IRegistration.cs b/src/Protocol/IRegistration.cs index 3d67a6a1a..7f2eb9a67 100644 --- a/src/Protocol/IRegistration.cs +++ b/src/Protocol/IRegistration.cs @@ -11,6 +11,5 @@ public interface IRegistration /// public interface IDoesNotParticipateInRegistration { - } } diff --git a/src/Protocol/ISupports.cs b/src/Protocol/ISupports.cs index 8057f8b8d..ca9478a56 100644 --- a/src/Protocol/ISupports.cs +++ b/src/Protocol/ISupports.cs @@ -1,5 +1,4 @@ using System; -using OmniSharp.Extensions.LanguageServer.Protocol.Client; namespace OmniSharp.Extensions.LanguageServer.Protocol { diff --git a/src/Protocol/LanguageProtocolDelegatingHandlers.cs b/src/Protocol/LanguageProtocolDelegatingHandlers.cs index 0f9189447..30c3c70c5 100644 --- a/src/Protocol/LanguageProtocolDelegatingHandlers.cs +++ b/src/Protocol/LanguageProtocolDelegatingHandlers.cs @@ -224,7 +224,7 @@ public RequestRegistration(Func handler, TRegistrationOptions reg { } - public RequestRegistration(Func handler, TRegistrationOptions registrationOptions): + public RequestRegistration(Func handler, TRegistrationOptions registrationOptions) : this(Guid.Empty, handler, registrationOptions) { } @@ -268,7 +268,7 @@ public RequestCapability(Func> handler) : { } - public RequestCapability(Func> handler): + public RequestCapability(Func> handler) : this(Guid.Empty, handler) { } @@ -308,7 +308,7 @@ public RequestCapability(Func handler) : { } - public RequestCapability(Func handler): + public RequestCapability(Func handler) : this(Guid.Empty, handler) { } @@ -351,22 +351,33 @@ public sealed class PartialResult _id; - public PartialResult(Action, TCapability> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func factory) : + public PartialResult( + Action, TCapability> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func factory + ) : this(Guid.Empty, (p, o, c, ct) => handler(p, o, c), registrationOptions, progressManager, factory) { } - public PartialResult(Action, TCapability, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func factory): + public PartialResult( + Action, TCapability, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, + Func factory + ) : this(Guid.Empty, handler, registrationOptions, progressManager, factory) { } - public PartialResult(Guid id, Action, TCapability> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func factory) : + public PartialResult( + Guid id, Action, TCapability> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, + Func factory + ) : this(id, (p, o, c, ct) => handler(p, o, c), registrationOptions, progressManager, factory) { } - public PartialResult(Guid id, Action, TCapability, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func factory) + public PartialResult( + Guid id, Action, TCapability, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, + Func factory + ) { _id = id; _handler = handler; @@ -375,8 +386,10 @@ public PartialResult(Guid id, Action, TCapability, Cance _factory = factory; } - async Task IRequestHandler.Handle(TItem request, - CancellationToken cancellationToken) + async Task IRequestHandler.Handle( + TItem request, + CancellationToken cancellationToken + ) { var observer = _progressManager.For(request, cancellationToken); if (observer != ProgressObserver.Noop) @@ -410,22 +423,32 @@ public sealed class PartialResult : private readonly Guid _id; Guid ICanBeIdentifiedHandler.Id => _id; - public PartialResult(Action> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func factory) : + public PartialResult( + Action> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func factory + ) : this(Guid.Empty, (p, o, ct) => handler(p, o), registrationOptions, progressManager, factory) { } - public PartialResult(Action, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func factory): + public PartialResult( + Action, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, + Func factory + ) : this(Guid.Empty, handler, registrationOptions, progressManager, factory) { } - public PartialResult(Guid id, Action> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func factory) : + public PartialResult( + Guid id, Action> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func factory + ) : this(id, (p, o, ct) => handler(p, o), registrationOptions, progressManager, factory) { } - public PartialResult(Guid id, Action, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func factory) + public PartialResult( + Guid id, Action, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, + Func factory + ) { _id = id; _handler = handler; @@ -472,7 +495,9 @@ public PartialResultCapability(Action> hand { } - public PartialResultCapability(Action, CancellationToken> handler, IProgressManager progressManager, Func factory): + public PartialResultCapability( + Action, CancellationToken> handler, IProgressManager progressManager, Func factory + ) : this(Guid.Empty, handler, progressManager, factory) { } @@ -482,7 +507,9 @@ public PartialResultCapability(Guid id, Action, CancellationToken> handler, IProgressManager progressManager, Func factory) + public PartialResultCapability( + Guid id, Action, CancellationToken> handler, IProgressManager progressManager, Func factory + ) { _id = id; _handler = handler; @@ -525,8 +552,8 @@ public PartialResult(Action> handler, IProgressManager p { } - public PartialResult(Action, CancellationToken> handler, IProgressManager progressManager, Func factory): - this(Guid.Empty, handler, progressManager,factory) + public PartialResult(Action, CancellationToken> handler, IProgressManager progressManager, Func factory) : + this(Guid.Empty, handler, progressManager, factory) { _handler = handler; _progressManager = progressManager; @@ -579,22 +606,34 @@ public sealed class PartialResults _id; - public PartialResults(Action>, TCapability> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func, TResponse> factory) : + public PartialResults( + Action>, TCapability> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, + Func, TResponse> factory + ) : this(Guid.Empty, (p, o, c, ct) => handler(p, o, c), registrationOptions, progressManager, factory) { } - public PartialResults(Action>, TCapability, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func, TResponse> factory): + public PartialResults( + Action>, TCapability, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, + Func, TResponse> factory + ) : this(Guid.Empty, handler, registrationOptions, progressManager, factory) { } - public PartialResults(Guid id, Action>, TCapability> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func, TResponse> factory) : + public PartialResults( + Guid id, Action>, TCapability> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, + Func, TResponse> factory + ) : this(id, (p, o, c, ct) => handler(p, o, c), registrationOptions, progressManager, factory) { } - public PartialResults(Guid id, Action>, TCapability, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func, TResponse> factory) + public PartialResults( + Guid id, Action>, TCapability, CancellationToken> handler, TRegistrationOptions registrationOptions, + IProgressManager progressManager, Func, TResponse> factory + ) { _id = id; _handler = handler; @@ -614,11 +653,13 @@ async Task IRequestHandler.Handle(TParams request } var subject = new Subject>(); - var task = subject.Aggregate(new List(), (acc, items) => { - acc.AddRange(items); - return acc; - }) - .ToTask(cancellationToken); + var task = subject.Aggregate( + new List(), (acc, items) => { + acc.AddRange(items); + return acc; + } + ) + .ToTask(cancellationToken); _handler(request, subject, _capability, cancellationToken); var result = _factory(await task); return result; @@ -643,22 +684,34 @@ public sealed class PartialResults _id; - public PartialResults(Action>> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func, TResponse> factory) : + public PartialResults( + Action>> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, + Func, TResponse> factory + ) : this(Guid.Empty, (p, o, ct) => handler(p, o), registrationOptions, progressManager, factory) { } - public PartialResults(Action>, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func, TResponse> factory): + public PartialResults( + Action>, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, + Func, TResponse> factory + ) : this(Guid.Empty, handler, registrationOptions, progressManager, factory) { } - public PartialResults(Guid id, Action>> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func, TResponse> factory) : + public PartialResults( + Guid id, Action>> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, + Func, TResponse> factory + ) : this(id, (p, o, ct) => handler(p, o), registrationOptions, progressManager, factory) { } - public PartialResults(Guid id, Action>, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, Func, TResponse> factory) + public PartialResults( + Guid id, Action>, CancellationToken> handler, TRegistrationOptions registrationOptions, IProgressManager progressManager, + Func, TResponse> factory + ) { _id = id; _handler = handler; @@ -678,11 +731,13 @@ async Task IRequestHandler.Handle(TParams request } var subject = new Subject>(); - var task = subject.Aggregate(new List(), (acc, items) => { - acc.AddRange(items); - return acc; - }) - .ToTask(cancellationToken); + var task = subject.Aggregate( + new List(), (acc, items) => { + acc.AddRange(items); + return acc; + } + ) + .ToTask(cancellationToken); _handler(request, subject, cancellationToken); var result = _factory(await task); return result; @@ -705,22 +760,32 @@ public sealed class PartialResultsCapability _id; - public PartialResultsCapability(Action>> handler, IProgressManager progressManager, Func, TResponse> factory) : + public PartialResultsCapability( + Action>> handler, IProgressManager progressManager, Func, TResponse> factory + ) : this(Guid.Empty, (p, c, o, ct) => handler(p, c, o), progressManager, factory) { } - public PartialResultsCapability(Action>, CancellationToken> handler, IProgressManager progressManager, Func, TResponse> factory): + public PartialResultsCapability( + Action>, CancellationToken> handler, IProgressManager progressManager, + Func, TResponse> factory + ) : this(Guid.Empty, handler, progressManager, factory) { } - public PartialResultsCapability(Guid id, Action>> handler, IProgressManager progressManager, Func, TResponse> factory) : + public PartialResultsCapability( + Guid id, Action>> handler, IProgressManager progressManager, Func, TResponse> factory + ) : this(id, (p, c, o, ct) => handler(p, c, o), progressManager, factory) { } - public PartialResultsCapability(Guid id, Action>, CancellationToken> handler, IProgressManager progressManager, Func, TResponse> factory) + public PartialResultsCapability( + Guid id, Action>, CancellationToken> handler, IProgressManager progressManager, + Func, TResponse> factory + ) { _id = id; _handler = handler; @@ -739,11 +804,13 @@ async Task IRequestHandler.Handle(TParams request } var subject = new Subject>(); - var task = subject.Aggregate(new List(), (acc, items) => { - acc.AddRange(items); - return acc; - }) - .ToTask(cancellationToken); + var task = subject.Aggregate( + new List(), (acc, items) => { + acc.AddRange(items); + return acc; + } + ) + .ToTask(cancellationToken); _handler(request, _capability, subject, cancellationToken); var result = _factory(await task); return result; @@ -769,7 +836,9 @@ public PartialResults(Action>> handler, IP { } - public PartialResults(Action>, CancellationToken> handler, IProgressManager progressManager, Func, TResponse> factory): + public PartialResults( + Action>, CancellationToken> handler, IProgressManager progressManager, Func, TResponse> factory + ) : this(Guid.Empty, handler, progressManager, factory) { _handler = handler; @@ -782,7 +851,9 @@ public PartialResults(Guid id, Action>> ha { } - public PartialResults(Guid id, Action>, CancellationToken> handler, IProgressManager progressManager, Func, TResponse> factory) + public PartialResults( + Guid id, Action>, CancellationToken> handler, IProgressManager progressManager, Func, TResponse> factory + ) { _id = id; _handler = handler; @@ -801,11 +872,13 @@ async Task IRequestHandler.Handle(TParams request } var subject = new Subject>(); - var task = subject.Aggregate(new List(), (acc, items) => { - acc.AddRange(items); - return acc; - }) - .ToTask(cancellationToken); + var task = subject.Aggregate( + new List(), (acc, items) => { + acc.AddRange(items); + return acc; + } + ) + .ToTask(cancellationToken); _handler(request, subject, cancellationToken); var result = _factory(await task); return result; @@ -827,12 +900,22 @@ public sealed class Notification : Guid ICanBeIdentifiedHandler.Id => _id; public Notification(Action handler, TRegistrationOptions registrationOptions) : - this(Guid.Empty, (request, capability, ct) => { handler(request, capability); return Task.CompletedTask; }, registrationOptions) + this( + Guid.Empty, (request, capability, ct) => { + handler(request, capability); + return Task.CompletedTask; + }, registrationOptions + ) { } public Notification(Action handler, TRegistrationOptions registrationOptions) : - this(Guid.Empty, (request, c, ct) => { handler(request, c, ct); return Task.CompletedTask; }, registrationOptions) + this( + Guid.Empty, (request, c, ct) => { + handler(request, c, ct); + return Task.CompletedTask; + }, registrationOptions + ) { } @@ -841,18 +924,28 @@ public Notification(Func handler, TRegistrationOptio { } - public Notification(Func handler, TRegistrationOptions registrationOptions): + public Notification(Func handler, TRegistrationOptions registrationOptions) : this(Guid.Empty, handler, registrationOptions) { } public Notification(Guid id, Action handler, TRegistrationOptions registrationOptions) : - this(id, (request, capability, ct) => { handler(request, capability); return Task.CompletedTask; }, registrationOptions) + this( + id, (request, capability, ct) => { + handler(request, capability); + return Task.CompletedTask; + }, registrationOptions + ) { } - public Notification( Guid id, Action handler, TRegistrationOptions registrationOptions) : - this(id, (request, c, ct) => { handler(request, c, ct); return Task.CompletedTask; }, registrationOptions) + public Notification(Guid id, Action handler, TRegistrationOptions registrationOptions) : + this( + id, (request, c, ct) => { + handler(request, c, ct); + return Task.CompletedTask; + }, registrationOptions + ) { } @@ -891,12 +984,22 @@ public sealed class Notification : Guid ICanBeIdentifiedHandler.Id => _id; public Notification(Action handler, TRegistrationOptions registrationOptions) : - this(Guid.Empty, (request, ct) => { handler(request); return Task.CompletedTask; }, registrationOptions) + this( + Guid.Empty, (request, ct) => { + handler(request); + return Task.CompletedTask; + }, registrationOptions + ) { } public Notification(Action handler, TRegistrationOptions registrationOptions) : - this(Guid.Empty, (request, ct) => { handler(request, ct); return Task.CompletedTask; }, registrationOptions) + this( + Guid.Empty, (request, ct) => { + handler(request, ct); + return Task.CompletedTask; + }, registrationOptions + ) { } @@ -905,18 +1008,28 @@ public Notification(Func handler, TRegistrationOptions registrati { } - public Notification(Func handler, TRegistrationOptions registrationOptions): + public Notification(Func handler, TRegistrationOptions registrationOptions) : this(Guid.Empty, handler, registrationOptions) { } public Notification(Guid id, Action handler, TRegistrationOptions registrationOptions) : - this(id,(request, ct) => { handler(request); return Task.CompletedTask; }, registrationOptions) + this( + id, (request, ct) => { + handler(request); + return Task.CompletedTask; + }, registrationOptions + ) { } public Notification(Guid id, Action handler, TRegistrationOptions registrationOptions) : - this(id, (request, ct) => { handler(request, ct); return Task.CompletedTask; }, registrationOptions) + this( + id, (request, ct) => { + handler(request, ct); + return Task.CompletedTask; + }, registrationOptions + ) { } @@ -953,7 +1066,12 @@ public sealed class NotificationCapability : Guid ICanBeIdentifiedHandler.Id => _id; public NotificationCapability(Action handler) : - this(Guid.Empty, (request, capability, ct) => { handler(request, capability); return Task.CompletedTask; }) + this( + Guid.Empty, (request, capability, ct) => { + handler(request, capability); + return Task.CompletedTask; + } + ) { } @@ -968,7 +1086,12 @@ public NotificationCapability(Func handler) : - this(id, (request, capability, ct) => { handler(request, capability); return Task.CompletedTask; }) + this( + id, (request, capability, ct) => { + handler(request, capability); + return Task.CompletedTask; + } + ) { } diff --git a/src/Protocol/LanguageProtocolEventingHelper.cs b/src/Protocol/LanguageProtocolEventingHelper.cs index 66da31ec3..0a3898eb3 100644 --- a/src/Protocol/LanguageProtocolEventingHelper.cs +++ b/src/Protocol/LanguageProtocolEventingHelper.cs @@ -20,21 +20,21 @@ CancellationToken cancellationToken ) { var events = delegates.Select(z => Observable.FromAsync(ct => executeDelegate(z, ct))) - .Concat(handlers.Select(z => Observable.FromAsync(ct => executeHandler(z, ct)))) - .ToObservable(); + .Concat(handlers.Select(z => Observable.FromAsync(ct => executeHandler(z, ct)))) + .ToObservable(); if (concurrency.HasValue) { return events.Merge(concurrency.Value) - .LastOrDefaultAsync() - .ToTask(cancellationToken); + .LastOrDefaultAsync() + .ToTask(cancellationToken); } return events - .Merge() - .LastOrDefaultAsync() - .ToTask(cancellationToken); + .Merge() + .LastOrDefaultAsync() + .ToTask(cancellationToken); } } } diff --git a/src/Protocol/LanguageProtocolProxy.cs b/src/Protocol/LanguageProtocolProxy.cs index 19a551e1d..6c3c028a1 100644 --- a/src/Protocol/LanguageProtocolProxy.cs +++ b/src/Protocol/LanguageProtocolProxy.cs @@ -15,7 +15,9 @@ internal abstract class LanguageProtocolProxy : ILanguageProtocolProxy private readonly IServiceProvider _serviceProvider; private readonly ILanguageProtocolSettings _languageProtocolSettings; - public LanguageProtocolProxy(IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, ILanguageProtocolSettings languageProtocolSettings) + public LanguageProtocolProxy( + IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, ILanguageProtocolSettings languageProtocolSettings + ) { ProgressManager = progressManager; _responseRouter = requestRouter; diff --git a/src/Protocol/LanguageProtocolRpcOptionsBase.cs b/src/Protocol/LanguageProtocolRpcOptionsBase.cs index 9a1c27990..986065112 100644 --- a/src/Protocol/LanguageProtocolRpcOptionsBase.cs +++ b/src/Protocol/LanguageProtocolRpcOptionsBase.cs @@ -5,15 +5,14 @@ using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; +using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; +using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; namespace OmniSharp.Extensions.LanguageServer.Protocol { public abstract class LanguageProtocolRpcOptionsBase : JsonRpcServerOptionsBase where T : IJsonRpcHandlerRegistry { - public LanguageProtocolRpcOptionsBase() - { - Services.AddLogging(builder => LoggingBuilderAction?.Invoke(builder)); - } + public LanguageProtocolRpcOptionsBase() => Services.AddLogging(builder => LoggingBuilderAction?.Invoke(builder)); public T AddTextDocumentIdentifier(params ITextDocumentIdentifier[] handlers) { @@ -31,7 +30,7 @@ public T AddTextDocumentIdentifier() where TI : ITextDocumentIdentifier return (T) (object) this; } - public Protocol.Serialization.ISerializer Serializer { get; set; } = new Protocol.Serialization.Serializer(ClientVersion.Lsp3); + public ISerializer Serializer { get; set; } = new Serializer(ClientVersion.Lsp3); internal bool AddDefaultLoggingProvider { get; set; } internal Action LoggingBuilderAction { get; set; } = _ => { }; internal Action ConfigurationBuilderAction { get; set; } = _ => { }; diff --git a/src/Protocol/LanguageProtocolSettingsBag.cs b/src/Protocol/LanguageProtocolSettingsBag.cs index 93538c1a5..0841556d1 100644 --- a/src/Protocol/LanguageProtocolSettingsBag.cs +++ b/src/Protocol/LanguageProtocolSettingsBag.cs @@ -2,7 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol { - class LanguageProtocolSettingsBag : ILanguageProtocolSettings + internal class LanguageProtocolSettingsBag : ILanguageProtocolSettings { public InitializeParams ClientSettings { get; internal set; } diff --git a/src/Protocol/Minimatch/Minimatcher.cs b/src/Protocol/Minimatch/Minimatcher.cs index 3943d0032..56c5a3871 100644 --- a/src/Protocol/Minimatch/Minimatcher.cs +++ b/src/Protocol/Minimatch/Minimatcher.cs @@ -21,6 +21,7 @@ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + using System; using System.Collections.Generic; using System.Linq; @@ -42,6 +43,7 @@ public static Func CreateFilter(string pattern, Options options = var m = new Minimatcher(pattern, options); return m.IsMatch; } + ///Tests a single input against a pattern. ///This function reparses this input on each invocation. For performance, avoid this function and reuse a Minimatcher instance instead. public static bool Check(string input, string pattern, Options options = null) @@ -73,18 +75,15 @@ public static IEnumerable Filter(IEnumerable list, string patter } ///Compiles a pattern into a single regular expression. - public static Regex CreateRegex(string pattern, Options options = null) - { - return new Minimatcher(pattern, options).MakeRegex(); - } + public static Regex CreateRegex(string pattern, Options options = null) => new Minimatcher(pattern, options).MakeRegex(); - readonly Options options; + private readonly Options options; - string pattern; - bool negate = false; - bool comment = false; - bool empty = false; + private string pattern; + private bool negate; + private bool comment; + private bool empty; ///Creates a new Minimatcher instance, parsing the pattern into a regex. public Minimatcher(string pattern, Options options = null) @@ -95,11 +94,11 @@ public Minimatcher(string pattern, Options options = null) if (this.options.AllowWindowsPaths) this.pattern = this.pattern.Replace('\\', '/'); - this.Make(); + Make(); } ///Checks whether a given string matches this pattern. - public bool IsMatch(string input) { return Match(input, false); } + public bool IsMatch(string input) => Match(input, false); ///Filters a list of inputs against this pattern. public IEnumerable Filter(IEnumerable list) @@ -111,69 +110,73 @@ public IEnumerable Filter(IEnumerable list) } - Regex regexp; - bool isError; + private Regex regexp; + private bool isError; - IEnumerable globSet; - IEnumerable> set; - IEnumerable> globParts; + private IEnumerable globSet; + private IEnumerable> set; + private IEnumerable> globParts; // any single thing other than / // don't need to escape / when using new RegExp() - const string qmark = "[^/]" + private const string qmark = "[^/]" - // * => any number of characters - , star = qmark + "*?" + // * => any number of characters + , + star = qmark + "*?" - // ** when dots are allowed. Anything goes, except .. and . - // not (^ or / followed by one or two dots followed by $ or /), - // followed by anything, any number of times. - , twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?" + // ** when dots are allowed. Anything goes, except .. and . + // not (^ or / followed by one or two dots followed by $ or /), + // followed by anything, any number of times. + , + twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?" - // not a ^ or / followed by a dot, - // followed by anything, any number of times. - , twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?"; + // not a ^ or / followed by a dot, + // followed by anything, any number of times. + , + twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?"; // characters that need to be escaped in RegExp. - static readonly HashSet reSpecials = new HashSet("().*{}+?[]^$\\!".ToCharArray()); - static readonly Regex slashSplit = new Regex("/+"); + private static readonly HashSet reSpecials = new HashSet("().*{}+?[]^$\\!".ToCharArray()); + private static readonly Regex slashSplit = new Regex("/+"); - void Make() + private void Make() { // empty patterns and comments match nothing. if (!options.NoComment && !string.IsNullOrEmpty(pattern) && pattern[0] == '#') { - this.comment = true; + comment = true; return; } + if (string.IsNullOrEmpty(pattern)) { - this.empty = true; + empty = true; return; } // step 1: figure out negation, etc. - this.ParseNegate(); + ParseNegate(); // step 2: expand braces - this.globSet = BraceExpand(pattern, options); + globSet = BraceExpand(pattern, options); // step 3: now we have a set, so turn each one into a series of path-portion // matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters - this.globParts = globSet.Select(s => slashSplit.Split(s)).ToList(); + globParts = globSet.Select(s => slashSplit.Split(s)).ToList(); // glob --> regexps - this.set = globParts.Select(g => g.Select(t => this.Parse(t, false))) - .Where(g => !g.Contains(null)) - .Select(g => g.Select(t => t.Item1)) - .ToList(); + set = globParts.Select(g => g.Select(t => Parse(t, false))) + .Where(g => !g.Contains(null)) + .Select(g => g.Select(t => t.Item1)) + .ToList(); } - void ParseNegate() + private void ParseNegate() { var negateOffset = 0; @@ -185,11 +188,13 @@ void ParseNegate() negateOffset++; } - if (negateOffset > 0) this.pattern = pattern.Substring(negateOffset); + if (negateOffset > 0) pattern = pattern.Substring(negateOffset); } - static readonly Regex hasBraces = new Regex(@"\{.*\}"); - static readonly Regex numericSet = new Regex(@"^\{(-?[0-9]+)\.\.(-?[0-9]+)\}"); + private static readonly Regex hasBraces = new Regex(@"\{.*\}"); + + private static readonly Regex numericSet = new Regex(@"^\{(-?[0-9]+)\.\.(-?[0-9]+)\}"); + // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac @@ -208,7 +213,8 @@ public static IEnumerable BraceExpand(string pattern, Options options) // shortcut. no need to expand. return new[] { pattern }; } - bool escaping = false; + + var escaping = false; int i; // examples and comments refer to this crazy pattern: // a{b,c{d,e},{f,g}h}x{y,z} @@ -272,14 +278,15 @@ public static IEnumerable BraceExpand(string pattern, Options options) end = int.Parse(numset.Groups[2].Value), inc = start > end ? -1 : 1; var retVal = new List(); - for (var w = start; w != (end + inc); w += inc) + for (var w = start; w != end + inc; w += inc) { // append all the suffixes for (var ii = 0; ii < suf.Count; ii++) { - retVal.Add(w.ToString() + suf[ii]); + retVal.Add(w + suf[ii]); } } + return retVal; } @@ -290,9 +297,9 @@ public static IEnumerable BraceExpand(string pattern, Options options) // interpreted as braceExpand("\\" + pattern) so that // the leading \{ will be interpreted literally. i = 1; // skip the \{ - int depth = 1; + var depth = 1; var set = new List(); - string member = ""; + var member = ""; for (i = 1; i < pattern.Length && depth > 0; i++) { @@ -343,6 +350,7 @@ public static IEnumerable BraceExpand(string pattern, Options options) { member += c; } + continue; default: @@ -388,51 +396,53 @@ abstract class ParseItem public string Source { get; protected set; } public static readonly ParseItem Empty = new LiteralItem(""); - public static ParseItem Literal(string source) { return new LiteralItem(source); } + public static ParseItem Literal(string source) => new LiteralItem(source); public abstract string RegexSource(Options options); public abstract bool Match(string input, Options options); } - class LiteralItem : ParseItem + + private class LiteralItem : ParseItem { - public LiteralItem(string source) { Source = source; } - public override string RegexSource(Options options) { return Regex.Escape(Source); } - public override bool Match(string input, Options options) - { - return input.Equals(Source, options.NoCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); - } + public LiteralItem(string source) => Source = source; + public override string RegexSource(Options options) => Regex.Escape(Source); + + public override bool Match(string input, Options options) => input.Equals(Source, options.NoCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } - class MagicItem : ParseItem + + private class MagicItem : ParseItem { public MagicItem(string source, Options options) { Source = source; regex = new Lazy(() => new Regex("^" + source + "$", options.RegexOptions)); } - readonly Lazy regex; - public override string RegexSource(Options options) { return Source; } - public override bool Match(string input, Options options) - { - return regex.Value.IsMatch(input); - } + private readonly Lazy regex; + + public override string RegexSource(Options options) => Source; + + public override bool Match(string input, Options options) => regex.Value.IsMatch(input); } - class GlobStar : ParseItem - { - private GlobStar() { } - public static readonly ParseItem Instance = new GlobStar(); - public override string RegexSource(Options options) + private class GlobStar : ParseItem + { + private GlobStar() { - return options.NoGlobStar ? star - : options.Dot ? twoStarDot - : twoStarNoDot; } - public override bool Match(string input, Options options) { throw new NotSupportedException(); } + public static readonly ParseItem Instance = new GlobStar(); + + public override string RegexSource(Options options) => + options.NoGlobStar ? star + : options.Dot ? twoStarDot + : twoStarNoDot; + + public override bool Match(string input, Options options) => throw new NotSupportedException(); } - static readonly Regex escapeCheck = new Regex(@"((?:\\{2})*)(\\?)\|"); + private static readonly Regex escapeCheck = new Regex(@"((?:\\{2})*)(\\?)\|"); + // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full @@ -450,7 +460,7 @@ private Tuple Parse(string pattern, bool isSub) if (!options.NoGlobStar && pattern == "**") return Tuple.Create(GlobStar.Instance, false); if (pattern == "") return Tuple.Create(ParseItem.Empty, false); - string re = ""; + var re = ""; bool hasMagic = options.NoCase, escaping = false, inClass = false; // ? => one single character var patternListStack = new Stack(); @@ -460,10 +470,10 @@ private Tuple Parse(string pattern, bool isSub) int reClassStart = -1, classStart = -1; // . and .. never match anything that doesn't start with ., // even when options.dot is set. - string patternStart = pattern[0] == '.' ? "" // anything - // not (start or / followed by . or .. followed by / or end) + var patternStart = pattern[0] == '.' ? "" // anything + // not (start or / followed by . or .. followed by / or end) : options.Dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" - : "(?!\\.)"; + : "(?!\\.)"; Action clearStatechar = () => { if (statechar != null) @@ -484,6 +494,7 @@ private Tuple Parse(string pattern, bool isSub) re += "\\" + statechar; break; } + statechar = null; } }; @@ -585,9 +596,12 @@ private Tuple Parse(string pattern, bool isSub) break; case '?': case '+': - case '*': re += plType; break; + case '*': + re += plType; + break; case '@': break; // the default anyway } + continue; case '|': @@ -645,7 +659,7 @@ private Tuple Parse(string pattern, bool isSub) // no need escaping = false; } - else if (reSpecials.Contains(c) && !(c == '^' && inClass)) + else if (reSpecials.Contains(c) && !( c == '^' && inClass )) { re += "\\"; } @@ -664,8 +678,8 @@ private Tuple Parse(string pattern, bool isSub) // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is - string cs = pattern.Substring(classStart + 1); - var sp = this.Parse(cs, true); + var cs = pattern.Substring(classStart + 1); + var sp = Parse(cs, true); re = re.Substring(0, reClassStart) + "\\[" + sp.Item1.Source; hasMagic = hasMagic || sp.Item2; } @@ -681,29 +695,31 @@ private Tuple Parse(string pattern, bool isSub) var pl = patternListStack.Pop(); var tail = re.Substring(pl.ReStart + 3); // maybe some even number of \, then maybe 1 \, followed by a | - tail = escapeCheck.Replace(tail, m => { - string escape = m.Groups[2].Value; - // the | isn't already escaped, so escape it. - if (string.IsNullOrEmpty(escape)) escape = "\\"; - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return m.Groups[1].Value + m.Groups[1].Value + escape + "|"; - }); + tail = escapeCheck.Replace( + tail, m => { + var escape = m.Groups[2].Value; + // the | isn't already escaped, so escape it. + if (string.IsNullOrEmpty(escape)) escape = "\\"; + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return m.Groups[1].Value + m.Groups[1].Value + escape + "|"; + } + ); // console.error("tail=%j\n %s", tail, tail) var t = pl.Type == '*' ? star : pl.Type == '?' ? qmark - : "\\" + pl.Type; + : "\\" + pl.Type; hasMagic = true; re = re.Remove(pl.ReStart) - + t + "\\(" - + tail; + + t + "\\(" + + tail; } // handle trailing things that only matter at the very end. @@ -721,7 +737,9 @@ private Tuple Parse(string pattern, bool isSub) { case '.': case '[': - case '(': addPatternStart = true; break; + case '(': + addPatternStart = true; + break; } // if the re is not "" at this point, then we need to make sure @@ -744,13 +762,14 @@ private Tuple Parse(string pattern, bool isSub) { return Tuple.Create(ParseItem.Literal(GlobUnescape(pattern)), false); } + return new Tuple(new MagicItem(re, options), false); } - Regex MakeRegex() + private Regex MakeRegex() { - if (this.regexp != null || isError) return this.regexp; + if (regexp != null || isError) return regexp; // at this point, this.set is a 2d array of partial // pattern strings, or "**". @@ -760,27 +779,33 @@ Regex MakeRegex() // when you just want to work with a regex. if (comment || empty || !set.Any()) { - this.isError = true; + isError = true; return null; } - var re = string.Join("|", set.Select(pattern => - string.Join("\\/", pattern.Select(p => p.RegexSource(options)) - ))); + + var re = string.Join( + "|", set.Select( + pattern => + string.Join( + "\\/", pattern.Select(p => p.RegexSource(options)) + ) + ) + ); // must match entire pattern // ending in a * or ** will make it less strict. re = "^(?:" + re + ")$"; // can match anything, as long as it's not this. - if (this.negate) re = "^(?!" + re + ").*$"; + if (negate) re = "^(?!" + re + ").*$"; try { - return this.regexp = new Regex(re, options.RegexOptions); + return regexp = new Regex(re, options.RegexOptions); } catch { - this.isError = true; + isError = true; return null; } } @@ -791,8 +816,8 @@ private bool Match(string input, bool partial) // console.error("match", f, this.pattern) // short-circuit in the case of busted things. // comments, etc. - if (this.comment) return false; - if (this.empty) return input == ""; + if (comment) return false; + if (empty) return input == ""; if (input == "/" && partial) return true; @@ -815,19 +840,18 @@ private bool Match(string input, bool partial) foreach (var pattern in set) { - var hit = this.MatchOne(f, pattern.ToList(), partial); + var hit = MatchOne(f, pattern.ToList(), partial); if (hit) { if (options.FlipNegate) return true; - return !this.negate; + return !negate; } - } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.FlipNegate) return false; - return this.negate; + return negate; } // set partial to true to test if, for example, @@ -835,9 +859,8 @@ private bool Match(string input, bool partial) // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. - bool MatchOne(IList file, IList pattern, bool partial) + private bool MatchOne(IList file, IList pattern, bool partial) { - //if (options.debug) { // console.error("matchOne", // { "this": this @@ -854,14 +877,13 @@ bool MatchOne(IList file, IList pattern, bool partial) // console.error("matchOne", file.length, pattern.length) //} int fi = 0, pi = 0; - for (; (fi < file.Count) && (pi < pattern.Count); fi++, pi++) + for (; fi < file.Count && pi < pattern.Count; fi++, pi++) { - //if (options.debug) { // console.error("matchOne loop") //} - ParseItem p = pattern[pi]; - string f = file[fi]; + var p = pattern[pi]; + var f = file[fi]; //if (options.debug) { // console.error(pattern, p, f) @@ -912,8 +934,9 @@ bool MatchOne(IList file, IList pattern, bool partial) for (; fi < file.Count; fi++) { if (file[fi] == "." || file[fi] == ".." || - (!options.Dot && !string.IsNullOrEmpty(file[fi]) && file[fi][0] == '.')) return false; + !options.Dot && !string.IsNullOrEmpty(file[fi]) && file[fi][0] == '.') return false; } + return true; } @@ -928,31 +951,30 @@ bool MatchOne(IList file, IList pattern, bool partial) //} // XXX remove this slice. Just pass the start index. - if (this.MatchOne(file.Skip(fr).ToList(), pattern.Skip(pr).ToList(), partial)) + if (MatchOne(file.Skip(fr).ToList(), pattern.Skip(pr).ToList(), partial)) { //if (options.debug) // console.error('globstar found match!', fr, file.Count, swallowee) // found a match. return true; } - else - { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee == "." || swallowee == ".." || - (!options.Dot && swallowee[0] == '.')) - { - //if (options.debug) - // console.error("dot detected!", file, fr, pattern, pr) - break; - } - // ** swallows a segment, and continue. + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee == "." || swallowee == ".." || + !options.Dot && swallowee[0] == '.') + { //if (options.debug) - // console.error('globstar swallow a segment, and continue') - fr++; + // console.error("dot detected!", file, fr, pattern, pr) + break; } + + // ** swallows a segment, and continue. + //if (options.debug) + // console.error('globstar swallow a segment, and continue') + fr++; } + // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then @@ -962,6 +984,7 @@ bool MatchOne(IList file, IList pattern, bool partial) // console.error("\n>>> no match, partial?", file, fr, pattern, pr) if (fr == file.Count) return true; } + return false; } @@ -990,20 +1013,22 @@ bool MatchOne(IList file, IList pattern, bool partial) // an exact hit! return true; } - else if (fi == file.Count) + + if (fi == file.Count) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial; } - else if (pi == pattern.Count) + + if (pi == pattern.Count) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ - var emptyFileEnd = (fi == file.Count - 1) && (file[fi] == ""); + var emptyFileEnd = fi == file.Count - 1 && file[fi] == ""; return emptyFileEnd; } @@ -1013,10 +1038,7 @@ bool MatchOne(IList file, IList pattern, bool partial) // replace stuff like \* with * - static readonly Regex globUnescaper = new Regex(@"\\(.)"); - static string GlobUnescape(string s) - { - return globUnescaper.Replace(s, "$1"); - } + private static readonly Regex globUnescaper = new Regex(@"\\(.)"); + private static string GlobUnescape(string s) => globUnescaper.Replace(s, "$1"); } -} \ No newline at end of file +} diff --git a/src/Protocol/Minimatch/Options.cs b/src/Protocol/Minimatch/Options.cs index 30d0cd62a..0a4e4eaec 100644 --- a/src/Protocol/Minimatch/Options.cs +++ b/src/Protocol/Minimatch/Options.cs @@ -21,6 +21,7 @@ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + using System.Text.RegularExpressions; // ReSharper disable once CheckNamespace @@ -31,28 +32,41 @@ public class Options { ///Suppresses the behavior of treating # at the start of a pattern as a comment. public bool NoComment { get; set; } + ///Suppresses the behavior of treating a leading ! character as negation. public bool NoNegate { get; set; } + ///Do not expand {a,b} and {1.3} brace sets. public bool NoBrace { get; set; } + ///Disable ** matching against multiple folder names. public bool NoGlobStar { get; set; } + ///Ignores case differences when matching. public bool NoCase { get; set; } + ///Disable "extglob" style patterns like +(a|b). public bool NoExt { get; set; } - ///Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. - ///Note that by default, a/**/b will not match a/.d/b, unless dot is set. + + /// + /// Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. + /// Note that by default, a/**/b will not match a/.d/b, unless dot is set. + /// public bool Dot { get; set; } + ///When a match is not found by Match(), return a list containing the pattern itself. If not set, an empty list is returned if there are no matches. public bool NoNull { get; set; } + ///Returns from negate expressions the same as if they were not negated. (ie, true on a hit, false on a miss). public bool FlipNegate { get; set; } - ///If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, a?b would match the path /xyz/123/acb, but not /xyz/acb/123. + /// + /// If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, a?b would match the path + /// /xyz/123/acb, but not /xyz/acb/123. + /// public bool MatchBase { get; set; } - internal RegexOptions RegexOptions { get { return NoCase ? RegexOptions.IgnoreCase : RegexOptions.None; } } + internal RegexOptions RegexOptions => NoCase ? RegexOptions.IgnoreCase : RegexOptions.None; ///If true, backslahes in patterns and paths will be treated as forward slashes. This disables escape characters. public bool AllowWindowsPaths { get; set; } @@ -61,8 +75,8 @@ public class Options ///Ignores case differences when matching. This is the same as NoCase. public bool IgnoreCase { - get { return NoCase; } - set { NoCase = value; } + get => NoCase; + set => NoCase = value; } } -} \ No newline at end of file +} diff --git a/src/Protocol/Models/ApplyWorkspaceEditParams.cs b/src/Protocol/Models/ApplyWorkspaceEditParams.cs index 9698b9f22..26e7ec358 100644 --- a/src/Protocol/Models/ApplyWorkspaceEditParams.cs +++ b/src/Protocol/Models/ApplyWorkspaceEditParams.cs @@ -14,6 +14,7 @@ public class ApplyWorkspaceEditParams : IRequest /// [Optional] public string Label { get; set; } + /// /// The edits to apply. /// diff --git a/src/Protocol/Models/BooleanNumberString.cs b/src/Protocol/Models/BooleanNumberString.cs index ced9ddc9d..a05e062ab 100644 --- a/src/Protocol/Models/BooleanNumberString.cs +++ b/src/Protocol/Models/BooleanNumberString.cs @@ -16,12 +16,14 @@ public BooleanNumberString(long value) _string = null; _bool = null; } + public BooleanNumberString(string value) { _long = null; _string = value; _bool = null; } + public BooleanNumberString(bool value) { _long = null; @@ -30,11 +32,11 @@ public BooleanNumberString(bool value) } public bool IsLong => _long.HasValue; + public long Long { get => _long ?? 0; - set - { + set { String = null; _long = value; _bool = null; @@ -42,11 +44,11 @@ public long Long } public bool IsString => _string != null; + public string String { get => _string; - set - { + set { _string = value; _long = null; _bool = null; @@ -54,30 +56,21 @@ public string String } public bool IsBool => _bool.HasValue; + public bool Bool { get => _bool.HasValue && _bool.Value; - set - { + set { String = null; _long = null; _bool = value; } } - public static implicit operator BooleanNumberString(long value) - { - return new BooleanNumberString(value); - } + public static implicit operator BooleanNumberString(long value) => new BooleanNumberString(value); - public static implicit operator BooleanNumberString(string value) - { - return new BooleanNumberString(value); - } + public static implicit operator BooleanNumberString(string value) => new BooleanNumberString(value); - public static implicit operator BooleanNumberString(bool value) - { - return new BooleanNumberString(value); - } + public static implicit operator BooleanNumberString(bool value) => new BooleanNumberString(value); } } diff --git a/src/Protocol/Models/BooleanOr.cs b/src/Protocol/Models/BooleanOr.cs index 66e7e837b..d0ad1f801 100644 --- a/src/Protocol/Models/BooleanOr.cs +++ b/src/Protocol/Models/BooleanOr.cs @@ -6,11 +6,13 @@ public class BooleanOr { private T _value; private bool? _bool; + public BooleanOr(T value) { _value = value; _bool = null; } + public BooleanOr(bool value) { _value = default; @@ -24,42 +26,35 @@ public BooleanOr(bool value) public T Value { - get { return this._value; } - set - { - this._value = value; - this._bool = null; + get => _value; + set { + _value = value; + _bool = null; } } - public bool IsBool => this._bool.HasValue; + public bool IsBool => _bool.HasValue; + public bool Bool { - get { return this._bool.HasValue && this._bool.Value; } - set - { - this.Value = default; - this._bool = value; + get => _bool.HasValue && _bool.Value; + set { + Value = default; + _bool = value; } } + public object RawValue { - get - { + get { if (IsBool) return Bool; if (IsValue) return Value; return null; } } - public static implicit operator BooleanOr(T value) - { - return value != null ? new BooleanOr(value) : null; - } + public static implicit operator BooleanOr(T value) => value != null ? new BooleanOr(value) : null; - public static implicit operator BooleanOr(bool value) - { - return new BooleanOr(value); - } + public static implicit operator BooleanOr(bool value) => new BooleanOr(value); } } diff --git a/src/Protocol/Models/BooleanString.cs b/src/Protocol/Models/BooleanString.cs index 9023ab47b..dea782a6e 100644 --- a/src/Protocol/Models/BooleanString.cs +++ b/src/Protocol/Models/BooleanString.cs @@ -8,11 +8,13 @@ public struct BooleanString { private string _string; private bool? _bool; + public BooleanString(string value) { _string = value; _bool = null; } + public BooleanString(bool value) { _string = null; @@ -20,35 +22,29 @@ public BooleanString(bool value) } public bool IsString => _string != null; + public string String { get => _string; - set - { + set { _string = value; _bool = null; } } public bool IsBool => _bool.HasValue; + public bool Bool { get => _bool.HasValue && _bool.Value; - set - { + set { String = null; _bool = value; } } - public static implicit operator BooleanString(string value) - { - return new BooleanString(value); - } + public static implicit operator BooleanString(string value) => new BooleanString(value); - public static implicit operator BooleanString(bool value) - { - return new BooleanString(value); - } + public static implicit operator BooleanString(bool value) => new BooleanString(value); } } diff --git a/src/Protocol/Models/ClientInfo.cs b/src/Protocol/Models/ClientInfo.cs index ead6e27b6..08e663194 100644 --- a/src/Protocol/Models/ClientInfo.cs +++ b/src/Protocol/Models/ClientInfo.cs @@ -11,7 +11,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public class ClientInfo { - /// /// The name of the client as defined by the client. /// @@ -24,6 +23,7 @@ public class ClientInfo public string Version { get; set; } private string DebuggerDisplay => string.IsNullOrWhiteSpace(Version) ? Name : $"{Name} ({Version})"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/CodeAction.cs b/src/Protocol/Models/CodeAction.cs index 935e8a579..0774d4fc9 100644 --- a/src/Protocol/Models/CodeAction.cs +++ b/src/Protocol/Models/CodeAction.cs @@ -52,6 +52,7 @@ public class CodeAction public Command Command { get; set; } private string DebuggerDisplay => $"[{Kind}] {Title}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/CodeActionKind.cs b/src/Protocol/Models/CodeActionKind.cs index b372e1780..ae34a99b7 100644 --- a/src/Protocol/Models/CodeActionKind.cs +++ b/src/Protocol/Models/CodeActionKind.cs @@ -80,28 +80,20 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models private readonly string _value; - public CodeActionKind(string kind) - { - _value = kind; - } + public CodeActionKind(string kind) => _value = kind; - public static implicit operator CodeActionKind(string kind) - { - return new CodeActionKind(kind); - } + public static implicit operator CodeActionKind(string kind) => new CodeActionKind(kind); - public static implicit operator string(CodeActionKind kind) - { - return kind._value; - } + public static implicit operator string(CodeActionKind kind) => kind._value; /// public override string ToString() => _value; + public bool Equals(CodeActionKind other) => _value == other._value; public override bool Equals(object obj) => obj is CodeActionKind other && Equals(other); - public override int GetHashCode() => (_value != null ? _value.GetHashCode() : 0); + public override int GetHashCode() => _value != null ? _value.GetHashCode() : 0; public static bool operator ==(CodeActionKind left, CodeActionKind right) => left.Equals(right); diff --git a/src/Protocol/Models/CodeLens.cs b/src/Protocol/Models/CodeLens.cs index 7d45127d8..06b00ec8a 100644 --- a/src/Protocol/Models/CodeLens.cs +++ b/src/Protocol/Models/CodeLens.cs @@ -3,7 +3,6 @@ using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { @@ -36,7 +35,8 @@ public class CodeLens : IRequest, ICanBeResolved [Optional] public JToken Data { get; set; } - private string DebuggerDisplay => $"{Range}{(Command != null ? $" {Command}" : "")}"; + private string DebuggerDisplay => $"{Range}{( Command != null ? $" {Command}" : "" )}"; + /// public override string ToString() => DebuggerDisplay; } @@ -68,14 +68,14 @@ public class CodeLens : ICanBeResolved /// public T Data { - get => ((ICanBeResolved)this).Data?.ToObject(); - set => ((ICanBeResolved)this).Data = JToken.FromObject(value ?? new object()); + get => ( (ICanBeResolved) this ).Data?.ToObject(); + set => ( (ICanBeResolved) this ).Data = JToken.FromObject(value ?? new object()); } JToken ICanBeResolved.Data { get; set; } public static implicit operator CodeLens(CodeLens value) => new CodeLens { - Data = ((ICanBeResolved)value).Data, + Data = ( (ICanBeResolved) value ).Data, Command = value.Command, Range = value.Range, }; @@ -86,7 +86,7 @@ public static implicit operator CodeLens(CodeLens value) Command = value.Command, Range = value.Range, }; - ((ICanBeResolved)item).Data = value.Data; + ( (ICanBeResolved) item ).Data = value.Data; return item; } } diff --git a/src/Protocol/Models/CodeLensContainer.cs b/src/Protocol/Models/CodeLensContainer.cs index 5cc6b2c09..6b9729648 100644 --- a/src/Protocol/Models/CodeLensContainer.cs +++ b/src/Protocol/Models/CodeLensContainer.cs @@ -1,8 +1,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; -using System.ComponentModel; using System.Linq; -using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { @@ -20,20 +18,11 @@ public CodeLensContainer(params CodeLens[] items) : base(items) { } - public static implicit operator CodeLensContainer(CodeLens[] items) - { - return new CodeLensContainer(items); - } + public static implicit operator CodeLensContainer(CodeLens[] items) => new CodeLensContainer(items); - public static implicit operator CodeLensContainer(Collection items) - { - return new CodeLensContainer(items); - } + public static implicit operator CodeLensContainer(Collection items) => new CodeLensContainer(items); - public static implicit operator CodeLensContainer(List items) - { - return new CodeLensContainer(items); - } + public static implicit operator CodeLensContainer(List items) => new CodeLensContainer(items); } /// @@ -53,21 +42,12 @@ public CodeLensContainer(params CodeLens[] items) : base(items) { } - public static implicit operator CodeLensContainer(CodeLens[] items) - { - return new CodeLensContainer(items); - } + public static implicit operator CodeLensContainer(CodeLens[] items) => new CodeLensContainer(items); - public static implicit operator CodeLensContainer(Collection> items) - { - return new CodeLensContainer(items); - } + public static implicit operator CodeLensContainer(Collection> items) => new CodeLensContainer(items); - public static implicit operator CodeLensContainer(List> items) - { - return new CodeLensContainer(items); - } + public static implicit operator CodeLensContainer(List> items) => new CodeLensContainer(items); - public static implicit operator CodeLensContainer(CodeLensContainer container) => new CodeLensContainer(container.Select(z => (CodeLens)z)); + public static implicit operator CodeLensContainer(CodeLensContainer container) => new CodeLensContainer(container.Select(z => (CodeLens) z)); } } diff --git a/src/Protocol/Models/ColorInformation.cs b/src/Protocol/Models/ColorInformation.cs index ea6db727c..be44be8f7 100644 --- a/src/Protocol/Models/ColorInformation.cs +++ b/src/Protocol/Models/ColorInformation.cs @@ -6,6 +6,7 @@ public class ColorInformation /// The range in the document where this color appers. /// public Range Range { get; set; } + /// /// The actual color value for this color range. /// diff --git a/src/Protocol/Models/ColorPresentation.cs b/src/Protocol/Models/ColorPresentation.cs index 7e4cb8857..4f00aedb7 100644 --- a/src/Protocol/Models/ColorPresentation.cs +++ b/src/Protocol/Models/ColorPresentation.cs @@ -10,6 +10,7 @@ public class ColorPresentation /// this color presentation. /// public string Label { get; set; } + /// /// An [edit](#TextEdit) which is applied to a document when selecting /// this presentation for the color. When `falsy` the [label](#ColorPresentation.label) @@ -17,6 +18,7 @@ public class ColorPresentation /// [Optional] public TextEdit TextEdit { get; set; } + /// /// An optional array of additional [text edits](#TextEdit) that are applied when /// selecting this color presentation. Edits must not overlap with the main [edit](#ColorPresentation.textEdit) nor with themselves. diff --git a/src/Protocol/Models/ColorPresentationParams.cs b/src/Protocol/Models/ColorPresentationParams.cs index 2bb9e1175..ea845f037 100644 --- a/src/Protocol/Models/ColorPresentationParams.cs +++ b/src/Protocol/Models/ColorPresentationParams.cs @@ -10,10 +10,12 @@ public class ColorPresentationParams : IRequest> /// The document to provide document links for. /// public TextDocumentIdentifier TextDocument { get; set; } + /// /// The actual color value for this color range. /// public DocumentColor Color { get; set; } + /// /// The range in the document where this color appers. /// diff --git a/src/Protocol/Models/Command.cs b/src/Protocol/Models/Command.cs index 064e5407f..8ea2f2a46 100644 --- a/src/Protocol/Models/Command.cs +++ b/src/Protocol/Models/Command.cs @@ -28,7 +28,7 @@ public class Command public JArray Arguments { get; set; } private string DebuggerDisplay => - $"{Title}{(string.IsNullOrWhiteSpace(Name) ? "" : $" {Name}")}{(Arguments == null ? "" : string.Join(", ", Arguments.Select(z => z.ToString().Trim('"'))))}"; + $"{Title}{( string.IsNullOrWhiteSpace(Name) ? "" : $" {Name}" )}{( Arguments == null ? "" : string.Join(", ", Arguments.Select(z => z.ToString().Trim('"'))) )}"; public override string ToString() => DebuggerDisplay; @@ -50,7 +50,7 @@ public Command WithArguments(params object[] args) return this; } - public static Command Create(string name, params object[] args) => new Command() { + public static Command Create(string name, params object[] args) => new Command { Name = name, Arguments = JArray.FromObject(args) }; diff --git a/src/Protocol/Models/CommandOrCodeAction.cs b/src/Protocol/Models/CommandOrCodeAction.cs index 1ef3c106d..d4b7bbea4 100644 --- a/src/Protocol/Models/CommandOrCodeAction.cs +++ b/src/Protocol/Models/CommandOrCodeAction.cs @@ -10,36 +10,41 @@ public struct CommandOrCodeAction { private CodeAction _codeAction; private Command _command; + public CommandOrCodeAction(CodeAction value) { _codeAction = value; _command = default; } + public CommandOrCodeAction(Command value) { _codeAction = default; _command = value; } - public bool IsCommand => this._command != null; + public bool IsCommand => _command != null; + public Command Command { - get { return this._command; } + get => _command; set { - this._command = value; - this._codeAction = null; + _command = value; + _codeAction = null; } } - public bool IsCodeAction => this._codeAction != null; + public bool IsCodeAction => _codeAction != null; + public CodeAction CodeAction { - get { return this._codeAction; } + get => _codeAction; set { - this._command = default; - this._codeAction = value; + _command = default; + _codeAction = value; } } + public object RawValue { get { @@ -49,17 +54,12 @@ public object RawValue } } - public static implicit operator CommandOrCodeAction(Command value) - { - return new CommandOrCodeAction(value); - } + public static implicit operator CommandOrCodeAction(Command value) => new CommandOrCodeAction(value); - public static implicit operator CommandOrCodeAction(CodeAction value) - { - return new CommandOrCodeAction(value); - } + public static implicit operator CommandOrCodeAction(CodeAction value) => new CommandOrCodeAction(value); + + private string DebuggerDisplay => $"{( IsCommand ? $"command: {Command}" : IsCodeAction ? $"code action: {CodeAction}" : "..." )}"; - private string DebuggerDisplay => $"{(IsCommand ? $"command: {Command}" : IsCodeAction ? $"code action: {CodeAction}" : "...")}"; /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/CommandOrCodeActionContainer.cs b/src/Protocol/Models/CommandOrCodeActionContainer.cs index f26813973..861fba7a2 100644 --- a/src/Protocol/Models/CommandOrCodeActionContainer.cs +++ b/src/Protocol/Models/CommandOrCodeActionContainer.cs @@ -18,19 +18,10 @@ public CommandOrCodeActionContainer(params CommandOrCodeAction[] items) : base(i { } - public static implicit operator CommandOrCodeActionContainer(CommandOrCodeAction[] items) - { - return new CommandOrCodeActionContainer(items); - } + public static implicit operator CommandOrCodeActionContainer(CommandOrCodeAction[] items) => new CommandOrCodeActionContainer(items); - public static implicit operator CommandOrCodeActionContainer(Collection items) - { - return new CommandOrCodeActionContainer(items); - } + public static implicit operator CommandOrCodeActionContainer(Collection items) => new CommandOrCodeActionContainer(items); - public static implicit operator CommandOrCodeActionContainer(List items) - { - return new CommandOrCodeActionContainer(items); - } + public static implicit operator CommandOrCodeActionContainer(List items) => new CommandOrCodeActionContainer(items); } } diff --git a/src/Protocol/Models/CompletionItem.cs b/src/Protocol/Models/CompletionItem.cs index 7a96842ee..80c1698c7 100644 --- a/src/Protocol/Models/CompletionItem.cs +++ b/src/Protocol/Models/CompletionItem.cs @@ -1,11 +1,9 @@ -using System.ComponentModel; using System.Diagnostics; using System.Linq; using MediatR; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { @@ -135,7 +133,8 @@ public class CompletionItem : ICanBeResolved, IRequest [Optional] public JToken Data { get; set; } - private string DebuggerDisplay => $"[{Kind}] {Label}{(Tags?.Any() == true ? $" tags: {string.Join(", ", Tags.Select(z => z.ToString()))}" : "")}"; + private string DebuggerDisplay => $"[{Kind}] {Label}{( Tags?.Any() == true ? $" tags: {string.Join(", ", Tags.Select(z => z.ToString()))}" : "" )}"; + /// public override string ToString() => DebuggerDisplay; } @@ -268,14 +267,14 @@ public class CompletionItem : ICanBeResolved [Optional] public T Data { - get => ((ICanBeResolved)this).Data?.ToObject(); - set => ((ICanBeResolved)this).Data = JToken.FromObject(value ?? new object()); + get => ( (ICanBeResolved) this ).Data?.ToObject(); + set => ( (ICanBeResolved) this ).Data = JToken.FromObject(value ?? new object()); } JToken ICanBeResolved.Data { get; set; } public static implicit operator CompletionItem(CompletionItem value) => new CompletionItem { - Data = ((ICanBeResolved)value).Data, + Data = ( (ICanBeResolved) value ).Data, Command = value.Command, Deprecated = value.Deprecated, Detail = value.Detail, @@ -312,7 +311,7 @@ public static implicit operator CompletionItem(CompletionItem value) AdditionalTextEdits = value.AdditionalTextEdits, InsertTextFormat = value.InsertTextFormat, }; - ((ICanBeResolved)item).Data = value.Data; + ( (ICanBeResolved) item ).Data = value.Data; return item; } } diff --git a/src/Protocol/Models/CompletionList.cs b/src/Protocol/Models/CompletionList.cs index 569a35e7b..2ec619e19 100644 --- a/src/Protocol/Models/CompletionList.cs +++ b/src/Protocol/Models/CompletionList.cs @@ -1,9 +1,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; -using System.ComponentModel; using System.Linq; using Newtonsoft.Json; -using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models @@ -15,24 +13,24 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [JsonConverter(typeof(CompletionListConverter))] public class CompletionList : Container { - public CompletionList() : base(Enumerable.Empty()) { } - public CompletionList(bool isIncomplete) : base(Enumerable.Empty()) + public CompletionList() : base(Enumerable.Empty()) { - IsIncomplete = isIncomplete; } - public CompletionList(IEnumerable items) : base(items) { } - public CompletionList(IEnumerable items, bool isIncomplete) : base(items) + public CompletionList(bool isIncomplete) : base(Enumerable.Empty()) => IsIncomplete = isIncomplete; + + public CompletionList(IEnumerable items) : base(items) { - IsIncomplete = isIncomplete; } - public CompletionList(params CompletionItem[] items) : base(items) { } - public CompletionList(bool isIncomplete, params CompletionItem[] items) : base(items) + public CompletionList(IEnumerable items, bool isIncomplete) : base(items) => IsIncomplete = isIncomplete; + + public CompletionList(params CompletionItem[] items) : base(items) { - IsIncomplete = isIncomplete; } + public CompletionList(bool isIncomplete, params CompletionItem[] items) : base(items) => IsIncomplete = isIncomplete; + /// /// This list it not complete. Further typing should result in recomputing /// this list. @@ -44,25 +42,13 @@ public CompletionList(bool isIncomplete, params CompletionItem[] items) : base(i /// public IEnumerable Items => this; - public static implicit operator CompletionList(CompletionItem[] items) - { - return new CompletionList(items); - } + public static implicit operator CompletionList(CompletionItem[] items) => new CompletionList(items); - public static implicit operator CompletionList(Collection items) - { - return new CompletionList(items); - } + public static implicit operator CompletionList(Collection items) => new CompletionList(items); - public static implicit operator CompletionList(List items) - { - return new CompletionList(items); - } + public static implicit operator CompletionList(List items) => new CompletionList(items); - public static implicit operator CompletionItem[] (CompletionList list) - { - return list.ToArray(); - } + public static implicit operator CompletionItem[](CompletionList list) => list.ToArray(); } /// @@ -71,24 +57,24 @@ public static implicit operator CompletionItem[] (CompletionList list) /// public class CompletionList : Container> where T : HandlerIdentity, new() { - public CompletionList() : base(Enumerable.Empty>()) { } - public CompletionList(bool isIncomplete) : base(Enumerable.Empty>()) + public CompletionList() : base(Enumerable.Empty>()) { - IsIncomplete = isIncomplete; } - public CompletionList(IEnumerable> items) : base(items) { } - public CompletionList(IEnumerable> items, bool isIncomplete) : base(items) + public CompletionList(bool isIncomplete) : base(Enumerable.Empty>()) => IsIncomplete = isIncomplete; + + public CompletionList(IEnumerable> items) : base(items) { - IsIncomplete = isIncomplete; } - public CompletionList(params CompletionItem[] items) : base(items) { } - public CompletionList(bool isIncomplete, params CompletionItem[] items) : base(items) + public CompletionList(IEnumerable> items, bool isIncomplete) : base(items) => IsIncomplete = isIncomplete; + + public CompletionList(params CompletionItem[] items) : base(items) { - IsIncomplete = isIncomplete; } + public CompletionList(bool isIncomplete, params CompletionItem[] items) : base(items) => IsIncomplete = isIncomplete; + /// /// This list it not complete. Further typing should result in recomputing /// this list. @@ -100,26 +86,14 @@ public CompletionList(bool isIncomplete, params CompletionItem[] items) : bas /// public IEnumerable> Items => this; - public static implicit operator CompletionList(CompletionItem[] items) - { - return new CompletionList(items); - } + public static implicit operator CompletionList(CompletionItem[] items) => new CompletionList(items); - public static implicit operator CompletionList(Collection> items) - { - return new CompletionList(items); - } + public static implicit operator CompletionList(Collection> items) => new CompletionList(items); - public static implicit operator CompletionList(List> items) - { - return new CompletionList(items); - } + public static implicit operator CompletionList(List> items) => new CompletionList(items); - public static implicit operator CompletionItem[] (CompletionList list) - { - return list.ToArray(); - } + public static implicit operator CompletionItem[](CompletionList list) => list.ToArray(); - public static implicit operator CompletionList(CompletionList container) => new CompletionList(container.Select(z => (CompletionItem)z)); + public static implicit operator CompletionList(CompletionList container) => new CompletionList(container.Select(z => (CompletionItem) z)); } } diff --git a/src/Protocol/Models/CompletionTriggerKind.cs b/src/Protocol/Models/CompletionTriggerKind.cs index 0e50c061c..ab5f71446 100644 --- a/src/Protocol/Models/CompletionTriggerKind.cs +++ b/src/Protocol/Models/CompletionTriggerKind.cs @@ -10,10 +10,12 @@ public enum CompletionTriggerKind /// Completion was triggered by typing an identifier (24x7 code complete), manual invocation (e.g Ctrl+Space) or via API. /// Invoked = 1, + /// /// Completion was triggered by a trigger character specified by the `triggerCharacters` properties of the `CompletionRegistrationOptions`. /// TriggerCharacter = 2, + /// /// Completion was re-triggered as the current completion list is incomplete. /// diff --git a/src/Protocol/Models/ConfigurationItem.cs b/src/Protocol/Models/ConfigurationItem.cs index f0fd49438..89a9185fb 100644 --- a/src/Protocol/Models/ConfigurationItem.cs +++ b/src/Protocol/Models/ConfigurationItem.cs @@ -4,9 +4,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public class ConfigurationItem { - [Optional] - public DocumentUri ScopeUri { get; set; } - [Optional] - public string Section { get; set; } + [Optional] public DocumentUri ScopeUri { get; set; } + [Optional] public string Section { get; set; } } } diff --git a/src/Protocol/Models/Container.cs b/src/Protocol/Models/Container.cs index 0d49de174..45aa40737 100644 --- a/src/Protocol/Models/Container.cs +++ b/src/Protocol/Models/Container.cs @@ -18,19 +18,10 @@ public Container(params T[] items) : base(items) { } - public static implicit operator Container(T[] items) - { - return new Container(items); - } + public static implicit operator Container(T[] items) => new Container(items); - public static implicit operator Container(Collection items) - { - return new Container(items); - } + public static implicit operator Container(Collection items) => new Container(items); - public static implicit operator Container(List items) - { - return new Container(items); - } + public static implicit operator Container(List items) => new Container(items); } } diff --git a/src/Protocol/Models/ContainerBase.cs b/src/Protocol/Models/ContainerBase.cs index 16ec769f3..1e2efa1a0 100644 --- a/src/Protocol/Models/ContainerBase.cs +++ b/src/Protocol/Models/ContainerBase.cs @@ -8,45 +8,22 @@ public abstract class ContainerBase : IEnumerable, IEquatable _items; - public ContainerBase(IEnumerable items) - { - _items = items; - } - - public override bool Equals(object obj) - { - return Equals(obj as ContainerBase); - } - - public bool Equals(ContainerBase other) - { - return other != null && - EqualityComparer>.Default.Equals(_items, other._items); - } - - public IEnumerator GetEnumerator() - { - return _items.GetEnumerator(); - } - - public override int GetHashCode() - { - return -566117206 + EqualityComparer>.Default.GetHashCode(_items); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public static bool operator ==(ContainerBase base1, ContainerBase base2) - { - return EqualityComparer>.Default.Equals(base1, base2); - } - - public static bool operator !=(ContainerBase base1, ContainerBase base2) - { - return !(base1 == base2); - } + public ContainerBase(IEnumerable items) => _items = items; + + public override bool Equals(object obj) => Equals(obj as ContainerBase); + + public bool Equals(ContainerBase other) => + other != null && + EqualityComparer>.Default.Equals(_items, other._items); + + public IEnumerator GetEnumerator() => _items.GetEnumerator(); + + public override int GetHashCode() => -566117206 + EqualityComparer>.Default.GetHashCode(_items); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + public static bool operator ==(ContainerBase base1, ContainerBase base2) => EqualityComparer>.Default.Equals(base1, base2); + + public static bool operator !=(ContainerBase base1, ContainerBase base2) => !( base1 == base2 ); } } diff --git a/src/Protocol/Models/CreateFile.cs b/src/Protocol/Models/CreateFile.cs index 982cb9b18..a83171c47 100644 --- a/src/Protocol/Models/CreateFile.cs +++ b/src/Protocol/Models/CreateFile.cs @@ -11,10 +11,12 @@ public class CreateFile : IFile /// A create /// public ResourceOperationKind Kind { get; } = ResourceOperationKind.Create; + /// /// The resource to create. /// public DocumentUri Uri { get; set; } + /// /// Additional Options /// diff --git a/src/Protocol/Models/CreateFileOptions.cs b/src/Protocol/Models/CreateFileOptions.cs index 2661cd28b..5c3b94f50 100644 --- a/src/Protocol/Models/CreateFileOptions.cs +++ b/src/Protocol/Models/CreateFileOptions.cs @@ -12,6 +12,7 @@ public class CreateFileOptions /// [Optional] public bool Overwrite { get; set; } + /// /// Ignore if exists. /// diff --git a/src/Protocol/Models/DeclarationRegistrationOptions.cs b/src/Protocol/Models/DeclarationRegistrationOptions.cs index d990b0dee..444d2e46f 100644 --- a/src/Protocol/Models/DeclarationRegistrationOptions.cs +++ b/src/Protocol/Models/DeclarationRegistrationOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public class DeclarationRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IDeclarationOptions { } + public class DeclarationRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IDeclarationOptions + { + } } diff --git a/src/Protocol/Models/DefinitionRegistrationOptions.cs b/src/Protocol/Models/DefinitionRegistrationOptions.cs index 7f5c35257..f8a54aacf 100644 --- a/src/Protocol/Models/DefinitionRegistrationOptions.cs +++ b/src/Protocol/Models/DefinitionRegistrationOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public class DefinitionRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IDefinitionOptions { } + public class DefinitionRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IDefinitionOptions + { + } } diff --git a/src/Protocol/Models/DeleteFile.cs b/src/Protocol/Models/DeleteFile.cs index 994f95972..d81194971 100644 --- a/src/Protocol/Models/DeleteFile.cs +++ b/src/Protocol/Models/DeleteFile.cs @@ -11,10 +11,12 @@ public class DeleteFile : IFile /// A delete /// public ResourceOperationKind Kind { get; } = ResourceOperationKind.Delete; + /// /// The file to delete. /// public DocumentUri Uri { get; set; } + /// /// Delete Options. /// diff --git a/src/Protocol/Models/DeleteFileOptions.cs b/src/Protocol/Models/DeleteFileOptions.cs index 8348381e0..d8af13997 100644 --- a/src/Protocol/Models/DeleteFileOptions.cs +++ b/src/Protocol/Models/DeleteFileOptions.cs @@ -12,6 +12,7 @@ public class DeleteFileOptions /// [Optional] public bool Recursive { get; set; } + /// /// Ignore the operation if the file doesn't exist. /// diff --git a/src/Protocol/Models/Diagnostic.cs b/src/Protocol/Models/Diagnostic.cs index 2b7fb8749..6f954cf6f 100644 --- a/src/Protocol/Models/Diagnostic.cs +++ b/src/Protocol/Models/Diagnostic.cs @@ -53,10 +53,10 @@ public class Diagnostic public Container RelatedInformation { get; set; } private string DebuggerDisplay => - $"{(Code.HasValue ? $"[{Code.Value.ToString()}]" : "")}" + + $"{( Code.HasValue ? $"[{Code.Value.ToString()}]" : "" )}" + $"{Range}" + - $"{(string.IsNullOrWhiteSpace(Source) ? "" : $" ({Source})")}" + - $"{(Tags?.Any() == true ? $" [tags: {string.Join(", ", Tags.Select(z => z.ToString()))}]" : "")}" + - $" {(Message?.Length > 20 ? Message.Substring(0, 20) : Message)}"; + $"{( string.IsNullOrWhiteSpace(Source) ? "" : $" ({Source})" )}" + + $"{( Tags?.Any() == true ? $" [tags: {string.Join(", ", Tags.Select(z => z.ToString()))}]" : "" )}" + + $" {( Message?.Length > 20 ? Message.Substring(0, 20) : Message )}"; } } diff --git a/src/Protocol/Models/DiagnosticCode.cs b/src/Protocol/Models/DiagnosticCode.cs index a9252b968..a47c07070 100644 --- a/src/Protocol/Models/DiagnosticCode.cs +++ b/src/Protocol/Models/DiagnosticCode.cs @@ -18,29 +18,17 @@ public DiagnosticCode(string value) String = value; } - public bool IsLong => this.String == null; + public bool IsLong => String == null; public long Long { get; set; } - public bool IsString => this.String != null; + public bool IsString => String != null; public string String { get; set; } - public static implicit operator DiagnosticCode(long value) - { - return new DiagnosticCode(value); - } + public static implicit operator DiagnosticCode(long value) => new DiagnosticCode(value); - public static implicit operator DiagnosticCode(string value) - { - return new DiagnosticCode(value); - } + public static implicit operator DiagnosticCode(string value) => new DiagnosticCode(value); - public static implicit operator long(DiagnosticCode value) - { - return value.IsLong ? value.Long : 0; - } + public static implicit operator long(DiagnosticCode value) => value.IsLong ? value.Long : 0; - public static implicit operator string(DiagnosticCode value) - { - return value.IsString ? value.String : null; - } + public static implicit operator string(DiagnosticCode value) => value.IsString ? value.String : null; } } diff --git a/src/Protocol/Models/DiagnosticSeverity.cs b/src/Protocol/Models/DiagnosticSeverity.cs index b3389effc..18c9147ca 100644 --- a/src/Protocol/Models/DiagnosticSeverity.cs +++ b/src/Protocol/Models/DiagnosticSeverity.cs @@ -10,14 +10,17 @@ public enum DiagnosticSeverity /// Reports an error. /// Error = 1, + /// /// Reports a warning. /// Warning = 2, + /// /// Reports an information. /// Information = 3, + /// /// Reports a hint. /// diff --git a/src/Protocol/Models/DidChangeConfigurationParams.cs b/src/Protocol/Models/DidChangeConfigurationParams.cs index 08fd35201..a4c638010 100644 --- a/src/Protocol/Models/DidChangeConfigurationParams.cs +++ b/src/Protocol/Models/DidChangeConfigurationParams.cs @@ -8,7 +8,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models public class DidChangeConfigurationParams : IRequest { /// - /// The actual changed settings + /// The actual changed settings /// public JToken Settings { get; set; } } diff --git a/src/Protocol/Models/DidChangeTextDocumentParams.cs b/src/Protocol/Models/DidChangeTextDocumentParams.cs index dbd091010..30c1da460 100644 --- a/src/Protocol/Models/DidChangeTextDocumentParams.cs +++ b/src/Protocol/Models/DidChangeTextDocumentParams.cs @@ -7,14 +7,14 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models public class DidChangeTextDocumentParams : IRequest { /// - /// The document that did change. The version number points - /// to the version after all provided content changes have - /// been applied. + /// The document that did change. The version number points + /// to the version after all provided content changes have + /// been applied. /// public VersionedTextDocumentIdentifier TextDocument { get; set; } /// - /// The actual content changes. + /// The actual content changes. /// public Container ContentChanges { get; set; } } diff --git a/src/Protocol/Models/DidChangeWatchedFilesParams.cs b/src/Protocol/Models/DidChangeWatchedFilesParams.cs index 965c7149f..5ca0c038e 100644 --- a/src/Protocol/Models/DidChangeWatchedFilesParams.cs +++ b/src/Protocol/Models/DidChangeWatchedFilesParams.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models public class DidChangeWatchedFilesParams : IRequest { /// - /// The actual file events. + /// The actual file events. /// public Container Changes { get; set; } } diff --git a/src/Protocol/Models/DidCloseTextDocumentParams.cs b/src/Protocol/Models/DidCloseTextDocumentParams.cs index 8a1b9f7bf..d33294869 100644 --- a/src/Protocol/Models/DidCloseTextDocumentParams.cs +++ b/src/Protocol/Models/DidCloseTextDocumentParams.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models public class DidCloseTextDocumentParams : ITextDocumentIdentifierParams, IRequest { /// - /// The document that was closed. + /// The document that was closed. /// public TextDocumentIdentifier TextDocument { get; set; } } diff --git a/src/Protocol/Models/DidOpenTextDocumentParams.cs b/src/Protocol/Models/DidOpenTextDocumentParams.cs index a1d676b1d..3c6716134 100644 --- a/src/Protocol/Models/DidOpenTextDocumentParams.cs +++ b/src/Protocol/Models/DidOpenTextDocumentParams.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models public class DidOpenTextDocumentParams : IRequest { /// - /// The document that was opened. + /// The document that was opened. /// public TextDocumentItem TextDocument { get; set; } } diff --git a/src/Protocol/Models/DidSaveTextDocumentParams.cs b/src/Protocol/Models/DidSaveTextDocumentParams.cs index 0c2ee907f..be1695950 100644 --- a/src/Protocol/Models/DidSaveTextDocumentParams.cs +++ b/src/Protocol/Models/DidSaveTextDocumentParams.cs @@ -8,13 +8,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models public class DidSaveTextDocumentParams : ITextDocumentIdentifierParams, IRequest { /// - /// The document that was saved. + /// The document that was saved. /// public TextDocumentIdentifier TextDocument { get; set; } /// - /// Optional the content when saved. Depends on the includeText value - /// when the save notifcation was requested. + /// Optional the content when saved. Depends on the includeText value + /// when the save notifcation was requested. /// [Optional] public string Text { get; set; } diff --git a/src/Protocol/Models/DocumentColor.cs b/src/Protocol/Models/DocumentColor.cs index 70ca4d36f..18f0d5f81 100644 --- a/src/Protocol/Models/DocumentColor.cs +++ b/src/Protocol/Models/DocumentColor.cs @@ -1,5 +1,4 @@ using System.Diagnostics; -using System.Reflection.Emit; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { @@ -30,6 +29,7 @@ public class DocumentColor public double Alpha { get; set; } private string DebuggerDisplay => $"R:{Red} G:{Green} B:{Blue} A:{Alpha}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/DocumentFilter.cs b/src/Protocol/Models/DocumentFilter.cs index cd4e86df7..3a9d2297e 100644 --- a/src/Protocol/Models/DocumentFilter.cs +++ b/src/Protocol/Models/DocumentFilter.cs @@ -11,20 +11,11 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public class DocumentFilter : IEquatable { - public static DocumentFilter ForPattern(string wildcard) - { - return new DocumentFilter() { Pattern = wildcard }; - } + public static DocumentFilter ForPattern(string wildcard) => new DocumentFilter { Pattern = wildcard }; - public static DocumentFilter ForLanguage(string language) - { - return new DocumentFilter() { Language = language }; - } + public static DocumentFilter ForLanguage(string language) => new DocumentFilter { Language = language }; - public static DocumentFilter ForScheme(string scheme) - { - return new DocumentFilter() { Scheme = scheme }; - } + public static DocumentFilter ForScheme(string scheme) => new DocumentFilter { Scheme = scheme }; /// /// A language id, like `typescript`. @@ -59,7 +50,7 @@ public string Pattern get => _pattern; set { _pattern = value; - _minimatcher = new Minimatcher(value, new Options() { MatchBase = true }); + _minimatcher = new Minimatcher(value, new Options { MatchBase = true }); } } @@ -144,17 +135,17 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; - return Equals((DocumentFilter)obj); + if (obj.GetType() != GetType()) return false; + return Equals((DocumentFilter) obj); } public override int GetHashCode() { unchecked { - var hashCode = (_pattern != null ? _pattern.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (Language != null ? Language.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (Scheme != null ? Scheme.GetHashCode() : 0); + var hashCode = _pattern != null ? _pattern.GetHashCode() : 0; + hashCode = ( hashCode * 397 ) ^ ( Language != null ? Language.GetHashCode() : 0 ); + hashCode = ( hashCode * 397 ) ^ ( Scheme != null ? Scheme.GetHashCode() : 0 ); return hashCode; } } @@ -163,7 +154,8 @@ public override int GetHashCode() public static bool operator !=(DocumentFilter left, DocumentFilter right) => !Equals(left, right); - private string DebuggerDisplay => (string)this; + private string DebuggerDisplay => (string) this; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/DocumentFormattingParams.cs b/src/Protocol/Models/DocumentFormattingParams.cs index b0762d123..235b525ba 100644 --- a/src/Protocol/Models/DocumentFormattingParams.cs +++ b/src/Protocol/Models/DocumentFormattingParams.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { -[Method(TextDocumentNames.DocumentFormatting, Direction.ClientToServer)] + [Method(TextDocumentNames.DocumentFormatting, Direction.ClientToServer)] public class DocumentFormattingParams : ITextDocumentIdentifierParams, IRequest, IWorkDoneProgressParams { /// diff --git a/src/Protocol/Models/DocumentFormattingRegistrationOptions.cs b/src/Protocol/Models/DocumentFormattingRegistrationOptions.cs index 140e37cca..a80583396 100644 --- a/src/Protocol/Models/DocumentFormattingRegistrationOptions.cs +++ b/src/Protocol/Models/DocumentFormattingRegistrationOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public class DocumentFormattingRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IDocumentFormattingOptions { } + public class DocumentFormattingRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IDocumentFormattingOptions + { + } } diff --git a/src/Protocol/Models/DocumentHighlightContainer.cs b/src/Protocol/Models/DocumentHighlightContainer.cs index 6a104e370..ffed1720e 100644 --- a/src/Protocol/Models/DocumentHighlightContainer.cs +++ b/src/Protocol/Models/DocumentHighlightContainer.cs @@ -18,19 +18,10 @@ public DocumentHighlightContainer(params DocumentHighlight[] items) : base(items { } - public static implicit operator DocumentHighlightContainer(DocumentHighlight[] items) - { - return new DocumentHighlightContainer(items); - } + public static implicit operator DocumentHighlightContainer(DocumentHighlight[] items) => new DocumentHighlightContainer(items); - public static implicit operator DocumentHighlightContainer(Collection items) - { - return new DocumentHighlightContainer(items); - } + public static implicit operator DocumentHighlightContainer(Collection items) => new DocumentHighlightContainer(items); - public static implicit operator DocumentHighlightContainer(List items) - { - return new DocumentHighlightContainer(items); - } + public static implicit operator DocumentHighlightContainer(List items) => new DocumentHighlightContainer(items); } } diff --git a/src/Protocol/Models/DocumentHighlightRegistrationOptions.cs b/src/Protocol/Models/DocumentHighlightRegistrationOptions.cs index 108c37f86..229a4c570 100644 --- a/src/Protocol/Models/DocumentHighlightRegistrationOptions.cs +++ b/src/Protocol/Models/DocumentHighlightRegistrationOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public class DocumentHighlightRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IDocumentHighlightOptions { } + public class DocumentHighlightRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IDocumentHighlightOptions + { + } } diff --git a/src/Protocol/Models/DocumentLink.cs b/src/Protocol/Models/DocumentLink.cs index 915e118aa..271f974e0 100644 --- a/src/Protocol/Models/DocumentLink.cs +++ b/src/Protocol/Models/DocumentLink.cs @@ -1,10 +1,8 @@ -using System.ComponentModel; using System.Diagnostics; using MediatR; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { @@ -46,7 +44,8 @@ public class DocumentLink : ICanBeResolved, IRequest [Optional] public string Tooltip { get; set; } - private string DebuggerDisplay => $"{Range}{(Target != null ? $" {Target}" : "")}{(string.IsNullOrWhiteSpace(Tooltip) ? $" {Tooltip}" : "")}"; + private string DebuggerDisplay => $"{Range}{( Target != null ? $" {Target}" : "" )}{( string.IsNullOrWhiteSpace(Tooltip) ? $" {Tooltip}" : "" )}"; + /// public override string ToString() => DebuggerDisplay; } @@ -88,14 +87,14 @@ public class DocumentLink : ICanBeResolved [Optional] public T Data { - get => ((ICanBeResolved)this).Data?.ToObject(); - set => ((ICanBeResolved)this).Data = JToken.FromObject(value ?? new object()); + get => ( (ICanBeResolved) this ).Data?.ToObject(); + set => ( (ICanBeResolved) this ).Data = JToken.FromObject(value ?? new object()); } JToken ICanBeResolved.Data { get; set; } public static implicit operator DocumentLink(DocumentLink value) => new DocumentLink { - Data = ((ICanBeResolved)value).Data, + Data = ( (ICanBeResolved) value ).Data, Range = value.Range, Target = value.Target, Tooltip = value.Tooltip, @@ -108,7 +107,7 @@ public static implicit operator DocumentLink(DocumentLink value) Target = value.Target, Tooltip = value.Tooltip, }; - ((ICanBeResolved)item).Data = value.Data; + ( (ICanBeResolved) item ).Data = value.Data; return item; } } diff --git a/src/Protocol/Models/DocumentLinkContainer.cs b/src/Protocol/Models/DocumentLinkContainer.cs index 1075516b0..5df8dc011 100644 --- a/src/Protocol/Models/DocumentLinkContainer.cs +++ b/src/Protocol/Models/DocumentLinkContainer.cs @@ -1,8 +1,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; -using System.ComponentModel; using System.Linq; -using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { @@ -20,20 +18,11 @@ public DocumentLinkContainer(params DocumentLink[] items) : base(items) { } - public static implicit operator DocumentLinkContainer(DocumentLink[] items) - { - return new DocumentLinkContainer(items); - } + public static implicit operator DocumentLinkContainer(DocumentLink[] items) => new DocumentLinkContainer(items); - public static implicit operator DocumentLinkContainer(Collection items) - { - return new DocumentLinkContainer(items); - } + public static implicit operator DocumentLinkContainer(Collection items) => new DocumentLinkContainer(items); - public static implicit operator DocumentLinkContainer(List items) - { - return new DocumentLinkContainer(items); - } + public static implicit operator DocumentLinkContainer(List items) => new DocumentLinkContainer(items); } public class DocumentLinkContainer : Container> where T : HandlerIdentity, new() @@ -50,21 +39,12 @@ public DocumentLinkContainer(params DocumentLink[] items) : base(items) { } - public static implicit operator DocumentLinkContainer(DocumentLink[] items) - { - return new DocumentLinkContainer(items); - } + public static implicit operator DocumentLinkContainer(DocumentLink[] items) => new DocumentLinkContainer(items); - public static implicit operator DocumentLinkContainer(Collection> items) - { - return new DocumentLinkContainer(items); - } + public static implicit operator DocumentLinkContainer(Collection> items) => new DocumentLinkContainer(items); - public static implicit operator DocumentLinkContainer(List> items) - { - return new DocumentLinkContainer(items); - } + public static implicit operator DocumentLinkContainer(List> items) => new DocumentLinkContainer(items); - public static implicit operator DocumentLinkContainer(DocumentLinkContainer container) => new DocumentLinkContainer(container.Select(z => (DocumentLink)z)); + public static implicit operator DocumentLinkContainer(DocumentLinkContainer container) => new DocumentLinkContainer(container.Select(z => (DocumentLink) z)); } } diff --git a/src/Protocol/Models/DocumentRangeFormattingRegistrationOptions.cs b/src/Protocol/Models/DocumentRangeFormattingRegistrationOptions.cs index b9440793b..fb94ea9e0 100644 --- a/src/Protocol/Models/DocumentRangeFormattingRegistrationOptions.cs +++ b/src/Protocol/Models/DocumentRangeFormattingRegistrationOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public class DocumentRangeFormattingRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IDocumentRangeFormattingOptions { } + public class DocumentRangeFormattingRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IDocumentRangeFormattingOptions + { + } } diff --git a/src/Protocol/Models/DocumentSelector.cs b/src/Protocol/Models/DocumentSelector.cs index 5114767ea..00de5491c 100644 --- a/src/Protocol/Models/DocumentSelector.cs +++ b/src/Protocol/Models/DocumentSelector.cs @@ -2,7 +2,6 @@ using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; -using System.Reactive.Joins; using OmniSharp.Extensions.LanguageServer.Protocol.Document; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models @@ -25,52 +24,24 @@ public DocumentSelector(params DocumentFilter[] items) : base(items) { } - public static implicit operator DocumentSelector(DocumentFilter[] items) - { - return new DocumentSelector(items); - } + public static implicit operator DocumentSelector(DocumentFilter[] items) => new DocumentSelector(items); - public static implicit operator DocumentSelector(Collection items) - { - return new DocumentSelector(items); - } + public static implicit operator DocumentSelector(Collection items) => new DocumentSelector(items); - public static implicit operator DocumentSelector(List items) - { - return new DocumentSelector(items); - } + public static implicit operator DocumentSelector(List items) => new DocumentSelector(items); - public static implicit operator string(DocumentSelector documentSelector) - { - return documentSelector != null ? - string.Join(", ", documentSelector.Select(x => (string)x)) : - null; - } + public static implicit operator string(DocumentSelector documentSelector) => + documentSelector != null ? string.Join(", ", documentSelector.Select(x => (string) x)) : null; - public bool IsMatch(TextDocumentAttributes attributes) - { - return this.Any(z => z.IsMatch(attributes)); - } + public bool IsMatch(TextDocumentAttributes attributes) => this.Any(z => z.IsMatch(attributes)); - public override string ToString() - { - return this; - } + public override string ToString() => this; - public static DocumentSelector ForPattern(params string[] wildcards) - { - return new DocumentSelector(wildcards.Select(DocumentFilter.ForPattern)); - } + public static DocumentSelector ForPattern(params string[] wildcards) => new DocumentSelector(wildcards.Select(DocumentFilter.ForPattern)); - public static DocumentSelector ForLanguage(params string[] languages) - { - return new DocumentSelector(languages.Select(DocumentFilter.ForLanguage)); - } + public static DocumentSelector ForLanguage(params string[] languages) => new DocumentSelector(languages.Select(DocumentFilter.ForLanguage)); - public static DocumentSelector ForScheme(params string[] schemes) - { - return new DocumentSelector(schemes.Select(DocumentFilter.ForScheme)); - } + public static DocumentSelector ForScheme(params string[] schemes) => new DocumentSelector(schemes.Select(DocumentFilter.ForScheme)); private string DebuggerDisplay => this; } diff --git a/src/Protocol/Models/DocumentSymbol.cs b/src/Protocol/Models/DocumentSymbol.cs index 0eb9f33f1..a39b0ec47 100644 --- a/src/Protocol/Models/DocumentSymbol.cs +++ b/src/Protocol/Models/DocumentSymbol.cs @@ -64,6 +64,7 @@ public class DocumentSymbol public Container Children { get; set; } private string DebuggerDisplay => $"[{Kind}] {Name} {{ range: {Range}, selection: {SelectionRange}, detail: {Detail ?? string.Empty} }}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/DocumentSymbolParams.cs b/src/Protocol/Models/DocumentSymbolParams.cs index 23b8117c9..2656b6930 100644 --- a/src/Protocol/Models/DocumentSymbolParams.cs +++ b/src/Protocol/Models/DocumentSymbolParams.cs @@ -4,7 +4,8 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { [Method(TextDocumentNames.DocumentSymbol, Direction.ClientToServer)] - public class DocumentSymbolParams : ITextDocumentIdentifierParams, IPartialItemsRequest, IWorkDoneProgressParams + public class DocumentSymbolParams : ITextDocumentIdentifierParams, IPartialItemsRequest, + IWorkDoneProgressParams { /// /// The text document. diff --git a/src/Protocol/Models/DocumentSymbolRegistrationOptions.cs b/src/Protocol/Models/DocumentSymbolRegistrationOptions.cs index 761e74ce5..0cbafb51a 100644 --- a/src/Protocol/Models/DocumentSymbolRegistrationOptions.cs +++ b/src/Protocol/Models/DocumentSymbolRegistrationOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public class DocumentSymbolRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IDocumentSymbolOptions { } + public class DocumentSymbolRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IDocumentSymbolOptions + { + } } diff --git a/src/Protocol/Models/ExitRequest.cs b/src/Protocol/Models/ExitRequest.cs index b3a2d0cff..9a3a301b1 100644 --- a/src/Protocol/Models/ExitRequest.cs +++ b/src/Protocol/Models/ExitRequest.cs @@ -6,7 +6,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [Method(GeneralNames.Exit, Direction.ClientToServer)] public class ExitParams : IRequest { - public ExitParams() {} public static ExitParams Instance { get; } = new ExitParams(); } } diff --git a/src/Protocol/Models/FailureHandlingKind.cs b/src/Protocol/Models/FailureHandlingKind.cs index 32c3ba9cf..b9157d2fb 100644 --- a/src/Protocol/Models/FailureHandlingKind.cs +++ b/src/Protocol/Models/FailureHandlingKind.cs @@ -11,14 +11,14 @@ public enum FailureHandlingKind /// Applying the workspace change is simply aborted if one of the changes provided /// fails. All operations executed before the failing operation stay executed. /// - [EnumMember(Value = "abort")] - Abort, + [EnumMember(Value = "abort")] Abort, + /// /// All operations are executed transactional. That means they either all /// succeed or no changes at all are applied to the workspace. /// - [EnumMember(Value = "transactional")] - Transactional, + [EnumMember(Value = "transactional")] Transactional, + /// /// If the workspace edit contains only textual file changes they are executed transactional. /// If resource changes (create, rename or delete file) are part of the change the failure @@ -26,11 +26,11 @@ public enum FailureHandlingKind /// [EnumMember(Value = "textOnlyTransactional")] TextOnlyTransactional, + /// /// The client tries to undo the operations already executed. But there is no /// guarantee that this is succeeding. /// - [EnumMember(Value = "undo")] - Undo, + [EnumMember(Value = "undo")] Undo, } } diff --git a/src/Protocol/Models/FileChangeType.cs b/src/Protocol/Models/FileChangeType.cs index 1348183eb..b0d22af00 100644 --- a/src/Protocol/Models/FileChangeType.cs +++ b/src/Protocol/Models/FileChangeType.cs @@ -4,21 +4,23 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { /// - /// The file event type. + /// The file event type. /// [JsonConverter(typeof(NumberEnumConverter))] public enum FileChangeType { /// - /// The file got created. + /// The file got created. /// Created = 1, + /// - /// The file got changed. + /// The file got changed. /// Changed = 2, + /// - /// The file got deleted. + /// The file got deleted. /// Deleted = 3, } diff --git a/src/Protocol/Models/FileEvent.cs b/src/Protocol/Models/FileEvent.cs index 4841f400a..1ce6605e5 100644 --- a/src/Protocol/Models/FileEvent.cs +++ b/src/Protocol/Models/FileEvent.cs @@ -3,22 +3,23 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { /// - /// An event describing a file change. + /// An event describing a file change. /// [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public class FileEvent { /// - /// The file's URI. + /// The file's URI. /// public DocumentUri Uri { get; set; } /// - /// The change type. + /// The change type. /// public FileChangeType Type { get; set; } private string DebuggerDisplay => $"[{Type}] {Uri}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/FileSystemWatcher.cs b/src/Protocol/Models/FileSystemWatcher.cs index 0ba792913..a6600f4b9 100644 --- a/src/Protocol/Models/FileSystemWatcher.cs +++ b/src/Protocol/Models/FileSystemWatcher.cs @@ -26,6 +26,7 @@ public class FileSystemWatcher public WatchKind Kind { get; set; } private string DebuggerDisplay => $"[{Kind}] {GlobPattern}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/FoldingRange.cs b/src/Protocol/Models/FoldingRange.cs index 978ea99f5..d423a03e5 100644 --- a/src/Protocol/Models/FoldingRange.cs +++ b/src/Protocol/Models/FoldingRange.cs @@ -39,7 +39,9 @@ public class FoldingRange [Optional] public FoldingRangeKind? Kind { get; set; } - private string DebuggerDisplay => $"[start: (line: {StartLine}{(StartCharacter.HasValue ? $", char: {StartCharacter}" : string.Empty)}), end: (line: {EndLine}, char: {(EndCharacter.HasValue ? $", char: {EndCharacter}" : string.Empty)})]"; + private string DebuggerDisplay => + $"[start: (line: {StartLine}{( StartCharacter.HasValue ? $", char: {StartCharacter}" : string.Empty )}), end: (line: {EndLine}, char: {( EndCharacter.HasValue ? $", char: {EndCharacter}" : string.Empty )})]"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/FoldingRangeKind.cs b/src/Protocol/Models/FoldingRangeKind.cs index bd40a211e..e2fba0a00 100644 --- a/src/Protocol/Models/FoldingRangeKind.cs +++ b/src/Protocol/Models/FoldingRangeKind.cs @@ -13,17 +13,16 @@ public enum FoldingRangeKind /// /// Folding range for a comment /// - [EnumMember(Value="comment")] - Comment, + [EnumMember(Value = "comment")] Comment, + /// /// Folding range for a imports or includes /// - [EnumMember(Value="imports")] - Imports, + [EnumMember(Value = "imports")] Imports, + /// /// Folding range for a region (e.g. `#region`) /// - [EnumMember(Value="region")] - Region + [EnumMember(Value = "region")] Region } } diff --git a/src/Protocol/Models/FoldingRangeRegistrationOptions.cs b/src/Protocol/Models/FoldingRangeRegistrationOptions.cs index fdbe2f7a2..341c990dd 100644 --- a/src/Protocol/Models/FoldingRangeRegistrationOptions.cs +++ b/src/Protocol/Models/FoldingRangeRegistrationOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public class FoldingRangeRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IFoldingRangeOptions { } + public class FoldingRangeRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IFoldingRangeOptions + { + } } diff --git a/src/Protocol/Models/FormattingOptions.cs b/src/Protocol/Models/FormattingOptions.cs index 77c34c1e9..bb18b4f71 100644 --- a/src/Protocol/Models/FormattingOptions.cs +++ b/src/Protocol/Models/FormattingOptions.cs @@ -15,14 +15,8 @@ public class FormattingOptions : Dictionary [JsonIgnore] public long TabSize { - get - { - return this["tabSize"].IsLong ? this["tabSize"].Long : -1; - } - set - { - this["tabSize"] = value; - } + get => this["tabSize"].IsLong ? this["tabSize"].Long : -1; + set => this["tabSize"] = value; } /// @@ -31,14 +25,8 @@ public long TabSize [JsonIgnore] public bool InsertSpaces { - get - { - return this["insertSpaces"].IsBool ? this["insertSpaces"].Bool : false; - } - set - { - this["insertSpaces"] = value; - } + get => this["insertSpaces"].IsBool ? this["insertSpaces"].Bool : false; + set => this["insertSpaces"] = value; } /// @@ -49,14 +37,8 @@ public bool InsertSpaces [JsonIgnore] public bool TrimTrailingWhitespace { - get - { - return this["trimTrailingWhitespace"].IsBool ? this["trimTrailingWhitespace"].Bool : false; - } - set - { - this["trimTrailingWhitespace"] = value; - } + get => this["trimTrailingWhitespace"].IsBool ? this["trimTrailingWhitespace"].Bool : false; + set => this["trimTrailingWhitespace"] = value; } /// @@ -67,14 +49,8 @@ public bool TrimTrailingWhitespace [JsonIgnore] public bool InsertFinalNewline { - get - { - return this["insertFinalNewline"].IsBool ? this["insertFinalNewline"].Bool : false; - } - set - { - this["insertFinalNewline"] = value; - } + get => this["insertFinalNewline"].IsBool ? this["insertFinalNewline"].Bool : false; + set => this["insertFinalNewline"] = value; } /// @@ -85,14 +61,8 @@ public bool InsertFinalNewline [JsonIgnore] public bool TrimFinalNewlines { - get - { - return this["trimFinalNewlines"].IsBool ? this["trimFinalNewlines"].Bool : false; - } - set - { - this["trimFinalNewlines"] = value; - } + get => this["trimFinalNewlines"].IsBool ? this["trimFinalNewlines"].Bool : false; + set => this["trimFinalNewlines"] = value; } } } diff --git a/src/Protocol/Models/HandlerIdentity.cs b/src/Protocol/Models/HandlerIdentity.cs index 445b58097..331c965f0 100644 --- a/src/Protocol/Models/HandlerIdentity.cs +++ b/src/Protocol/Models/HandlerIdentity.cs @@ -5,7 +5,8 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public abstract class HandlerIdentity { - [JsonProperty(Constants.PrivateHandlerId, DefaultValueHandling = DefaultValueHandling.Ignore), EditorBrowsable(EditorBrowsableState.Never)] + [JsonProperty(Constants.PrivateHandlerId, DefaultValueHandling = DefaultValueHandling.Ignore)] + [EditorBrowsable(EditorBrowsableState.Never)] public string __identity { get; set; } } } diff --git a/src/Protocol/Models/Hover.cs b/src/Protocol/Models/Hover.cs index 5f1ceeef4..30b0fbb91 100644 --- a/src/Protocol/Models/Hover.cs +++ b/src/Protocol/Models/Hover.cs @@ -21,7 +21,8 @@ public class Hover [Optional] public Range Range { get; set; } - private string DebuggerDisplay => $"{Contents}{(Range != null ? $" {Range}" : string.Empty)}"; + private string DebuggerDisplay => $"{Contents}{( Range != null ? $" {Range}" : string.Empty )}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/HoverRegistrationOptions.cs b/src/Protocol/Models/HoverRegistrationOptions.cs index 0876721cd..0cd641f2f 100644 --- a/src/Protocol/Models/HoverRegistrationOptions.cs +++ b/src/Protocol/Models/HoverRegistrationOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public class HoverRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IHoverOptions { } + public class HoverRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IHoverOptions + { + } } diff --git a/src/Protocol/Models/ICanBeResolvedHandler.cs b/src/Protocol/Models/ICanBeResolvedHandler.cs index 118a614d7..f479b2069 100644 --- a/src/Protocol/Models/ICanBeResolvedHandler.cs +++ b/src/Protocol/Models/ICanBeResolvedHandler.cs @@ -13,7 +13,8 @@ public interface ICanBeResolvedHandler : IJsonRpcRequestHandler, ICanBe { } - public interface ICanBeResolvedHandler { + public interface ICanBeResolvedHandler + { } public interface ICanBeIdentifiedHandler diff --git a/src/Protocol/Models/IDeclarationOptions.cs b/src/Protocol/Models/IDeclarationOptions.cs index c13a19c60..67bcb7b06 100644 --- a/src/Protocol/Models/IDeclarationOptions.cs +++ b/src/Protocol/Models/IDeclarationOptions.cs @@ -2,6 +2,5 @@ { public interface IDeclarationOptions : IWorkDoneProgressOptions { - } } diff --git a/src/Protocol/Models/IDefinitionOptions.cs b/src/Protocol/Models/IDefinitionOptions.cs index 994cc5813..0e45eca3c 100644 --- a/src/Protocol/Models/IDefinitionOptions.cs +++ b/src/Protocol/Models/IDefinitionOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public interface IDefinitionOptions : IWorkDoneProgressOptions { } + public interface IDefinitionOptions : IWorkDoneProgressOptions + { + } } diff --git a/src/Protocol/Models/IDocumentFormattingOptions.cs b/src/Protocol/Models/IDocumentFormattingOptions.cs index 96ee33f45..603ec73f0 100644 --- a/src/Protocol/Models/IDocumentFormattingOptions.cs +++ b/src/Protocol/Models/IDocumentFormattingOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public interface IDocumentFormattingOptions : IWorkDoneProgressOptions { } + public interface IDocumentFormattingOptions : IWorkDoneProgressOptions + { + } } diff --git a/src/Protocol/Models/IDocumentHighlightOptions.cs b/src/Protocol/Models/IDocumentHighlightOptions.cs index f4c8365e1..d290c2e5d 100644 --- a/src/Protocol/Models/IDocumentHighlightOptions.cs +++ b/src/Protocol/Models/IDocumentHighlightOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public interface IDocumentHighlightOptions : IWorkDoneProgressOptions { } + public interface IDocumentHighlightOptions : IWorkDoneProgressOptions + { + } } diff --git a/src/Protocol/Models/IDocumentRangeFormattingOptions.cs b/src/Protocol/Models/IDocumentRangeFormattingOptions.cs index d6539eb9f..62381d9af 100644 --- a/src/Protocol/Models/IDocumentRangeFormattingOptions.cs +++ b/src/Protocol/Models/IDocumentRangeFormattingOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public interface IDocumentRangeFormattingOptions : IWorkDoneProgressOptions { } + public interface IDocumentRangeFormattingOptions : IWorkDoneProgressOptions + { + } } diff --git a/src/Protocol/Models/IDocumentSymbolOptions.cs b/src/Protocol/Models/IDocumentSymbolOptions.cs index 2bbf086b5..e3feb78d5 100644 --- a/src/Protocol/Models/IDocumentSymbolOptions.cs +++ b/src/Protocol/Models/IDocumentSymbolOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public interface IDocumentSymbolOptions : IWorkDoneProgressOptions { } + public interface IDocumentSymbolOptions : IWorkDoneProgressOptions + { + } } diff --git a/src/Protocol/Models/IDocumentSymbolOptionsOptions.cs b/src/Protocol/Models/IDocumentSymbolOptionsOptions.cs index d50f5a9a8..42c81210e 100644 --- a/src/Protocol/Models/IDocumentSymbolOptionsOptions.cs +++ b/src/Protocol/Models/IDocumentSymbolOptionsOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public interface IDocumentSymbolOptionsOptions : IWorkDoneProgressOptions { } + public interface IDocumentSymbolOptionsOptions : IWorkDoneProgressOptions + { + } } diff --git a/src/Protocol/Models/IFoldingRangeOptions.cs b/src/Protocol/Models/IFoldingRangeOptions.cs index b4ba7fdd6..669c29c5c 100644 --- a/src/Protocol/Models/IFoldingRangeOptions.cs +++ b/src/Protocol/Models/IFoldingRangeOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public interface IFoldingRangeOptions : IWorkDoneProgressOptions { } + public interface IFoldingRangeOptions : IWorkDoneProgressOptions + { + } } diff --git a/src/Protocol/Models/IHoverOptions.cs b/src/Protocol/Models/IHoverOptions.cs index 352d0004b..ab0b5598b 100644 --- a/src/Protocol/Models/IHoverOptions.cs +++ b/src/Protocol/Models/IHoverOptions.cs @@ -2,6 +2,5 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public interface IHoverOptions : IWorkDoneProgressOptions { - } } diff --git a/src/Protocol/Models/IImplementationOptions.cs b/src/Protocol/Models/IImplementationOptions.cs index fc051b2fd..53c38b860 100644 --- a/src/Protocol/Models/IImplementationOptions.cs +++ b/src/Protocol/Models/IImplementationOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public interface IImplementationOptions : IWorkDoneProgressOptions { } + public interface IImplementationOptions : IWorkDoneProgressOptions + { + } } diff --git a/src/Protocol/Models/IPartialItem.cs b/src/Protocol/Models/IPartialItem.cs index 0cbdbddff..7adba645a 100644 --- a/src/Protocol/Models/IPartialItem.cs +++ b/src/Protocol/Models/IPartialItem.cs @@ -12,5 +12,8 @@ public interface IPartialItem [Optional] ProgressToken PartialResultToken { get; set; } } - public interface IPartialItemRequest : IRequest, IPartialItem { } + + public interface IPartialItemRequest : IRequest, IPartialItem + { + } } diff --git a/src/Protocol/Models/IReferencesOptions.cs b/src/Protocol/Models/IReferencesOptions.cs index eccf1e24e..dd7decc67 100644 --- a/src/Protocol/Models/IReferencesOptions.cs +++ b/src/Protocol/Models/IReferencesOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public interface IReferencesOptions : IWorkDoneProgressOptions { } + public interface IReferencesOptions : IWorkDoneProgressOptions + { + } } diff --git a/src/Protocol/Models/ISelectionRangeOptions.cs b/src/Protocol/Models/ISelectionRangeOptions.cs index 4609f65d9..fae5d498a 100644 --- a/src/Protocol/Models/ISelectionRangeOptions.cs +++ b/src/Protocol/Models/ISelectionRangeOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public interface ISelectionRangeOptions : IWorkDoneProgressOptions { } + public interface ISelectionRangeOptions : IWorkDoneProgressOptions + { + } } diff --git a/src/Protocol/Models/ITypeDefinitionOptions.cs b/src/Protocol/Models/ITypeDefinitionOptions.cs index 45fab8dd6..2ff9ef52a 100644 --- a/src/Protocol/Models/ITypeDefinitionOptions.cs +++ b/src/Protocol/Models/ITypeDefinitionOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public interface ITypeDefinitionOptions : IWorkDoneProgressOptions { } + public interface ITypeDefinitionOptions : IWorkDoneProgressOptions + { + } } diff --git a/src/Protocol/Models/IWorkDoneProgressOptions.cs b/src/Protocol/Models/IWorkDoneProgressOptions.cs index 0a6f3c834..90d83ebb6 100644 --- a/src/Protocol/Models/IWorkDoneProgressOptions.cs +++ b/src/Protocol/Models/IWorkDoneProgressOptions.cs @@ -4,7 +4,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public interface IWorkDoneProgressOptions { - [Optional] - bool WorkDoneProgress { get; set; } + [Optional] bool WorkDoneProgress { get; set; } } } diff --git a/src/Protocol/Models/IWorkspaceFolderOptions.cs b/src/Protocol/Models/IWorkspaceFolderOptions.cs index 81b74e5c4..03c896b24 100644 --- a/src/Protocol/Models/IWorkspaceFolderOptions.cs +++ b/src/Protocol/Models/IWorkspaceFolderOptions.cs @@ -9,6 +9,7 @@ public interface IWorkspaceFolderOptions /// [Optional] bool Supported { get; set; } + /// /// Whether the server wants to receive workspace folder /// change notifications. diff --git a/src/Protocol/Models/IWorkspaceSymbolOptions.cs b/src/Protocol/Models/IWorkspaceSymbolOptions.cs index 2239ffc0f..b7a218a5f 100644 --- a/src/Protocol/Models/IWorkspaceSymbolOptions.cs +++ b/src/Protocol/Models/IWorkspaceSymbolOptions.cs @@ -2,6 +2,5 @@ { public interface IWorkspaceSymbolOptions : IWorkDoneProgressOptions { - } } diff --git a/src/Protocol/Models/ImplementationRegistrationOptions.cs b/src/Protocol/Models/ImplementationRegistrationOptions.cs index cad62d02b..44af4d48c 100644 --- a/src/Protocol/Models/ImplementationRegistrationOptions.cs +++ b/src/Protocol/Models/ImplementationRegistrationOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public class ImplementationRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, ITypeDefinitionOptions { } + public class ImplementationRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, ITypeDefinitionOptions + { + } } diff --git a/src/Protocol/Models/InitializeParams.cs b/src/Protocol/Models/InitializeParams.cs index 9f0c595d1..9df72245e 100644 --- a/src/Protocol/Models/InitializeParams.cs +++ b/src/Protocol/Models/InitializeParams.cs @@ -32,8 +32,8 @@ public class InitializeParams : IWorkDoneProgressParams, IRequest RootUri?.GetFileSystemPath(); + set => RootUri = value == null ? null : DocumentUri.FromFileSystemPath(value); } /// @@ -64,9 +64,9 @@ public string RootPath /// This property is only available if the client supports workspace folders. /// It can be `null` if the client supports workspace folders but none are /// configured. - /// + /// /// Since 3.6.0 - /// + /// public Container WorkspaceFolders { get; set; } /// diff --git a/src/Protocol/Models/InitializeResult.cs b/src/Protocol/Models/InitializeResult.cs index b938f1331..46c9b8758 100644 --- a/src/Protocol/Models/InitializeResult.cs +++ b/src/Protocol/Models/InitializeResult.cs @@ -11,9 +11,9 @@ public class InitializeResult public ServerCapabilities Capabilities { get; set; } /// - /// Information about the server. - /// - /// @since 3.15.0 + /// Information about the server. + /// + /// @since 3.15.0 /// [Optional] public ServerInfo ServerInfo { get; set; } diff --git a/src/Protocol/Models/InitializeTrace.cs b/src/Protocol/Models/InitializeTrace.cs index d9d55d723..06ccd7a0f 100644 --- a/src/Protocol/Models/InitializeTrace.cs +++ b/src/Protocol/Models/InitializeTrace.cs @@ -7,11 +7,8 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [JsonConverter(typeof(StringEnumConverter))] public enum InitializeTrace { - [EnumMember(Value="off")] - Off, - [EnumMember(Value="messages")] - Messages, - [EnumMember(Value="verbose")] - Verbose + [EnumMember(Value = "off")] Off, + [EnumMember(Value = "messages")] Messages, + [EnumMember(Value = "verbose")] Verbose } } diff --git a/src/Protocol/Models/Location.cs b/src/Protocol/Models/Location.cs index 51a42db9a..092160eb2 100644 --- a/src/Protocol/Models/Location.cs +++ b/src/Protocol/Models/Location.cs @@ -17,17 +17,12 @@ public class Location : IEquatable /// public Range Range { get; set; } - public override bool Equals(object obj) - { - return Equals(obj as Location); - } + public override bool Equals(object obj) => Equals(obj as Location); - public bool Equals(Location other) - { - return other != null && - DocumentUri.Comparer.Equals(Uri, other.Uri) && - EqualityComparer.Default.Equals(Range, other.Range); - } + public bool Equals(Location other) => + other != null && + DocumentUri.Comparer.Equals(Uri, other.Uri) && + EqualityComparer.Default.Equals(Range, other.Range); public override int GetHashCode() { @@ -37,17 +32,12 @@ public override int GetHashCode() return hashCode; } - public static bool operator ==(Location location1, Location location2) - { - return EqualityComparer.Default.Equals(location1, location2); - } + public static bool operator ==(Location location1, Location location2) => EqualityComparer.Default.Equals(location1, location2); - public static bool operator !=(Location location1, Location location2) - { - return !(location1 == location2); - } + public static bool operator !=(Location location1, Location location2) => !( location1 == location2 ); private string DebuggerDisplay => $"{{{Range} {Uri}}}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/LocationContainer.cs b/src/Protocol/Models/LocationContainer.cs index ed4db7cb8..c3e947811 100644 --- a/src/Protocol/Models/LocationContainer.cs +++ b/src/Protocol/Models/LocationContainer.cs @@ -18,19 +18,10 @@ public LocationContainer(params Location[] items) : base(items) { } - public static implicit operator LocationContainer(Location[] items) - { - return new LocationContainer(items); - } + public static implicit operator LocationContainer(Location[] items) => new LocationContainer(items); - public static implicit operator LocationContainer(Collection items) - { - return new LocationContainer(items); - } + public static implicit operator LocationContainer(Collection items) => new LocationContainer(items); - public static implicit operator LocationContainer(List items) - { - return new LocationContainer(items); - } + public static implicit operator LocationContainer(List items) => new LocationContainer(items); } } diff --git a/src/Protocol/Models/LocationOrLocationLink.cs b/src/Protocol/Models/LocationOrLocationLink.cs index 23e21652b..a86661811 100644 --- a/src/Protocol/Models/LocationOrLocationLink.cs +++ b/src/Protocol/Models/LocationOrLocationLink.cs @@ -4,8 +4,8 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { [JsonConverter(typeof(LocationOrLocationLinkConverter))] - public struct LocationOrLocationLink { - + public struct LocationOrLocationLink + { public LocationOrLocationLink(Location location) { Location = location; @@ -24,14 +24,8 @@ public LocationOrLocationLink(LocationLink locationLink) public bool IsLocationLink => LocationLink != null; public LocationLink LocationLink { get; } - public static implicit operator LocationOrLocationLink(Location location) - { - return new LocationOrLocationLink(location); - } + public static implicit operator LocationOrLocationLink(Location location) => new LocationOrLocationLink(location); - public static implicit operator LocationOrLocationLink(LocationLink locationLink) - { - return new LocationOrLocationLink(locationLink); - } + public static implicit operator LocationOrLocationLink(LocationLink locationLink) => new LocationOrLocationLink(locationLink); } } diff --git a/src/Protocol/Models/LocationOrLocationLinks.cs b/src/Protocol/Models/LocationOrLocationLinks.cs index 8538610a4..3e271c650 100644 --- a/src/Protocol/Models/LocationOrLocationLinks.cs +++ b/src/Protocol/Models/LocationOrLocationLinks.cs @@ -21,19 +21,10 @@ public LocationOrLocationLinks(params LocationOrLocationLink[] items) : base(ite { } - public static implicit operator LocationOrLocationLinks(LocationOrLocationLink[] items) - { - return new LocationOrLocationLinks(items); - } + public static implicit operator LocationOrLocationLinks(LocationOrLocationLink[] items) => new LocationOrLocationLinks(items); - public static implicit operator LocationOrLocationLinks(Collection items) - { - return new LocationOrLocationLinks(items); - } + public static implicit operator LocationOrLocationLinks(Collection items) => new LocationOrLocationLinks(items); - public static implicit operator LocationOrLocationLinks(List items) - { - return new LocationOrLocationLinks(items); - } + public static implicit operator LocationOrLocationLinks(List items) => new LocationOrLocationLinks(items); } } diff --git a/src/Protocol/Models/LogMessageParams.cs b/src/Protocol/Models/LogMessageParams.cs index cecb0bc70..cfe5ec77c 100644 --- a/src/Protocol/Models/LogMessageParams.cs +++ b/src/Protocol/Models/LogMessageParams.cs @@ -7,12 +7,12 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models public class LogMessageParams : IRequest { /// - /// The message type. See {@link MessageType} + /// The message type. See {@link MessageType} /// public MessageType Type { get; set; } /// - /// The actual message + /// The actual message /// public string Message { get; set; } } diff --git a/src/Protocol/Models/MarkedString.cs b/src/Protocol/Models/MarkedString.cs index ec299ec20..8dbbd4ddd 100644 --- a/src/Protocol/Models/MarkedString.cs +++ b/src/Protocol/Models/MarkedString.cs @@ -22,27 +22,18 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public class MarkedString { - public MarkedString(string value) - { - Value = value; - } + public MarkedString(string value) => Value = value; - public MarkedString(string language, string value) : this(value) - { - Language = language; - } + public MarkedString(string language, string value) : this(value) => Language = language; - [Optional] - public string Language { get; } + [Optional] public string Language { get; } public string Value { get; } - public static implicit operator MarkedString(string value) - { - return new MarkedString(value); - } + public static implicit operator MarkedString(string value) => new MarkedString(value); + + private string DebuggerDisplay => $"{( string.IsNullOrWhiteSpace(Language) ? string.Empty : $"[{Language}] " )}{Value}"; - private string DebuggerDisplay => $"{(string.IsNullOrWhiteSpace(Language) ? string.Empty : $"[{Language}] ")}{Value}"; /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/MarkedStringsOrMarkupContent.cs b/src/Protocol/Models/MarkedStringsOrMarkupContent.cs index 5adec3d77..1b249cfc8 100644 --- a/src/Protocol/Models/MarkedStringsOrMarkupContent.cs +++ b/src/Protocol/Models/MarkedStringsOrMarkupContent.cs @@ -10,27 +10,20 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public class MarkedStringsOrMarkupContent { - public MarkedStringsOrMarkupContent(params MarkedString[] markedStrings) - { - MarkedStrings = markedStrings; - } + public MarkedStringsOrMarkupContent(params MarkedString[] markedStrings) => MarkedStrings = markedStrings; - public MarkedStringsOrMarkupContent(IEnumerable markedStrings) - { - MarkedStrings = markedStrings.ToArray(); - } + public MarkedStringsOrMarkupContent(IEnumerable markedStrings) => MarkedStrings = markedStrings.ToArray(); - public MarkedStringsOrMarkupContent(MarkupContent markupContent) - { - MarkupContent = markupContent; - } + public MarkedStringsOrMarkupContent(MarkupContent markupContent) => MarkupContent = markupContent; public Container MarkedStrings { get; } public bool HasMarkedStrings => MarkupContent == null; public MarkupContent MarkupContent { get; } public bool HasMarkupContent => MarkedStrings == null; - private string DebuggerDisplay => $"{(HasMarkedStrings ? string.Join(" ", MarkedStrings.Select(z => z.ToString())) : HasMarkupContent ? MarkupContent.ToString() : string.Empty)}"; + private string DebuggerDisplay => + $"{( HasMarkedStrings ? string.Join(" ", MarkedStrings.Select(z => z.ToString())) : HasMarkupContent ? MarkupContent.ToString() : string.Empty )}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/MarkupContent.cs b/src/Protocol/Models/MarkupContent.cs index 4d0e72b6b..c3d018bba 100644 --- a/src/Protocol/Models/MarkupContent.cs +++ b/src/Protocol/Models/MarkupContent.cs @@ -5,24 +5,24 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models /// /// A `MarkupContent` literal represents a string value which content is interpreted base on its /// kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds. - /// + /// /// If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues. /// See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting - /// + /// /// Here is an example how such a string can be constructed using JavaScript / TypeScript: /// ```ts /// let markdown: MarkdownContent = { - /// kind: MarkupKind.Markdown, + /// kind: MarkupKind.Markdown, /// value: [ - /// '# Header', - /// 'Some text', - /// '```typescript', - /// 'someCode();', - /// '```' + /// '# Header', + /// 'Some text', + /// '```typescript', + /// 'someCode();', + /// '```' /// ].join('\n') /// }; /// ``` - /// + /// /// *Please Note* that clients might sanitize the return markdown. A client could decide to /// remove HTML from the markdown to avoid script execution. /// @@ -40,6 +40,7 @@ public class MarkupContent public string Value { get; set; } private string DebuggerDisplay => $"[{Kind}] {Value}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/MarkupKind.cs b/src/Protocol/Models/MarkupKind.cs index 7a9ffe9ce..d354f408f 100644 --- a/src/Protocol/Models/MarkupKind.cs +++ b/src/Protocol/Models/MarkupKind.cs @@ -17,12 +17,11 @@ public enum MarkupKind /// /// Plain text is supported as a content format /// - [EnumMember(Value="plaintext")] - PlainText, // Only capitalize the first letter because the above converter will only lower case the first letter today + [EnumMember(Value = "plaintext")] PlainText, // Only capitalize the first letter because the above converter will only lower case the first letter today + /// /// Markdown is supported as a content format /// - [EnumMember(Value="markdown")] - Markdown, + [EnumMember(Value = "markdown")] Markdown, } } diff --git a/src/Protocol/Models/MessageActionItem.cs b/src/Protocol/Models/MessageActionItem.cs index daa71f5dc..5324a7c46 100644 --- a/src/Protocol/Models/MessageActionItem.cs +++ b/src/Protocol/Models/MessageActionItem.cs @@ -6,11 +6,12 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models public class MessageActionItem { /// - /// A short title like 'Retry', 'Open Log' etc. + /// A short title like 'Retry', 'Open Log' etc. /// public string Title { get; set; } private string DebuggerDisplay => Title; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/MessageType.cs b/src/Protocol/Models/MessageType.cs index 0d4001f98..dd2a8aadc 100644 --- a/src/Protocol/Models/MessageType.cs +++ b/src/Protocol/Models/MessageType.cs @@ -7,19 +7,22 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models public enum MessageType { /// - /// An error message. + /// An error message. /// Error = 1, + /// - /// A warning message. + /// A warning message. /// Warning = 2, + /// - /// An information message. + /// An information message. /// Info = 3, + /// - /// A log message. + /// A log message. /// Log = 4, } diff --git a/src/Protocol/Models/ParameterInformation.cs b/src/Protocol/Models/ParameterInformation.cs index 5759ce719..e53badc47 100644 --- a/src/Protocol/Models/ParameterInformation.cs +++ b/src/Protocol/Models/ParameterInformation.cs @@ -23,7 +23,8 @@ public class ParameterInformation [Optional] public StringOrMarkupContent Documentation { get; set; } - private string DebuggerDisplay => $"{Label}{(Documentation != null ? $" {Documentation}" : string.Empty)}"; + private string DebuggerDisplay => $"{Label}{( Documentation != null ? $" {Documentation}" : string.Empty )}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/ParameterInformationLabel.cs b/src/Protocol/Models/ParameterInformationLabel.cs index 557b85f20..7803a95f8 100644 --- a/src/Protocol/Models/ParameterInformationLabel.cs +++ b/src/Protocol/Models/ParameterInformationLabel.cs @@ -8,32 +8,21 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public class 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) - { - return new ParameterInformationLabel(label); - } + public static implicit operator ParameterInformationLabel(string label) => new ParameterInformationLabel(label); - public static implicit operator ParameterInformationLabel((int start, int end) range) - { - return new ParameterInformationLabel(range); - } + public static implicit operator ParameterInformationLabel((int start, int end) range) => new ParameterInformationLabel(range); private string DebuggerDisplay => IsRange ? $"(start: {Range.start}, end: {Range.end})" : IsLabel ? Label : string.Empty; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/Position.cs b/src/Protocol/Models/Position.cs index 90569d6a7..6fd070180 100644 --- a/src/Protocol/Models/Position.cs +++ b/src/Protocol/Models/Position.cs @@ -9,7 +9,6 @@ public class Position : IEquatable { public Position() { - } public Position(int line, int character) @@ -17,6 +16,7 @@ public Position(int line, int character) Line = line; Character = character; } + /// /// Line position in a document (zero-based). /// @@ -27,17 +27,12 @@ public Position(int line, int character) /// public int Character { get; set; } - public override bool Equals(object obj) - { - return Equals(obj as Position); - } + public override bool Equals(object obj) => Equals(obj as Position); - public bool Equals(Position other) - { - return other != null && - Line == other.Line && - Character == other.Character; - } + public bool Equals(Position other) => + other != null && + Line == other.Line && + Character == other.Character; public override int GetHashCode() { @@ -47,22 +42,14 @@ public override int GetHashCode() return hashCode; } - public static bool operator ==(Position position1, Position position2) - { - return EqualityComparer.Default.Equals(position1, position2); - } + public static bool operator ==(Position position1, Position position2) => EqualityComparer.Default.Equals(position1, position2); - public static bool operator !=(Position position1, Position position2) - { - return !(position1 == position2); - } + public static bool operator !=(Position position1, Position position2) => !( position1 == position2 ); - public static implicit operator Position((int line, int character) value) - { - return new Position(value.line, value.character); - } + public static implicit operator Position((int line, int character) value) => new Position(value.line, value.character); private string DebuggerDisplay => $"(line: {Line}, char: {Character})"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/ProgressParams.cs b/src/Protocol/Models/ProgressParams.cs index b7a50f3cd..c302c211d 100644 --- a/src/Protocol/Models/ProgressParams.cs +++ b/src/Protocol/Models/ProgressParams.cs @@ -8,14 +8,11 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [Method(GeneralNames.Progress, Direction.Bidirectional)] public class ProgressParams : IRequest { - public static ProgressParams Create(ProgressToken token, T value, JsonSerializer jsonSerializer) - { - return new ProgressParams() - { + public static ProgressParams Create(ProgressToken token, T value, JsonSerializer jsonSerializer) => + new ProgressParams { Token = token, Value = JToken.FromObject(value, jsonSerializer) }; - } /// /// The progress token provided by the client or server. diff --git a/src/Protocol/Models/ProgressToken.cs b/src/Protocol/Models/ProgressToken.cs index 87f545983..0bddcbc9b 100644 --- a/src/Protocol/Models/ProgressToken.cs +++ b/src/Protocol/Models/ProgressToken.cs @@ -18,6 +18,7 @@ public ProgressToken(long value) _long = value; _string = null; } + public ProgressToken(string value) { _long = null; @@ -25,6 +26,7 @@ public ProgressToken(string value) } public bool IsLong => _long.HasValue; + public long Long { get => _long ?? 0; @@ -35,6 +37,7 @@ public long Long } public bool IsString => _string != null; + public string String { get => _string; @@ -44,26 +47,15 @@ public string String } } - public static implicit operator ProgressToken(long value) - { - return new ProgressToken(value); - } + public static implicit operator ProgressToken(long value) => new ProgressToken(value); - public static implicit operator ProgressToken(string value) - { - return new ProgressToken(value); - } + public static implicit operator ProgressToken(string value) => new ProgressToken(value); - public ProgressParams Create(T value, JsonSerializer jsonSerializer) - { - return ProgressParams.Create(this, value, jsonSerializer); - } + public ProgressParams Create(T value, JsonSerializer jsonSerializer) => ProgressParams.Create(this, value, jsonSerializer); - public override bool Equals(object obj) - { - return obj is ProgressToken token && - this.Equals(token); - } + public override bool Equals(object obj) => + obj is ProgressToken token && + Equals(token); public override int GetHashCode() { @@ -75,25 +67,18 @@ public override int GetHashCode() return hashCode; } - public bool Equals(ProgressToken other) - { - return IsLong == other.IsLong && - Long == other.Long && - IsString == other.IsString && - String == other.String; - } + public bool Equals(ProgressToken other) => + IsLong == other.IsLong && + Long == other.Long && + IsString == other.IsString && + String == other.String; - public bool Equals(long other) - { - return this.IsLong && this.Long == other; - } + public bool Equals(long other) => IsLong && Long == other; - public bool Equals(string other) - { - return this.IsString && this.String == other; - } + public bool Equals(string other) => IsString && String == other; private string DebuggerDisplay => IsString ? String : IsLong ? Long.ToString() : ""; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/Proposals/CallHierarchyOptions.cs b/src/Protocol/Models/Proposals/CallHierarchyOptions.cs index 6d2486a0b..784e63e1e 100644 --- a/src/Protocol/Models/Proposals/CallHierarchyOptions.cs +++ b/src/Protocol/Models/Proposals/CallHierarchyOptions.cs @@ -12,11 +12,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals [Obsolete(Constants.Proposal)] public class CallHierarchyOptions : WorkDoneProgressOptions, ICallHierarchyOptions { - public static CallHierarchyOptions Of(ICallHierarchyOptions options, IEnumerable descriptors) - { - return new CallHierarchyOptions() { + public static CallHierarchyOptions Of(ICallHierarchyOptions options, IEnumerable descriptors) => + new CallHierarchyOptions { WorkDoneProgress = options.WorkDoneProgress, }; - } } } diff --git a/src/Protocol/Models/Proposals/CallHierarchyOutgoingCallsParams.cs b/src/Protocol/Models/Proposals/CallHierarchyOutgoingCallsParams.cs index d72a67f5c..3f1cb6513 100644 --- a/src/Protocol/Models/Proposals/CallHierarchyOutgoingCallsParams.cs +++ b/src/Protocol/Models/Proposals/CallHierarchyOutgoingCallsParams.cs @@ -10,7 +10,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals /// [Obsolete(Constants.Proposal)] [Method(TextDocumentNames.CallHierarchyOutgoing, Direction.ClientToServer)] - public class CallHierarchyOutgoingCallsParams : IWorkDoneProgressParams, IPartialItemsRequest + public class CallHierarchyOutgoingCallsParams : IWorkDoneProgressParams, IPartialItemsRequest { public CallHierarchyItem Item { get; set; } public ProgressToken WorkDoneToken { get; set; } diff --git a/src/Protocol/Models/Proposals/ISemanticTokensOptions.cs b/src/Protocol/Models/Proposals/ISemanticTokensOptions.cs index 726c96dcf..614f6e0d7 100644 --- a/src/Protocol/Models/Proposals/ISemanticTokensOptions.cs +++ b/src/Protocol/Models/Proposals/ISemanticTokensOptions.cs @@ -13,20 +13,20 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals public interface ISemanticTokensOptions : IWorkDoneProgressOptions { /// - /// The legend used by the server + /// The legend used by the server /// public SemanticTokensLegend Legend { get; set; } /// - /// Server supports providing semantic tokens for a sepcific range - /// of a document. + /// Server supports providing semantic tokens for a sepcific range + /// of a document. /// [Optional] public BooleanOr Range { get; set; } /// - /// Server supports providing semantic tokens for a full document. + /// Server supports providing semantic tokens for a full document. /// [Optional] public BooleanOr Full { get; set; } diff --git a/src/Protocol/Models/Proposals/SemanticTokenFormat.cs b/src/Protocol/Models/Proposals/SemanticTokenFormat.cs index 4a6045499..6677e9f4d 100644 --- a/src/Protocol/Models/Proposals/SemanticTokenFormat.cs +++ b/src/Protocol/Models/Proposals/SemanticTokenFormat.cs @@ -23,11 +23,12 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals new Lazy>( () => { return typeof(SemanticTokenFormat) - .GetFields(BindingFlags.Static | BindingFlags.Public) - .Select(z => z.GetValue(null)) - .Cast() - .ToArray(); - }); + .GetFields(BindingFlags.Static | BindingFlags.Public) + .Select(z => z.GetValue(null)) + .Cast() + .ToArray(); + } + ); public static IEnumerable Defaults => _defaults.Value; @@ -35,27 +36,18 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals private readonly string _value; - public SemanticTokenFormat(string modifier) - { - _value = modifier; - } + public SemanticTokenFormat(string modifier) => _value = modifier; - public static implicit operator SemanticTokenFormat(string kind) - { - return new SemanticTokenFormat(kind); - } + public static implicit operator SemanticTokenFormat(string kind) => new SemanticTokenFormat(kind); - public static implicit operator string(SemanticTokenFormat kind) - { - return kind._value; - } + public static implicit operator string(SemanticTokenFormat kind) => kind._value; public override string ToString() => _value; public bool Equals(SemanticTokenFormat other) => _value == other._value; public override bool Equals(object obj) => obj is SemanticTokenFormat other && Equals(other); - public override int GetHashCode() => (_value != null ? _value.GetHashCode() : 0); + public override int GetHashCode() => _value != null ? _value.GetHashCode() : 0; public static bool operator ==(SemanticTokenFormat left, SemanticTokenFormat right) => left.Equals(right); diff --git a/src/Protocol/Models/Proposals/SemanticTokenModifiers.cs b/src/Protocol/Models/Proposals/SemanticTokenModifiers.cs index 12b15afa3..075f4bf0a 100644 --- a/src/Protocol/Models/Proposals/SemanticTokenModifiers.cs +++ b/src/Protocol/Models/Proposals/SemanticTokenModifiers.cs @@ -24,11 +24,12 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals new Lazy>( () => { return typeof(SemanticTokenModifier) - .GetFields(BindingFlags.Static | BindingFlags.Public) - .Select(z => z.GetValue(null)) - .Cast() - .ToArray(); - }); + .GetFields(BindingFlags.Static | BindingFlags.Public) + .Select(z => z.GetValue(null)) + .Cast() + .ToArray(); + } + ); public static IEnumerable Defaults => _defaults.Value; @@ -45,27 +46,18 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals private readonly string _value; - public SemanticTokenModifier(string modifier) - { - _value = modifier; - } + public SemanticTokenModifier(string modifier) => _value = modifier; - public static implicit operator SemanticTokenModifier(string kind) - { - return new SemanticTokenModifier(kind); - } + public static implicit operator SemanticTokenModifier(string kind) => new SemanticTokenModifier(kind); - public static implicit operator string(SemanticTokenModifier kind) - { - return kind._value; - } + public static implicit operator string(SemanticTokenModifier kind) => kind._value; public override string ToString() => _value; public bool Equals(SemanticTokenModifier other) => _value == other._value; public override bool Equals(object obj) => obj is SemanticTokenModifier other && Equals(other); - public override int GetHashCode() => (_value != null ? _value.GetHashCode() : 0); + public override int GetHashCode() => _value != null ? _value.GetHashCode() : 0; public static bool operator ==(SemanticTokenModifier left, SemanticTokenModifier right) => left.Equals(right); diff --git a/src/Protocol/Models/Proposals/SemanticTokenTypes.cs b/src/Protocol/Models/Proposals/SemanticTokenTypes.cs index 2b19f7714..8b66493a0 100644 --- a/src/Protocol/Models/Proposals/SemanticTokenTypes.cs +++ b/src/Protocol/Models/Proposals/SemanticTokenTypes.cs @@ -24,11 +24,12 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals new Lazy>( () => { return typeof(SemanticTokenType) - .GetFields(BindingFlags.Static | BindingFlags.Public) - .Select(z => z.GetValue(null)) - .Cast() - .ToArray(); - }); + .GetFields(BindingFlags.Static | BindingFlags.Public) + .Select(z => z.GetValue(null)) + .Cast() + .ToArray(); + } + ); public static IEnumerable Defaults => _defaults.Value; @@ -58,27 +59,18 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals private readonly string _value; - public SemanticTokenType(string type) - { - _value = type; - } + public SemanticTokenType(string type) => _value = type; - public static implicit operator SemanticTokenType(string kind) - { - return new SemanticTokenType(kind); - } + public static implicit operator SemanticTokenType(string kind) => new SemanticTokenType(kind); - public static implicit operator string(SemanticTokenType kind) - { - return kind._value; - } + public static implicit operator string(SemanticTokenType kind) => kind._value; public override string ToString() => _value; public bool Equals(SemanticTokenType other) => _value == other._value; public override bool Equals(object obj) => obj is SemanticTokenType other && Equals(other); - public override int GetHashCode() => (_value != null ? _value.GetHashCode() : 0); + public override int GetHashCode() => _value != null ? _value.GetHashCode() : 0; public static bool operator ==(SemanticTokenType left, SemanticTokenType right) => left.Equals(right); diff --git a/src/Protocol/Models/Proposals/SemanticTokensDeltaParams.cs b/src/Protocol/Models/Proposals/SemanticTokensDeltaParams.cs index fa809cdf5..617599ec2 100644 --- a/src/Protocol/Models/Proposals/SemanticTokensDeltaParams.cs +++ b/src/Protocol/Models/Proposals/SemanticTokensDeltaParams.cs @@ -9,7 +9,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals [Obsolete(Constants.Proposal)] [Method(TextDocumentNames.SemanticTokensFullDelta, Direction.ClientToServer)] public class SemanticTokensDeltaParams : IWorkDoneProgressParams, ITextDocumentIdentifierParams, - IPartialItemRequest + IPartialItemRequest { /// /// The text document. diff --git a/src/Protocol/Models/Proposals/SemanticTokensDeltaPartialResult.cs b/src/Protocol/Models/Proposals/SemanticTokensDeltaPartialResult.cs index 5a678d07c..9b445d545 100644 --- a/src/Protocol/Models/Proposals/SemanticTokensDeltaPartialResult.cs +++ b/src/Protocol/Models/Proposals/SemanticTokensDeltaPartialResult.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Immutable; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals { diff --git a/src/Protocol/Models/Proposals/SemanticTokensFullOrDelta.cs b/src/Protocol/Models/Proposals/SemanticTokensFullOrDelta.cs index 671874273..a4b26c090 100644 --- a/src/Protocol/Models/Proposals/SemanticTokensFullOrDelta.cs +++ b/src/Protocol/Models/Proposals/SemanticTokensFullOrDelta.cs @@ -26,14 +26,8 @@ public SemanticTokensFullOrDelta(SemanticTokens full) public bool IsDelta => Delta != null; public SemanticTokensDelta Delta { get; } - public static implicit operator SemanticTokensFullOrDelta(SemanticTokensDelta semanticTokensDelta) - { - return new SemanticTokensFullOrDelta(semanticTokensDelta); - } + public static implicit operator SemanticTokensFullOrDelta(SemanticTokensDelta semanticTokensDelta) => new SemanticTokensFullOrDelta(semanticTokensDelta); - public static implicit operator SemanticTokensFullOrDelta(SemanticTokens semanticTokens) - { - return new SemanticTokensFullOrDelta(semanticTokens); - } + public static implicit operator SemanticTokensFullOrDelta(SemanticTokens semanticTokens) => new SemanticTokensFullOrDelta(semanticTokens); } } diff --git a/src/Protocol/Models/Proposals/SemanticTokensFullOrDeltaPartialResult.cs b/src/Protocol/Models/Proposals/SemanticTokensFullOrDeltaPartialResult.cs index 790240359..2f830e8c0 100644 --- a/src/Protocol/Models/Proposals/SemanticTokensFullOrDeltaPartialResult.cs +++ b/src/Protocol/Models/Proposals/SemanticTokensFullOrDeltaPartialResult.cs @@ -9,14 +9,16 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals public struct SemanticTokensFullOrDeltaPartialResult { public SemanticTokensFullOrDeltaPartialResult( - SemanticTokensPartialResult full) + SemanticTokensPartialResult full + ) { Full = full; Delta = null; } public SemanticTokensFullOrDeltaPartialResult( - SemanticTokensDeltaPartialResult delta) + SemanticTokensDeltaPartialResult delta + ) { Full = null; Delta = delta; @@ -28,14 +30,10 @@ public SemanticTokensFullOrDeltaPartialResult( public bool IsFull => Full != null; public SemanticTokensPartialResult Full { get; } - public static implicit operator SemanticTokensFullOrDeltaPartialResult(SemanticTokensPartialResult semanticTokensPartialResult) - { - return new SemanticTokensFullOrDeltaPartialResult(semanticTokensPartialResult); - } + public static implicit operator SemanticTokensFullOrDeltaPartialResult(SemanticTokensPartialResult semanticTokensPartialResult) => + new SemanticTokensFullOrDeltaPartialResult(semanticTokensPartialResult); - public static implicit operator SemanticTokensFullOrDeltaPartialResult(SemanticTokensDeltaPartialResult semanticTokensDeltaPartialResult) - { - return new SemanticTokensFullOrDeltaPartialResult(semanticTokensDeltaPartialResult); - } + public static implicit operator SemanticTokensFullOrDeltaPartialResult(SemanticTokensDeltaPartialResult semanticTokensDeltaPartialResult) => + new SemanticTokensFullOrDeltaPartialResult(semanticTokensDeltaPartialResult); } } diff --git a/src/Protocol/Models/Proposals/SemanticTokensLegend.cs b/src/Protocol/Models/Proposals/SemanticTokensLegend.cs index 7f8afd6a2..4ede2f348 100644 --- a/src/Protocol/Models/Proposals/SemanticTokensLegend.cs +++ b/src/Protocol/Models/Proposals/SemanticTokensLegend.cs @@ -14,17 +14,19 @@ public class SemanticTokensLegend private ImmutableDictionary _tokenModifiersData; private ImmutableDictionary _tokenTypesData; - private Container _tokenTypes = new Container(SemanticTokenType - .Defaults - .Select(z => (string) z) - .ToArray() + private Container _tokenTypes = new Container( + SemanticTokenType + .Defaults + .Select(z => (string) z) + .ToArray() ); private Container _tokenModifiers = new Container( SemanticTokenModifier - .Defaults - .Select(z => (string) z) - .ToArray()); + .Defaults + .Select(z => (string) z) + .ToArray() + ); /// /// The token types a server uses. @@ -61,7 +63,7 @@ public int GetTokenTypeIdentity(SemanticTokenType? tokenType) { EnsureTokenTypes(); if (!tokenType.HasValue) return 0; - if (string.IsNullOrWhiteSpace((tokenType.Value))) return 0; + if (string.IsNullOrWhiteSpace(tokenType.Value)) return 0; return _tokenTypesData.TryGetValue(tokenType.Value, out var tokenTypeNumber) ? tokenTypeNumber : 0; } @@ -70,11 +72,13 @@ public int GetTokenModifiersIdentity(params string[] tokenModifiers) EnsureTokenModifiers(); if (tokenModifiers == null) return 0; return tokenModifiers - .Where(z => !string.IsNullOrWhiteSpace(z)) - .Aggregate(0, - (acc, value) => _tokenModifiersData.TryGetValue(value, out var tokenModifer) - ? acc + tokenModifer - : acc); + .Where(z => !string.IsNullOrWhiteSpace(z)) + .Aggregate( + 0, + (acc, value) => _tokenModifiersData.TryGetValue(value, out var tokenModifer) + ? acc + tokenModifer + : acc + ); } public int GetTokenModifiersIdentity(IEnumerable tokenModifiers) @@ -82,11 +86,13 @@ public int GetTokenModifiersIdentity(IEnumerable tokenModifiers) EnsureTokenModifiers(); if (tokenModifiers == null) return 0; return tokenModifiers - .Where(z => !string.IsNullOrWhiteSpace(z)) - .Aggregate(0, - (acc, value) => _tokenModifiersData.TryGetValue(value, out var tokenModifer) - ? acc + tokenModifer - : acc); + .Where(z => !string.IsNullOrWhiteSpace(z)) + .Aggregate( + 0, + (acc, value) => _tokenModifiersData.TryGetValue(value, out var tokenModifer) + ? acc + tokenModifer + : acc + ); } public int GetTokenModifiersIdentity(params SemanticTokenModifier[] tokenModifiers) @@ -94,11 +100,13 @@ public int GetTokenModifiersIdentity(params SemanticTokenModifier[] tokenModifie EnsureTokenModifiers(); if (tokenModifiers == null) return 0; return tokenModifiers - .Where(z => !string.IsNullOrWhiteSpace(z)) - .Aggregate(0, - (acc, value) => _tokenModifiersData.TryGetValue(value, out var tokenModifer) - ? acc + tokenModifer - : acc); + .Where(z => !string.IsNullOrWhiteSpace(z)) + .Aggregate( + 0, + (acc, value) => _tokenModifiersData.TryGetValue(value, out var tokenModifer) + ? acc + tokenModifer + : acc + ); } public int GetTokenModifiersIdentity(IEnumerable tokenModifiers) @@ -106,33 +114,35 @@ public int GetTokenModifiersIdentity(IEnumerable tokenMod EnsureTokenModifiers(); if (tokenModifiers == null) return 0; return tokenModifiers - .Where(z => !string.IsNullOrWhiteSpace(z)) - .Aggregate(0, - (acc, value) => _tokenModifiersData.TryGetValue(value, out var tokenModifer) - ? acc + tokenModifer - : acc); + .Where(z => !string.IsNullOrWhiteSpace(z)) + .Aggregate( + 0, + (acc, value) => _tokenModifiersData.TryGetValue(value, out var tokenModifer) + ? acc + tokenModifer + : acc + ); } - private void EnsureTokenTypes() - { + private void EnsureTokenTypes() => _tokenTypesData ??= TokenTypes - .Select((value, index) => ( - value: new SemanticTokenType(value), - index - )) - .Where(z => !string.IsNullOrWhiteSpace(z.value)) - .ToImmutableDictionary(z => z.value, z => z.index); - } + .Select( + (value, index) => ( + value: new SemanticTokenType(value), + index + ) + ) + .Where(z => !string.IsNullOrWhiteSpace(z.value)) + .ToImmutableDictionary(z => z.value, z => z.index); - private void EnsureTokenModifiers() - { + private void EnsureTokenModifiers() => _tokenModifiersData ??= TokenModifiers - .Select((value, index) => ( - value: new SemanticTokenModifier(value), - index - )) - .Where(z => !string.IsNullOrWhiteSpace(z.value)) - .ToImmutableDictionary(z => z.value, z => Convert.ToInt32(Math.Pow(2, z.index))); - } + .Select( + (value, index) => ( + value: new SemanticTokenModifier(value), + index + ) + ) + .Where(z => !string.IsNullOrWhiteSpace(z.value)) + .ToImmutableDictionary(z => z.value, z => Convert.ToInt32(Math.Pow(2, z.index))); } } diff --git a/src/Protocol/Models/Proposals/SemanticTokensOptions.cs b/src/Protocol/Models/Proposals/SemanticTokensOptions.cs index 37067e5bf..f0bd57710 100644 --- a/src/Protocol/Models/Proposals/SemanticTokensOptions.cs +++ b/src/Protocol/Models/Proposals/SemanticTokensOptions.cs @@ -17,26 +17,26 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals public class SemanticTokensOptions : WorkDoneProgressOptions, ISemanticTokensOptions, IStaticRegistrationOptions { /// - /// The legend used by the server + /// The legend used by the server /// public SemanticTokensLegend Legend { get; set; } /// - /// Server supports providing semantic tokens for a specific range - /// of a document. + /// Server supports providing semantic tokens for a specific range + /// of a document. /// [Optional] public BooleanOr Range { get; set; } /// - /// Server supports providing semantic tokens for a full document. + /// Server supports providing semantic tokens for a full document. /// [Optional] public BooleanOr Full { get; set; } public static SemanticTokensOptions Of(ISemanticTokensOptions options, IEnumerable descriptors) { - var result = new SemanticTokensOptions() { + var result = new SemanticTokensOptions { WorkDoneProgress = options.WorkDoneProgress, Legend = options.Legend ?? new SemanticTokensLegend(), Full = options.Full, @@ -47,9 +47,11 @@ public static SemanticTokensOptions Of(ISemanticTokensOptions options, IEnumerab var edits = descriptors.Any(z => z.HandlerType == typeof(ISemanticTokensDeltaHandler)); if (edits) { - result.Full = new BooleanOr(new SemanticTokensCapabilityRequestFull() { - Delta = true - }); + result.Full = new BooleanOr( + new SemanticTokensCapabilityRequestFull { + Delta = true + } + ); } } diff --git a/src/Protocol/Models/Proposals/SemanticTokensParams.cs b/src/Protocol/Models/Proposals/SemanticTokensParams.cs index 866977d4e..3861da735 100644 --- a/src/Protocol/Models/Proposals/SemanticTokensParams.cs +++ b/src/Protocol/Models/Proposals/SemanticTokensParams.cs @@ -9,7 +9,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals [Obsolete(Constants.Proposal)] [Method(TextDocumentNames.SemanticTokensFull, Direction.ClientToServer)] public class SemanticTokensParams : IWorkDoneProgressParams, ITextDocumentIdentifierParams, - IPartialItemRequest + IPartialItemRequest { /// /// The text document. diff --git a/src/Protocol/Models/Proposals/SemanticTokensRangeParams.cs b/src/Protocol/Models/Proposals/SemanticTokensRangeParams.cs index 0b97d5950..b6c435ed1 100644 --- a/src/Protocol/Models/Proposals/SemanticTokensRangeParams.cs +++ b/src/Protocol/Models/Proposals/SemanticTokensRangeParams.cs @@ -9,7 +9,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals [Obsolete(Constants.Proposal)] [Method(TextDocumentNames.SemanticTokensRange, Direction.ClientToServer)] public class SemanticTokensRangeParams : IWorkDoneProgressParams, ITextDocumentIdentifierParams, - IPartialItemRequest + IPartialItemRequest { /// /// The text document. diff --git a/src/Protocol/Models/Proposals/SemanticTokensRegistrationOptions.cs b/src/Protocol/Models/Proposals/SemanticTokensRegistrationOptions.cs index 5a98423a4..689031c88 100644 --- a/src/Protocol/Models/Proposals/SemanticTokensRegistrationOptions.cs +++ b/src/Protocol/Models/Proposals/SemanticTokensRegistrationOptions.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.Linq; -using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; -using OmniSharp.Extensions.LanguageServer.Protocol.Document.Proposals; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals @@ -12,19 +8,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals public class SemanticTokensRegistrationOptions : StaticWorkDoneTextDocumentRegistrationOptions, ISemanticTokensOptions { /// - /// The legend used by the server + /// The legend used by the server /// public SemanticTokensLegend Legend { get; set; } /// - /// Server supports providing semantic tokens for a specific range - /// of a document. + /// Server supports providing semantic tokens for a specific range + /// of a document. /// [Optional] public BooleanOr Range { get; set; } /// - /// Server supports providing semantic tokens for a full document. + /// Server supports providing semantic tokens for a full document. /// [Optional] public BooleanOr Full { get; set; } diff --git a/src/Protocol/Models/PublishDiagnosticsParams.cs b/src/Protocol/Models/PublishDiagnosticsParams.cs index eab188788..eb607377a 100644 --- a/src/Protocol/Models/PublishDiagnosticsParams.cs +++ b/src/Protocol/Models/PublishDiagnosticsParams.cs @@ -8,7 +8,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models public class PublishDiagnosticsParams : IRequest { /// - /// The URI for which diagnostic information is reported. + /// The URI for which diagnostic information is reported. /// public DocumentUri Uri { get; set; } @@ -21,7 +21,7 @@ public class PublishDiagnosticsParams : IRequest public int? Version { get; set; } /// - /// An array of diagnostic information items. + /// An array of diagnostic information items. /// public Container Diagnostics { get; set; } } diff --git a/src/Protocol/Models/Range.cs b/src/Protocol/Models/Range.cs index 7ed2dd2d8..dec12bf98 100644 --- a/src/Protocol/Models/Range.cs +++ b/src/Protocol/Models/Range.cs @@ -7,7 +7,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public class Range : IEquatable { - public Range() { } + public Range() + { + } public Range(Position start, Position end) { @@ -25,17 +27,12 @@ public Range(Position start, Position end) /// public Position End { get; set; } - public override bool Equals(object obj) - { - return Equals(obj as Range); - } + public override bool Equals(object obj) => Equals(obj as Range); - public bool Equals(Range other) - { - return other != null && - EqualityComparer.Default.Equals(Start, other.Start) && - EqualityComparer.Default.Equals(End, other.End); - } + public bool Equals(Range other) => + other != null && + EqualityComparer.Default.Equals(Start, other.Start) && + EqualityComparer.Default.Equals(End, other.End); public override int GetHashCode() { @@ -45,22 +42,14 @@ public override int GetHashCode() return hashCode; } - public static bool operator ==(Range range1, Range range2) - { - return EqualityComparer.Default.Equals(range1, range2); - } + public static bool operator ==(Range range1, Range range2) => EqualityComparer.Default.Equals(range1, range2); - public static bool operator !=(Range range1, Range range2) - { - return !(range1 == range2); - } + public static bool operator !=(Range range1, Range range2) => !( range1 == range2 ); - public static implicit operator Range((Position start, Position end) value) - { - return new Range(value.start, value.end); - } + public static implicit operator Range((Position start, Position end) value) => new Range(value.start, value.end); private string DebuggerDisplay => $"[start: {Start}, end: {End}]"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/RangeOrPlaceholderRange.cs b/src/Protocol/Models/RangeOrPlaceholderRange.cs index a6a124e20..135bc4a6b 100644 --- a/src/Protocol/Models/RangeOrPlaceholderRange.cs +++ b/src/Protocol/Models/RangeOrPlaceholderRange.cs @@ -6,59 +6,54 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [JsonConverter(typeof(RangeOrPlaceholderRangeConverter))] public class RangeOrPlaceholderRange { - private Range _range; private PlaceholderRange _placeholderRange; + public RangeOrPlaceholderRange(Range value) { _range = value; _placeholderRange = default; } + public RangeOrPlaceholderRange(PlaceholderRange value) { _range = default; _placeholderRange = value; } - public bool IsPlaceholderRange => this._placeholderRange != null; + public bool IsPlaceholderRange => _placeholderRange != null; + public PlaceholderRange PlaceholderRange { - get { return this._placeholderRange; } - set - { - this._placeholderRange = value; - this._range = null; + get => _placeholderRange; + set { + _placeholderRange = value; + _range = null; } } - public bool IsRange => this._range != null; + public bool IsRange => _range != null; + public Range Range { - get { return this._range; } - set - { - this._placeholderRange = default; - this._range = value; + get => _range; + set { + _placeholderRange = default; + _range = value; } } + public object RawValue { - get - { + get { if (IsPlaceholderRange) return PlaceholderRange; if (IsRange) return Range; return default; } } - public static implicit operator RangeOrPlaceholderRange(PlaceholderRange value) - { - return new RangeOrPlaceholderRange(value); - } + public static implicit operator RangeOrPlaceholderRange(PlaceholderRange value) => new RangeOrPlaceholderRange(value); - public static implicit operator RangeOrPlaceholderRange(Range value) - { - return new RangeOrPlaceholderRange(value); - } + public static implicit operator RangeOrPlaceholderRange(Range value) => new RangeOrPlaceholderRange(value); } } diff --git a/src/Protocol/Models/ReferenceContext.cs b/src/Protocol/Models/ReferenceContext.cs index e6b21cf8f..1c28399a9 100644 --- a/src/Protocol/Models/ReferenceContext.cs +++ b/src/Protocol/Models/ReferenceContext.cs @@ -1,5 +1,3 @@ -using System.Diagnostics; - namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public class ReferenceContext @@ -8,6 +6,5 @@ public class ReferenceContext /// Include the declaration of the current symbol. /// public bool IncludeDeclaration { get; set; } - } } diff --git a/src/Protocol/Models/ReferenceRegistrationOptions.cs b/src/Protocol/Models/ReferenceRegistrationOptions.cs index ea27823cc..1e4835605 100644 --- a/src/Protocol/Models/ReferenceRegistrationOptions.cs +++ b/src/Protocol/Models/ReferenceRegistrationOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public class ReferenceRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IReferencesOptions { } + public class ReferenceRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, IReferencesOptions + { + } } diff --git a/src/Protocol/Models/Registration.cs b/src/Protocol/Models/Registration.cs index c4cdfa92e..31c9bf54f 100644 --- a/src/Protocol/Models/Registration.cs +++ b/src/Protocol/Models/Registration.cs @@ -4,29 +4,30 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { /// - /// General paramters to to regsiter for a capability. + /// General paramters to to regsiter for a capability. /// [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public class Registration { /// - /// The id used to register the request. The id can be used to deregister - /// the request again. + /// The id used to register the request. The id can be used to deregister + /// the request again. /// public string Id { get; set; } /// - /// The method / capability to register for. + /// The method / capability to register for. /// public string Method { get; set; } /// - /// Options necessary for the registration. + /// Options necessary for the registration. /// [Optional] public object RegisterOptions { get; set; } private string DebuggerDisplay => $"[{Id}] {Method}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/RegistrationContainer.cs b/src/Protocol/Models/RegistrationContainer.cs index b9ca4aad6..0ea0cbafd 100644 --- a/src/Protocol/Models/RegistrationContainer.cs +++ b/src/Protocol/Models/RegistrationContainer.cs @@ -6,27 +6,23 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public class RegistrationContainer : Container { - - public RegistrationContainer() : this(Enumerable.Empty()) { } - - public RegistrationContainer(IEnumerable items) : base(items) { } - - public RegistrationContainer(params Registration[] items) : base(items) { } - - - public static implicit operator RegistrationContainer(Registration[] items) + public RegistrationContainer() : this(Enumerable.Empty()) { - return new RegistrationContainer(items); } - public static implicit operator RegistrationContainer(Collection items) + public RegistrationContainer(IEnumerable items) : base(items) { - return new RegistrationContainer(items); } - public static implicit operator RegistrationContainer(List items) + public RegistrationContainer(params Registration[] items) : base(items) { - return new RegistrationContainer(items); } + + + public static implicit operator RegistrationContainer(Registration[] items) => new RegistrationContainer(items); + + public static implicit operator RegistrationContainer(Collection items) => new RegistrationContainer(items); + + public static implicit operator RegistrationContainer(List items) => new RegistrationContainer(items); } } diff --git a/src/Protocol/Models/RenameFile.cs b/src/Protocol/Models/RenameFile.cs index 395030634..f05117cdc 100644 --- a/src/Protocol/Models/RenameFile.cs +++ b/src/Protocol/Models/RenameFile.cs @@ -11,14 +11,17 @@ public class RenameFile : IFile /// A rename /// public ResourceOperationKind Kind { get; } = ResourceOperationKind.Rename; + /// /// The old (existing) location. /// public DocumentUri OldUri { get; set; } + /// /// The new location. /// public DocumentUri NewUri { get; set; } + /// /// Rename Options. /// diff --git a/src/Protocol/Models/RenameFileOptions.cs b/src/Protocol/Models/RenameFileOptions.cs index 7f86d458f..8245ef03d 100644 --- a/src/Protocol/Models/RenameFileOptions.cs +++ b/src/Protocol/Models/RenameFileOptions.cs @@ -12,6 +12,7 @@ public class RenameFileOptions /// [Optional] public bool Overwrite { get; set; } + /// /// Ignores if target exists. /// diff --git a/src/Protocol/Models/ResourceOperationKind.cs b/src/Protocol/Models/ResourceOperationKind.cs index 4319f902a..d802c3454 100644 --- a/src/Protocol/Models/ResourceOperationKind.cs +++ b/src/Protocol/Models/ResourceOperationKind.cs @@ -8,19 +8,18 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models public enum ResourceOperationKind { /// - ///Supports creating new files and folders. + /// Supports creating new files and folders. /// - [EnumMember(Value = "create")] - Create, + [EnumMember(Value = "create")] Create, + /// - ///Supports renaming existing files and folders. + /// Supports renaming existing files and folders. /// - [EnumMember(Value = "rename")] - Rename, + [EnumMember(Value = "rename")] Rename, + /// - ///Supports deleting existing files and folders. + /// Supports deleting existing files and folders. /// - [EnumMember(Value = "delete")] - Delete, + [EnumMember(Value = "delete")] Delete, } } diff --git a/src/Protocol/Models/SelectionRange.cs b/src/Protocol/Models/SelectionRange.cs index 2ff3cf964..85ce853f6 100644 --- a/src/Protocol/Models/SelectionRange.cs +++ b/src/Protocol/Models/SelectionRange.cs @@ -16,6 +16,7 @@ public class SelectionRange public SelectionRange Parent { get; set; } private string DebuggerDisplay => $"{Range} {{{Parent}}}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/SelectionRangeRegistrationOptions.cs b/src/Protocol/Models/SelectionRangeRegistrationOptions.cs index 7667be15c..f62375601 100644 --- a/src/Protocol/Models/SelectionRangeRegistrationOptions.cs +++ b/src/Protocol/Models/SelectionRangeRegistrationOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public class SelectionRangeRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, ISelectionRangeOptions { } + public class SelectionRangeRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, ISelectionRangeOptions + { + } } diff --git a/src/Protocol/Models/ServerInfo.cs b/src/Protocol/Models/ServerInfo.cs index 6e53d5885..1350bf8e8 100644 --- a/src/Protocol/Models/ServerInfo.cs +++ b/src/Protocol/Models/ServerInfo.cs @@ -4,25 +4,26 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { /// - /// Information about the server. - /// - /// @since 3.15.0 + /// Information about the server. + /// + /// @since 3.15.0 /// [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public class ServerInfo { /// - /// The name of the server as defined by the server. + /// The name of the server as defined by the server. /// public string Name { get; set; } /// - /// The servers's version as defined by the server. + /// The servers's version as defined by the server. /// [Optional] public string Version { get; set; } private string DebuggerDisplay => string.IsNullOrWhiteSpace(Version) ? Name : $"{Name} ({Version})"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/ShowMessageParams.cs b/src/Protocol/Models/ShowMessageParams.cs index 576369254..8375fbc6c 100644 --- a/src/Protocol/Models/ShowMessageParams.cs +++ b/src/Protocol/Models/ShowMessageParams.cs @@ -4,18 +4,18 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { /// - /// The show message notification is sent from a server to a client to ask the client to display a particular message in the user interface. + /// The show message notification is sent from a server to a client to ask the client to display a particular message in the user interface. /// -[Method(WindowNames.ShowMessage, Direction.ServerToClient)] + [Method(WindowNames.ShowMessage, Direction.ServerToClient)] public class ShowMessageParams : IRequest { /// - /// The message type. See {@link MessageType}. + /// The message type. See {@link MessageType}. /// public MessageType Type { get; set; } /// - /// The actual message. + /// The actual message. /// public string Message { get; set; } } diff --git a/src/Protocol/Models/ShowMessageRequestParams.cs b/src/Protocol/Models/ShowMessageRequestParams.cs index fface8d31..c6008dcc9 100644 --- a/src/Protocol/Models/ShowMessageRequestParams.cs +++ b/src/Protocol/Models/ShowMessageRequestParams.cs @@ -5,23 +5,24 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.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 request allows to pass actions and to wait for an answer from the client. + /// 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. /// -[Method(WindowNames.ShowMessageRequest, Direction.ServerToClient)] + [Method(WindowNames.ShowMessageRequest, Direction.ServerToClient)] public class ShowMessageRequestParams : IRequest { /// - /// The message type. See {@link MessageType} + /// The message type. See {@link MessageType} /// public MessageType Type { get; set; } /// - /// The actual message + /// The actual message /// public string Message { get; set; } /// - /// The message action items to present. + /// The message action items to present. /// [Optional] public Container Actions { get; set; } diff --git a/src/Protocol/Models/ShutdownParams.cs b/src/Protocol/Models/ShutdownParams.cs index 24e2393f2..d240a9d14 100644 --- a/src/Protocol/Models/ShutdownParams.cs +++ b/src/Protocol/Models/ShutdownParams.cs @@ -6,7 +6,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [Method(GeneralNames.Shutdown, Direction.ClientToServer)] public class ShutdownParams : IRequest { - public ShutdownParams() {} public static ShutdownParams Instance { get; } = new ShutdownParams(); } } diff --git a/src/Protocol/Models/SignatureHelpTriggerKind.cs b/src/Protocol/Models/SignatureHelpTriggerKind.cs index 8b2b15d47..e47876e70 100644 --- a/src/Protocol/Models/SignatureHelpTriggerKind.cs +++ b/src/Protocol/Models/SignatureHelpTriggerKind.cs @@ -15,10 +15,12 @@ public enum SignatureHelpTriggerKind /// Signature help was invoked manually by the user or by a command. /// Invoked = 1, + /// /// Signature help was triggered by a trigger character. /// TriggerCharacter = 2, + /// /// Signature help was triggered by the cursor moving or by the document content changing. /// diff --git a/src/Protocol/Models/StringOrMarkupContent.cs b/src/Protocol/Models/StringOrMarkupContent.cs index f7ad5c641..265391372 100644 --- a/src/Protocol/Models/StringOrMarkupContent.cs +++ b/src/Protocol/Models/StringOrMarkupContent.cs @@ -8,32 +8,21 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public class StringOrMarkupContent { - public StringOrMarkupContent(string value) - { - String = value; - } + public StringOrMarkupContent(string value) => String = value; - public StringOrMarkupContent(MarkupContent markupContent) - { - MarkupContent = markupContent; - } + public StringOrMarkupContent(MarkupContent markupContent) => MarkupContent = markupContent; public string String { get; } - public bool HasString => this.MarkupContent == null; + public bool HasString => MarkupContent == null; public MarkupContent MarkupContent { get; } public bool HasMarkupContent => String == null; - public static implicit operator StringOrMarkupContent(string value) - { - return new StringOrMarkupContent(value); - } + public static implicit operator StringOrMarkupContent(string value) => new StringOrMarkupContent(value); - public static implicit operator StringOrMarkupContent(MarkupContent markupContent) - { - return new StringOrMarkupContent(markupContent); - } + public static implicit operator StringOrMarkupContent(MarkupContent markupContent) => new StringOrMarkupContent(markupContent); + + private string DebuggerDisplay => $"{( HasString ? String : HasMarkupContent ? MarkupContent.ToString() : string.Empty )}"; - private string DebuggerDisplay => $"{(HasString ? String : HasMarkupContent ? MarkupContent.ToString() : string.Empty)}"; /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/SymbolInformation.cs b/src/Protocol/Models/SymbolInformation.cs index 2b8f8c4d4..dbf97b78b 100644 --- a/src/Protocol/Models/SymbolInformation.cs +++ b/src/Protocol/Models/SymbolInformation.cs @@ -44,6 +44,7 @@ public class SymbolInformation public string ContainerName { get; set; } private string DebuggerDisplay => $"[{Kind}@{Location}] {Name}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/SymbolInformationOrDocumentSymbol.cs b/src/Protocol/Models/SymbolInformationOrDocumentSymbol.cs index f5475f9bb..26dbc1825 100644 --- a/src/Protocol/Models/SymbolInformationOrDocumentSymbol.cs +++ b/src/Protocol/Models/SymbolInformationOrDocumentSymbol.cs @@ -8,46 +8,34 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public struct SymbolInformationOrDocumentSymbol { - private DocumentSymbol _documentSymbol; - private SymbolInformation _symbolInformation; public SymbolInformationOrDocumentSymbol(DocumentSymbol documentSymbol) { - _documentSymbol = documentSymbol; - _symbolInformation = default; + DocumentSymbol = documentSymbol; + SymbolInformation = default; } + public SymbolInformationOrDocumentSymbol(SymbolInformation symbolInformation) { - _documentSymbol = default; - _symbolInformation = symbolInformation; + DocumentSymbol = default; + SymbolInformation = symbolInformation; } - public bool IsDocumentSymbolInformation => _symbolInformation != null; - public SymbolInformation SymbolInformation => _symbolInformation; + public bool IsDocumentSymbolInformation => SymbolInformation != null; + public SymbolInformation SymbolInformation { get; } - public bool IsDocumentSymbol => _documentSymbol != null; - public DocumentSymbol DocumentSymbol => _documentSymbol; + public bool IsDocumentSymbol => DocumentSymbol != null; + public DocumentSymbol DocumentSymbol { get; } - public static SymbolInformationOrDocumentSymbol Create(SymbolInformation value) - { - return value; - } + public static SymbolInformationOrDocumentSymbol Create(SymbolInformation value) => value; - public static SymbolInformationOrDocumentSymbol Create(DocumentSymbol value) - { - return value; - } + public static SymbolInformationOrDocumentSymbol Create(DocumentSymbol value) => value; - public static implicit operator SymbolInformationOrDocumentSymbol(SymbolInformation value) - { - return new SymbolInformationOrDocumentSymbol(value); - } + public static implicit operator SymbolInformationOrDocumentSymbol(SymbolInformation value) => new SymbolInformationOrDocumentSymbol(value); - public static implicit operator SymbolInformationOrDocumentSymbol(DocumentSymbol value) - { - return new SymbolInformationOrDocumentSymbol(value); - } + public static implicit operator SymbolInformationOrDocumentSymbol(DocumentSymbol value) => new SymbolInformationOrDocumentSymbol(value); private string DebuggerDisplay => IsDocumentSymbol ? DocumentSymbol.ToString() : IsDocumentSymbolInformation ? SymbolInformation.ToString() : string.Empty; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/SymbolInformationOrDocumentSymbolContainer.cs b/src/Protocol/Models/SymbolInformationOrDocumentSymbolContainer.cs index ae0f8b5c8..f441ae94f 100644 --- a/src/Protocol/Models/SymbolInformationOrDocumentSymbolContainer.cs +++ b/src/Protocol/Models/SymbolInformationOrDocumentSymbolContainer.cs @@ -18,49 +18,31 @@ public SymbolInformationOrDocumentSymbolContainer(params SymbolInformationOrDocu { } - public static implicit operator SymbolInformationOrDocumentSymbolContainer(SymbolInformationOrDocumentSymbol[] items) - { - return new SymbolInformationOrDocumentSymbolContainer(items); - } + public static implicit operator SymbolInformationOrDocumentSymbolContainer(SymbolInformationOrDocumentSymbol[] items) => + new SymbolInformationOrDocumentSymbolContainer(items); - public static implicit operator SymbolInformationOrDocumentSymbolContainer(Collection items) - { - return new SymbolInformationOrDocumentSymbolContainer(items); - } + public static implicit operator SymbolInformationOrDocumentSymbolContainer(Collection items) => + new SymbolInformationOrDocumentSymbolContainer(items); - public static implicit operator SymbolInformationOrDocumentSymbolContainer(List items) - { - return new SymbolInformationOrDocumentSymbolContainer(items); - } + public static implicit operator SymbolInformationOrDocumentSymbolContainer(List items) => + new SymbolInformationOrDocumentSymbolContainer(items); - public static implicit operator SymbolInformationOrDocumentSymbolContainer(SymbolInformation[] items) - { - return new SymbolInformationOrDocumentSymbolContainer(items.Select(SymbolInformationOrDocumentSymbol.Create)); - } + public static implicit operator SymbolInformationOrDocumentSymbolContainer(SymbolInformation[] items) => + new SymbolInformationOrDocumentSymbolContainer(items.Select(SymbolInformationOrDocumentSymbol.Create)); - public static implicit operator SymbolInformationOrDocumentSymbolContainer(Collection items) - { - return new SymbolInformationOrDocumentSymbolContainer(items.Select(SymbolInformationOrDocumentSymbol.Create)); - } + public static implicit operator SymbolInformationOrDocumentSymbolContainer(Collection items) => + new SymbolInformationOrDocumentSymbolContainer(items.Select(SymbolInformationOrDocumentSymbol.Create)); - public static implicit operator SymbolInformationOrDocumentSymbolContainer(List items) - { - return new SymbolInformationOrDocumentSymbolContainer(items.Select(SymbolInformationOrDocumentSymbol.Create)); - } + public static implicit operator SymbolInformationOrDocumentSymbolContainer(List items) => + new SymbolInformationOrDocumentSymbolContainer(items.Select(SymbolInformationOrDocumentSymbol.Create)); - public static implicit operator SymbolInformationOrDocumentSymbolContainer(DocumentSymbol[] items) - { - return new SymbolInformationOrDocumentSymbolContainer(items.Select(SymbolInformationOrDocumentSymbol.Create)); - } + public static implicit operator SymbolInformationOrDocumentSymbolContainer(DocumentSymbol[] items) => + new SymbolInformationOrDocumentSymbolContainer(items.Select(SymbolInformationOrDocumentSymbol.Create)); - public static implicit operator SymbolInformationOrDocumentSymbolContainer(Collection items) - { - return new SymbolInformationOrDocumentSymbolContainer(items.Select(SymbolInformationOrDocumentSymbol.Create)); - } + public static implicit operator SymbolInformationOrDocumentSymbolContainer(Collection items) => + new SymbolInformationOrDocumentSymbolContainer(items.Select(SymbolInformationOrDocumentSymbol.Create)); - public static implicit operator SymbolInformationOrDocumentSymbolContainer(List items) - { - return new SymbolInformationOrDocumentSymbolContainer(items.Select(SymbolInformationOrDocumentSymbol.Create)); - } + public static implicit operator SymbolInformationOrDocumentSymbolContainer(List items) => + new SymbolInformationOrDocumentSymbolContainer(items.Select(SymbolInformationOrDocumentSymbol.Create)); } } diff --git a/src/Protocol/Models/TelemetryEventParams.cs b/src/Protocol/Models/TelemetryEventParams.cs index 6d2e2987c..a13fd8f2e 100644 --- a/src/Protocol/Models/TelemetryEventParams.cs +++ b/src/Protocol/Models/TelemetryEventParams.cs @@ -9,7 +9,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [Method(WindowNames.TelemetryEvent, Direction.ServerToClient)] public class TelemetryEventParams : IRequest { - [JsonExtensionData] - private IDictionary Data { get; set; } + [JsonExtensionData] private IDictionary Data { get; set; } } } diff --git a/src/Protocol/Models/TextDocument.cs b/src/Protocol/Models/TextDocument.cs index b27f026c9..bd00dc78e 100644 --- a/src/Protocol/Models/TextDocument.cs +++ b/src/Protocol/Models/TextDocument.cs @@ -2,6 +2,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public class TextDocument { - public static Container Eol = new string[] { "\n", "\r\n", "\r" }; + public static Container Eol = new[] { "\n", "\r\n", "\r" }; } } diff --git a/src/Protocol/Models/TextDocumentChangeRegistrationOptions.cs b/src/Protocol/Models/TextDocumentChangeRegistrationOptions.cs index 9299c8e90..7409ffbf2 100644 --- a/src/Protocol/Models/TextDocumentChangeRegistrationOptions.cs +++ b/src/Protocol/Models/TextDocumentChangeRegistrationOptions.cs @@ -3,13 +3,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { /// - /// Descibe options to be used when registered for text document change events. + /// Descibe options to be used when registered for text document change events. /// public class TextDocumentChangeRegistrationOptions : TextDocumentRegistrationOptions { /// - /// How documents are synced to the server. See TextDocumentSyncKind.Full - /// and TextDocumentSyncKindIncremental. + /// How documents are synced to the server. See TextDocumentSyncKind.Full + /// and TextDocumentSyncKindIncremental. /// public TextDocumentSyncKind SyncKind { get; set; } } diff --git a/src/Protocol/Models/TextDocumentContentChangeEvent.cs b/src/Protocol/Models/TextDocumentContentChangeEvent.cs index 7e3aa529d..2a145cb1f 100644 --- a/src/Protocol/Models/TextDocumentContentChangeEvent.cs +++ b/src/Protocol/Models/TextDocumentContentChangeEvent.cs @@ -3,25 +3,25 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { /// - /// An event describing a change to a text document. If range and rangeLength are omitted - /// the new text is considered to be the full content of the document. + /// An event describing a change to a text document. If range and rangeLength are omitted + /// the new text is considered to be the full content of the document. /// public class TextDocumentContentChangeEvent { /// - /// The range of the document that changed. + /// The range of the document that changed. /// [Optional] public Range Range { get; set; } /// - /// The length of the range that got replaced. + /// The length of the range that got replaced. /// [Optional] public int RangeLength { get; set; } /// - /// The new text of the document. + /// The new text of the document. /// public string Text { get; set; } } diff --git a/src/Protocol/Models/TextDocumentIdentifier.cs b/src/Protocol/Models/TextDocumentIdentifier.cs index 23a8969b5..b64bd0c25 100644 --- a/src/Protocol/Models/TextDocumentIdentifier.cs +++ b/src/Protocol/Models/TextDocumentIdentifier.cs @@ -8,13 +8,9 @@ public class TextDocumentIdentifier : IEquatable { public TextDocumentIdentifier() { - } - public TextDocumentIdentifier(DocumentUri uri) - { - Uri = uri; - } + public TextDocumentIdentifier(DocumentUri uri) => Uri = uri; /// /// The text document's URI. @@ -32,8 +28,8 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; - return Equals((TextDocumentIdentifier)obj); + if (obj.GetType() != GetType()) return false; + return Equals((TextDocumentIdentifier) obj); } public override int GetHashCode() => Uri.GetHashCode(); @@ -42,17 +38,12 @@ public override bool Equals(object obj) public static bool operator !=(TextDocumentIdentifier left, TextDocumentIdentifier right) => !Equals(left, right); - public static implicit operator TextDocumentIdentifier(DocumentUri uri) - { - return new TextDocumentIdentifier() { Uri = uri }; - } + public static implicit operator TextDocumentIdentifier(DocumentUri uri) => new TextDocumentIdentifier { Uri = uri }; - public static implicit operator TextDocumentIdentifier(string uri) - { - return new TextDocumentIdentifier() { Uri = uri }; - } + public static implicit operator TextDocumentIdentifier(string uri) => new TextDocumentIdentifier { Uri = uri }; private string DebuggerDisplay => Uri?.ToString(); + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/TextDocumentItem.cs b/src/Protocol/Models/TextDocumentItem.cs index 053ed2c90..5af38fdf5 100644 --- a/src/Protocol/Models/TextDocumentItem.cs +++ b/src/Protocol/Models/TextDocumentItem.cs @@ -22,6 +22,7 @@ public class TextDocumentItem : TextDocumentIdentifier public string Text { get; set; } private string DebuggerDisplay => $"({LanguageId}@{Version}) {Uri}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/TextDocumentRegistrationOptions.cs b/src/Protocol/Models/TextDocumentRegistrationOptions.cs index 976da8d73..ad9a35509 100644 --- a/src/Protocol/Models/TextDocumentRegistrationOptions.cs +++ b/src/Protocol/Models/TextDocumentRegistrationOptions.cs @@ -5,8 +5,8 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models public class TextDocumentRegistrationOptions : ITextDocumentRegistrationOptions { /// - /// A document selector to identify the scope of the registration. If set to null - /// the document selector provided on the client side will be used. + /// A document selector to identify the scope of the registration. If set to null + /// the document selector provided on the client side will be used. /// [Optional] public DocumentSelector DocumentSelector { get; set; } diff --git a/src/Protocol/Models/TextDocumentSaveReason.cs b/src/Protocol/Models/TextDocumentSaveReason.cs index d0bc1c052..d425b5791 100644 --- a/src/Protocol/Models/TextDocumentSaveReason.cs +++ b/src/Protocol/Models/TextDocumentSaveReason.cs @@ -4,25 +4,24 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { /// - /// Represents reasons why a text document is saved. + /// Represents reasons why a text document is saved. /// [JsonConverter(typeof(NumberEnumConverter))] public enum TextDocumentSaveReason { - /// - /// Manually triggered, e.g. by the user pressing save, by starting debugging, - /// or by an API call. + /// Manually triggered, e.g. by the user pressing save, by starting debugging, + /// or by an API call. /// Manual = 1, /// - /// Automatic after a delay. + /// Automatic after a delay. /// AfterDelay = 2, /// - /// When the editor lost focus. + /// When the editor lost focus. /// FocusOut = 3, } diff --git a/src/Protocol/Models/TextDocumentSaveRegistrationOptions.cs b/src/Protocol/Models/TextDocumentSaveRegistrationOptions.cs index 121fad8e2..8b0739eb3 100644 --- a/src/Protocol/Models/TextDocumentSaveRegistrationOptions.cs +++ b/src/Protocol/Models/TextDocumentSaveRegistrationOptions.cs @@ -5,7 +5,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models public class TextDocumentSaveRegistrationOptions : TextDocumentRegistrationOptions { /// - /// The client is supposed to include the content on save. + /// The client is supposed to include the content on save. /// [Optional] public bool IncludeText { get; set; } diff --git a/src/Protocol/Models/TextEdit.cs b/src/Protocol/Models/TextEdit.cs index 237acbd6c..498d51e39 100644 --- a/src/Protocol/Models/TextEdit.cs +++ b/src/Protocol/Models/TextEdit.cs @@ -17,7 +17,8 @@ public class TextEdit /// public string NewText { get; set; } - 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; } diff --git a/src/Protocol/Models/TextEditContainer.cs b/src/Protocol/Models/TextEditContainer.cs index 734372ce7..e6b32c38e 100644 --- a/src/Protocol/Models/TextEditContainer.cs +++ b/src/Protocol/Models/TextEditContainer.cs @@ -18,19 +18,10 @@ public TextEditContainer(params TextEdit[] items) : base(items) { } - public static implicit operator TextEditContainer(TextEdit[] items) - { - return new TextEditContainer(items); - } + public static implicit operator TextEditContainer(TextEdit[] items) => new TextEditContainer(items); - public static implicit operator TextEditContainer(Collection items) - { - return new TextEditContainer(items); - } + public static implicit operator TextEditContainer(Collection items) => new TextEditContainer(items); - public static implicit operator TextEditContainer(List items) - { - return new TextEditContainer(items); - } + public static implicit operator TextEditContainer(List items) => new TextEditContainer(items); } } diff --git a/src/Protocol/Models/TypeDefinitionRegistrationOptions.cs b/src/Protocol/Models/TypeDefinitionRegistrationOptions.cs index 3ebf4cee5..8b64bfdfa 100644 --- a/src/Protocol/Models/TypeDefinitionRegistrationOptions.cs +++ b/src/Protocol/Models/TypeDefinitionRegistrationOptions.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { - public class TypeDefinitionRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, ITypeDefinitionOptions { } + public class TypeDefinitionRegistrationOptions : WorkDoneTextDocumentRegistrationOptions, ITypeDefinitionOptions + { + } } diff --git a/src/Protocol/Models/Unregistration.cs b/src/Protocol/Models/Unregistration.cs index c6514a969..0a3aa5d67 100644 --- a/src/Protocol/Models/Unregistration.cs +++ b/src/Protocol/Models/Unregistration.cs @@ -3,31 +3,30 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { /// - /// General parameters to unregister a request or notification. + /// General parameters to unregister a request or notification. /// [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public class Unregistration { /// - /// The id used to unregister the request or notification. Usually an id - /// provided during the register request. + /// The id used to unregister the request or notification. Usually an id + /// provided during the register request. /// public string Id { get; set; } /// - /// The method to unregister for. + /// The method to unregister for. /// public string Method { get; set; } - public static implicit operator Unregistration(Registration registration) - { - return new Unregistration() { + public static implicit operator Unregistration(Registration registration) => + new Unregistration { Id = registration.Id, Method = registration.Method }; - } private string DebuggerDisplay => $"[{Id}] {Method}"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/UnregistrationContainer.cs b/src/Protocol/Models/UnregistrationContainer.cs index 053ac7839..b8cc120a4 100644 --- a/src/Protocol/Models/UnregistrationContainer.cs +++ b/src/Protocol/Models/UnregistrationContainer.cs @@ -6,43 +6,30 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public class UnregistrationContainer : Container { - - public UnregistrationContainer() : this(Enumerable.Empty()) { } - - public UnregistrationContainer(IEnumerable items) : base(items) { } - - public UnregistrationContainer(params Unregistration[] items) : base(items) { } - - - public static implicit operator UnregistrationContainer(Unregistration[] items) + public UnregistrationContainer() : this(Enumerable.Empty()) { - return new UnregistrationContainer(items); } - public static implicit operator UnregistrationContainer(Collection items) + public UnregistrationContainer(IEnumerable items) : base(items) { - return new UnregistrationContainer(items); } - public static implicit operator UnregistrationContainer(List items) + public UnregistrationContainer(params Unregistration[] items) : base(items) { - return new UnregistrationContainer(items); } - public static implicit operator UnregistrationContainer(Registration[] items) - { - return new UnregistrationContainer(items.Select(x => (Unregistration) x)); - } + public static implicit operator UnregistrationContainer(Unregistration[] items) => new UnregistrationContainer(items); - public static implicit operator UnregistrationContainer(Collection items) - { - return new UnregistrationContainer(items.Select(x => (Unregistration)x)); - } + public static implicit operator UnregistrationContainer(Collection items) => new UnregistrationContainer(items); - public static implicit operator UnregistrationContainer(List items) - { - return new UnregistrationContainer(items.Select(x => (Unregistration)x)); - } + public static implicit operator UnregistrationContainer(List items) => new UnregistrationContainer(items); + + + public static implicit operator UnregistrationContainer(Registration[] items) => new UnregistrationContainer(items.Select(x => (Unregistration) x)); + + public static implicit operator UnregistrationContainer(Collection items) => new UnregistrationContainer(items.Select(x => (Unregistration) x)); + + public static implicit operator UnregistrationContainer(List items) => new UnregistrationContainer(items.Select(x => (Unregistration) x)); } } diff --git a/src/Protocol/Models/UnregistrationParams.cs b/src/Protocol/Models/UnregistrationParams.cs index bd98d0b0f..c30f52d15 100644 --- a/src/Protocol/Models/UnregistrationParams.cs +++ b/src/Protocol/Models/UnregistrationParams.cs @@ -11,6 +11,10 @@ public class UnregistrationParams : IRequest // Placeholder for v4 support [JsonIgnore] - public UnregistrationContainer Unregistrations { get => Unregisterations; set => Unregisterations = value; } + public UnregistrationContainer Unregistrations + { + get => Unregisterations; + set => Unregisterations = value; + } } } diff --git a/src/Protocol/Models/VersionedTextDocumentIdentifier.cs b/src/Protocol/Models/VersionedTextDocumentIdentifier.cs index 63604c554..a663caf4f 100644 --- a/src/Protocol/Models/VersionedTextDocumentIdentifier.cs +++ b/src/Protocol/Models/VersionedTextDocumentIdentifier.cs @@ -17,15 +17,15 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; - return Equals((VersionedTextDocumentIdentifier)obj); + if (obj.GetType() != GetType()) return false; + return Equals((VersionedTextDocumentIdentifier) obj); } public override int GetHashCode() { unchecked { - return (base.GetHashCode() * 397) ^ Version.GetHashCode(); + return ( base.GetHashCode() * 397 ) ^ Version.GetHashCode(); } } @@ -39,6 +39,7 @@ public override int GetHashCode() public int? Version { get; set; } private string DebuggerDisplay => $"{Uri}@({Version})"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/WillSaveTextDocumentParams.cs b/src/Protocol/Models/WillSaveTextDocumentParams.cs index 1b8c34711..117a981c8 100644 --- a/src/Protocol/Models/WillSaveTextDocumentParams.cs +++ b/src/Protocol/Models/WillSaveTextDocumentParams.cs @@ -4,18 +4,18 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { /// - /// The parameters send in a will save text document notification. + /// The parameters send in a will save text document notification. /// [Method(TextDocumentNames.WillSave, Direction.ClientToServer)] public class WillSaveTextDocumentParams : IRequest { /// - /// The document that will be saved. + /// The document that will be saved. /// public TextDocumentIdentifier TextDocument { get; set; } /// - /// The 'TextDocumentSaveReason'. + /// The 'TextDocumentSaveReason'. /// public TextDocumentSaveReason Reason { get; set; } } diff --git a/src/Protocol/Models/WillSaveWaitUntilTextDocumentParams.cs b/src/Protocol/Models/WillSaveWaitUntilTextDocumentParams.cs index 6ae28fba1..bd02c3b7d 100644 --- a/src/Protocol/Models/WillSaveWaitUntilTextDocumentParams.cs +++ b/src/Protocol/Models/WillSaveWaitUntilTextDocumentParams.cs @@ -4,18 +4,18 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { /// - /// The parameters send in a will save text document notification. + /// The parameters send in a will save text document notification. /// [Method(TextDocumentNames.WillSaveWaitUntil, Direction.ClientToServer)] public class WillSaveWaitUntilTextDocumentParams : IRequest { /// - /// The document that will be saved. + /// The document that will be saved. /// public TextDocumentIdentifier TextDocument { get; set; } /// - /// The 'TextDocumentSaveReason'. + /// The 'TextDocumentSaveReason'. /// public TextDocumentSaveReason Reason { get; set; } } diff --git a/src/Protocol/Models/WorkDoneProgress.cs b/src/Protocol/Models/WorkDoneProgress.cs index a43d48ca6..41a05c808 100644 --- a/src/Protocol/Models/WorkDoneProgress.cs +++ b/src/Protocol/Models/WorkDoneProgress.cs @@ -10,10 +10,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public abstract class WorkDoneProgress { - public WorkDoneProgress(WorkDoneProgressKind kind) - { - Kind = kind; - } + public WorkDoneProgress(WorkDoneProgressKind kind) => Kind = kind; public WorkDoneProgressKind Kind { get; } @@ -32,11 +29,12 @@ public WorkDoneProgress(WorkDoneProgressKind kind) new Lazy>( () => { return typeof(WorkDoneProgressKind) - .GetFields(BindingFlags.Static | BindingFlags.Public) - .Select(z => z.GetValue(null)) - .Cast() - .ToArray(); - }); + .GetFields(BindingFlags.Static | BindingFlags.Public) + .Select(z => z.GetValue(null)) + .Cast() + .ToArray(); + } + ); public static IEnumerable Defaults => _defaults.Value; @@ -46,27 +44,18 @@ public WorkDoneProgress(WorkDoneProgressKind kind) private readonly string _value; - public WorkDoneProgressKind(string modifier) - { - _value = modifier; - } + public WorkDoneProgressKind(string modifier) => _value = modifier; - public static implicit operator WorkDoneProgressKind(string kind) - { - return new WorkDoneProgressKind(kind); - } + public static implicit operator WorkDoneProgressKind(string kind) => new WorkDoneProgressKind(kind); - public static implicit operator string(WorkDoneProgressKind kind) - { - return kind._value; - } + public static implicit operator string(WorkDoneProgressKind kind) => kind._value; public override string ToString() => _value; public bool Equals(WorkDoneProgressKind other) => _value == other._value; public override bool Equals(object obj) => obj is WorkDoneProgressKind other && Equals(other); - public override int GetHashCode() => (_value != null ? _value.GetHashCode() : 0); + public override int GetHashCode() => _value != null ? _value.GetHashCode() : 0; public static bool operator ==(WorkDoneProgressKind left, WorkDoneProgressKind right) => left.Equals(right); diff --git a/src/Protocol/Models/WorkDoneProgressBegin.cs b/src/Protocol/Models/WorkDoneProgressBegin.cs index e4a308f4a..a91cddc2d 100644 --- a/src/Protocol/Models/WorkDoneProgressBegin.cs +++ b/src/Protocol/Models/WorkDoneProgressBegin.cs @@ -7,7 +7,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models /// public class WorkDoneProgressBegin : WorkDoneProgress { - public WorkDoneProgressBegin() : base(WorkDoneProgressKind.Begin) { } + public WorkDoneProgressBegin() : base(WorkDoneProgressKind.Begin) + { + } /// /// Mandatory title of the progress operation. Used to briefly inform about diff --git a/src/Protocol/Models/WorkDoneProgressEnd.cs b/src/Protocol/Models/WorkDoneProgressEnd.cs index b3c21a823..287aae4c0 100644 --- a/src/Protocol/Models/WorkDoneProgressEnd.cs +++ b/src/Protocol/Models/WorkDoneProgressEnd.cs @@ -5,6 +5,8 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models /// public class WorkDoneProgressEnd : WorkDoneProgress { - public WorkDoneProgressEnd() : base(WorkDoneProgressKind.End) { } + public WorkDoneProgressEnd() : base(WorkDoneProgressKind.End) + { + } } } diff --git a/src/Protocol/Models/WorkDoneProgressOptions.cs b/src/Protocol/Models/WorkDoneProgressOptions.cs index 4f6eb35f4..0e06320f7 100644 --- a/src/Protocol/Models/WorkDoneProgressOptions.cs +++ b/src/Protocol/Models/WorkDoneProgressOptions.cs @@ -4,7 +4,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public class WorkDoneProgressOptions : IWorkDoneProgressOptions { - [Optional] - public bool WorkDoneProgress { get; set; } + [Optional] public bool WorkDoneProgress { get; set; } } } diff --git a/src/Protocol/Models/WorkDoneProgressReport.cs b/src/Protocol/Models/WorkDoneProgressReport.cs index 99f8bee7d..e747a57c8 100644 --- a/src/Protocol/Models/WorkDoneProgressReport.cs +++ b/src/Protocol/Models/WorkDoneProgressReport.cs @@ -7,7 +7,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models /// public class WorkDoneProgressReport : WorkDoneProgress { - public WorkDoneProgressReport() : base(WorkDoneProgressKind.Report) { } + public WorkDoneProgressReport() : base(WorkDoneProgressKind.Report) + { + } /// /// Controls enablement state of a cancel button. This property is only valid if a cancel diff --git a/src/Protocol/Models/WorkDoneTextDocumentPositionParams.cs b/src/Protocol/Models/WorkDoneTextDocumentPositionParams.cs index 2240ea4a2..7d8398491 100644 --- a/src/Protocol/Models/WorkDoneTextDocumentPositionParams.cs +++ b/src/Protocol/Models/WorkDoneTextDocumentPositionParams.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public abstract class WorkDoneTextDocumentPositionParams : TextDocumentPositionParams, IWorkDoneProgressParams { - /// + /// [Optional] public ProgressToken WorkDoneToken { get; set; } } diff --git a/src/Protocol/Models/WorkspaceEditDocumentChange.cs b/src/Protocol/Models/WorkspaceEditDocumentChange.cs index 0f604c438..7c4624ec1 100644 --- a/src/Protocol/Models/WorkspaceEditDocumentChange.cs +++ b/src/Protocol/Models/WorkspaceEditDocumentChange.cs @@ -50,24 +50,12 @@ public WorkspaceEditDocumentChange(DeleteFile deleteFile) public bool IsDeleteFile => DeleteFile != null; public DeleteFile DeleteFile { get; } - public static implicit operator WorkspaceEditDocumentChange(TextDocumentEdit textDocumentEdit) - { - return new WorkspaceEditDocumentChange(textDocumentEdit); - } + public static implicit operator WorkspaceEditDocumentChange(TextDocumentEdit textDocumentEdit) => new WorkspaceEditDocumentChange(textDocumentEdit); - public static implicit operator WorkspaceEditDocumentChange(CreateFile createFile) - { - return new WorkspaceEditDocumentChange(createFile); - } + public static implicit operator WorkspaceEditDocumentChange(CreateFile createFile) => new WorkspaceEditDocumentChange(createFile); - public static implicit operator WorkspaceEditDocumentChange(RenameFile renameFile) - { - return new WorkspaceEditDocumentChange(renameFile); - } + public static implicit operator WorkspaceEditDocumentChange(RenameFile renameFile) => new WorkspaceEditDocumentChange(renameFile); - public static implicit operator WorkspaceEditDocumentChange(DeleteFile deleteFile) - { - return new WorkspaceEditDocumentChange(deleteFile); - } + public static implicit operator WorkspaceEditDocumentChange(DeleteFile deleteFile) => new WorkspaceEditDocumentChange(deleteFile); } } diff --git a/src/Protocol/Models/WorkspaceFolder.cs b/src/Protocol/Models/WorkspaceFolder.cs index 5c4a25caf..f9770bc7a 100644 --- a/src/Protocol/Models/WorkspaceFolder.cs +++ b/src/Protocol/Models/WorkspaceFolder.cs @@ -27,15 +27,15 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; - return Equals((WorkspaceFolder)obj); + if (obj.GetType() != GetType()) return false; + return Equals((WorkspaceFolder) obj); } public override int GetHashCode() { unchecked { - return (Uri.GetHashCode() * 397) ^ Name.GetHashCode(); + return ( Uri.GetHashCode() * 397 ) ^ Name.GetHashCode(); } } @@ -44,6 +44,7 @@ public override int GetHashCode() public static bool operator !=(WorkspaceFolder left, WorkspaceFolder right) => !Equals(left, right); private string DebuggerDisplay => $"{Name} ({Uri})"; + /// public override string ToString() => DebuggerDisplay; } diff --git a/src/Protocol/Models/WorkspaceFolderParams.cs b/src/Protocol/Models/WorkspaceFolderParams.cs index c2e9ecacb..8bb7c5da7 100644 --- a/src/Protocol/Models/WorkspaceFolderParams.cs +++ b/src/Protocol/Models/WorkspaceFolderParams.cs @@ -6,11 +6,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [Method(WorkspaceNames.WorkspaceFolders, Direction.ServerToClient)] public class WorkspaceFolderParams : IRequest> { - public WorkspaceFolderParams() - { - - } - public static WorkspaceFolderParams Instance = new WorkspaceFolderParams(); } } diff --git a/src/Protocol/Models/WorkspaceSymbolOptions.cs b/src/Protocol/Models/WorkspaceSymbolOptions.cs index b5817e2c6..e8345ec10 100644 --- a/src/Protocol/Models/WorkspaceSymbolOptions.cs +++ b/src/Protocol/Models/WorkspaceSymbolOptions.cs @@ -5,12 +5,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public class WorkspaceSymbolOptions : WorkDoneProgressOptions, IWorkspaceSymbolOptions { - public static WorkspaceSymbolOptions Of(IWorkspaceSymbolOptions options, IEnumerable descriptors) - { - return new WorkspaceSymbolOptions() - { + public static WorkspaceSymbolOptions Of(IWorkspaceSymbolOptions options, IEnumerable descriptors) => + new WorkspaceSymbolOptions { WorkDoneProgress = options.WorkDoneProgress, }; - } } } diff --git a/src/Protocol/Models/WorkspaceSymbolRegistrationOptions.cs b/src/Protocol/Models/WorkspaceSymbolRegistrationOptions.cs index 461885edb..8f32a55e7 100644 --- a/src/Protocol/Models/WorkspaceSymbolRegistrationOptions.cs +++ b/src/Protocol/Models/WorkspaceSymbolRegistrationOptions.cs @@ -2,6 +2,5 @@ { public class WorkspaceSymbolRegistrationOptions : WorkDoneProgressOptions, IWorkspaceSymbolOptions { - } } diff --git a/src/Protocol/Progress/EmptySubject.cs b/src/Protocol/Progress/EmptySubject.cs index 5e4ee5e57..938485756 100644 --- a/src/Protocol/Progress/EmptySubject.cs +++ b/src/Protocol/Progress/EmptySubject.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Progress { - class EmptySubject : SubjectBase + internal class EmptySubject : SubjectBase { public override void Dispose() { @@ -32,4 +32,4 @@ public override IDisposable Subscribe(IObserver observer) public override bool HasObservers => false; public override bool IsDisposed => false; } -} \ No newline at end of file +} diff --git a/src/Protocol/Progress/IProgressContext.cs b/src/Protocol/Progress/IProgressContext.cs index 94ea0fc87..84168a87c 100644 --- a/src/Protocol/Progress/IProgressContext.cs +++ b/src/Protocol/Progress/IProgressContext.cs @@ -6,4 +6,4 @@ public interface IProgressContext { ProgressToken ProgressToken { get; } } -} \ No newline at end of file +} diff --git a/src/Protocol/Progress/IProgressManager.cs b/src/Protocol/Progress/IProgressManager.cs index 0929b7934..81989d91b 100644 --- a/src/Protocol/Progress/IProgressManager.cs +++ b/src/Protocol/Progress/IProgressManager.cs @@ -11,10 +11,17 @@ public interface IProgressManager : IProgressHandler IProgressObservable Monitor(ProgressToken token); IProgressObservable Monitor(ProgressToken token, Func factory); - IRequestProgressObservable MonitorUntil(IPartialItemRequest request, Func factory, CancellationToken cancellationToken); - IRequestProgressObservable MonitorUntil(IPartialItemRequest request, Func factory, CancellationToken cancellationToken); + IRequestProgressObservable MonitorUntil( + IPartialItemRequest request, Func factory, CancellationToken cancellationToken + ); - IRequestProgressObservable, TResponse> MonitorUntil(IPartialItemsRequest request, Func, TResponse> factory, CancellationToken cancellationToken) + IRequestProgressObservable MonitorUntil( + IPartialItemRequest request, Func factory, CancellationToken cancellationToken + ); + + IRequestProgressObservable, TResponse> MonitorUntil( + IPartialItemsRequest request, Func, TResponse> factory, CancellationToken cancellationToken + ) where TResponse : IEnumerable; IRequestProgressObservable MonitorUntil(IPartialItemsRequest request, CancellationToken cancellationToken); diff --git a/src/Protocol/Progress/IProgressObservable.cs b/src/Protocol/Progress/IProgressObservable.cs index abdcb9bfe..1f9c44f0c 100644 --- a/src/Protocol/Progress/IProgressObservable.cs +++ b/src/Protocol/Progress/IProgressObservable.cs @@ -2,7 +2,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Progress { - public interface IProgressObservable : IProgressObservable, IDisposable, IObservable { } + public interface IProgressObservable : IProgressObservable, IDisposable, IObservable + { + } public interface IProgressObservable : IProgressContext { diff --git a/src/Protocol/Progress/IProgressObserver.cs b/src/Protocol/Progress/IProgressObserver.cs index 3e3078e04..24616e9d4 100644 --- a/src/Protocol/Progress/IProgressObserver.cs +++ b/src/Protocol/Progress/IProgressObserver.cs @@ -1,4 +1,5 @@ using System; +using System.Reactive; using System.Runtime.CompilerServices; using System.Threading; @@ -6,7 +7,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Progress { public interface IProgressObserver : IProgressObserver, IObserver { - TaskAwaiter GetAwaiter(); + TaskAwaiter GetAwaiter(); } public interface IProgressObserver : IProgressContext, IDisposable diff --git a/src/Protocol/Progress/IRequestProgressObservable.cs b/src/Protocol/Progress/IRequestProgressObservable.cs index 296a35e9e..fef0a0fdb 100644 --- a/src/Protocol/Progress/IRequestProgressObservable.cs +++ b/src/Protocol/Progress/IRequestProgressObservable.cs @@ -11,6 +11,7 @@ public interface IRequestProgressObservable : IProgressObser Task AsTask(); TaskAwaiter GetAwaiter(); } + public interface IRequestProgressObservable : IRequestProgressObservable, Container> { } diff --git a/src/Protocol/Progress/PartialItemsRequestProgressObservable.cs b/src/Protocol/Progress/PartialItemsRequestProgressObservable.cs index b8ff6565a..0e532ff2d 100644 --- a/src/Protocol/Progress/PartialItemsRequestProgressObservable.cs +++ b/src/Protocol/Progress/PartialItemsRequestProgressObservable.cs @@ -13,7 +13,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Progress { - class PartialItemsRequestProgressObservable : IRequestProgressObservable, TResult>, IObserver, IDisposable + internal class PartialItemsRequestProgressObservable : IRequestProgressObservable, TResult>, IObserver, IDisposable where TResult : IEnumerable { private readonly ISerializer _serializer; @@ -27,18 +27,21 @@ public PartialItemsRequestProgressObservable( IObservable requestResult, Func, TResult> factory, CancellationToken cancellationToken, - Action disposal) + Action disposal + ) { _serializer = serializer; _dataSubject = new ReplaySubject>(int.MaxValue); var request = requestResult.Do(_ => { }, OnError, OnCompleted).Replay(1); - _disposable = new CompositeDisposable() {request.Connect(), Disposable.Create(disposal)}; + _disposable = new CompositeDisposable { request.Connect(), Disposable.Create(disposal) }; _task = request.Amb( - _dataSubject.Scan(new List(), (acc, data) => { - acc.AddRange(data); - return acc; - }).Select(factory) + _dataSubject.Scan( + new List(), (acc, data) => { + acc.AddRange(data); + return acc; + } + ).Select(factory) ).ToTask(cancellationToken); _task.ContinueWith(x => Dispose()); @@ -58,25 +61,23 @@ public PartialItemsRequestProgressObservable( public void OnNext(JToken value) => _dataSubject.OnNext(value.ToObject(_serializer.JsonSerializer)); - public void Dispose() - { - _disposable.Dispose(); - } + public void Dispose() => _disposable.Dispose(); - public IDisposable Subscribe(IObserver> observer) - { - return _disposable.IsDisposed ? Disposable.Empty : _dataSubject.Subscribe(observer); - } + public IDisposable Subscribe(IObserver> observer) => _disposable.IsDisposed ? Disposable.Empty : _dataSubject.Subscribe(observer); public Task AsTask() => _task; public TaskAwaiter GetAwaiter() => _task.GetAwaiter(); } - class PartialItemsRequestProgressObservable : PartialItemsRequestProgressObservable>, IRequestProgressObservable + internal class PartialItemsRequestProgressObservable : PartialItemsRequestProgressObservable>, IRequestProgressObservable { - public PartialItemsRequestProgressObservable(ISerializer serializer, ProgressToken token, IObservable> requestResult, - Func, Container> factory, CancellationToken cancellationToken, Action disposal) : base(serializer, token, requestResult, factory, cancellationToken, - disposal) + public PartialItemsRequestProgressObservable( + ISerializer serializer, ProgressToken token, IObservable> requestResult, + Func, Container> factory, CancellationToken cancellationToken, Action disposal + ) : base( + serializer, token, requestResult, factory, cancellationToken, + disposal + ) { } } diff --git a/src/Protocol/Progress/ProgressManager.cs b/src/Protocol/Progress/ProgressManager.cs index d70a08792..ecaabf14d 100644 --- a/src/Protocol/Progress/ProgressManager.cs +++ b/src/Protocol/Progress/ProgressManager.cs @@ -12,12 +12,16 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Progress { - class ProgressManager : IProgressManager + internal class ProgressManager : IProgressManager { private readonly IResponseRouter _router; private readonly ISerializer _serializer; - private readonly ConcurrentDictionary _activeObservers = new ConcurrentDictionary(EqualityComparer.Default); - private readonly ConcurrentDictionary _activeObservables = new ConcurrentDictionary(EqualityComparer.Default); + + private readonly ConcurrentDictionary _activeObservers = + new ConcurrentDictionary(EqualityComparer.Default); + + private readonly ConcurrentDictionary _activeObservables = + new ConcurrentDictionary(EqualityComparer.Default); public ProgressManager(IResponseRouter router, ISerializer serializer) { @@ -36,10 +40,7 @@ Task IRequestHandler.Handle(ProgressParams request, return Unit.Task; } - public IProgressObservable Monitor(ProgressToken token) - { - return Monitor(token, x => x.ToObject(_serializer.JsonSerializer)); - } + public IProgressObservable Monitor(ProgressToken token) => Monitor(token, x => x.ToObject(_serializer.JsonSerializer)); public IProgressObservable Monitor(ProgressToken token, Func factory) { @@ -53,11 +54,14 @@ public IProgressObservable Monitor(ProgressToken token, Func fa return observable; } - public IRequestProgressObservable MonitorUntil(IPartialItemRequest request, Func factory, - CancellationToken cancellationToken) + public IRequestProgressObservable MonitorUntil( + IPartialItemRequest request, Func factory, + CancellationToken cancellationToken + ) { request.PartialResultToken ??= new ProgressToken(Guid.NewGuid().ToString()); - if (request.PartialResultToken != null && _activeObservables.TryGetValue(request.PartialResultToken, out var o) && o is IRequestProgressObservable observable) + if (request.PartialResultToken != null && _activeObservables.TryGetValue(request.PartialResultToken, out var o) + && o is IRequestProgressObservable observable) { return observable; } @@ -67,13 +71,16 @@ public IRequestProgressObservable MonitorUntil(I request.PartialResultToken, MakeRequest(request), (x, f) => factory(x), - cancellationToken, () => _activeObservables.TryRemove(request.PartialResultToken, out var disposable)); + cancellationToken, () => _activeObservables.TryRemove(request.PartialResultToken, out var disposable) + ); _activeObservables.TryAdd(request.PartialResultToken, observable); return observable; } - public IRequestProgressObservable MonitorUntil(IPartialItemRequest request, Func factory, - CancellationToken cancellationToken) + public IRequestProgressObservable MonitorUntil( + IPartialItemRequest request, Func factory, + CancellationToken cancellationToken + ) { request.PartialResultToken ??= new ProgressToken(Guid.NewGuid().ToString()); if (_activeObservables.TryGetValue(request.PartialResultToken, out var o) && o is IRequestProgressObservable observable) @@ -81,14 +88,18 @@ public IRequestProgressObservable MonitorUntil(I return observable; } - observable = new RequestProgressObservable(_serializer, request.PartialResultToken, MakeRequest(request), factory, - cancellationToken, () => _activeObservables.TryRemove(request.PartialResultToken, out var disposable)); + observable = new RequestProgressObservable( + _serializer, request.PartialResultToken, MakeRequest(request), factory, + cancellationToken, () => _activeObservables.TryRemove(request.PartialResultToken, out var disposable) + ); _activeObservables.TryAdd(request.PartialResultToken, observable); return observable; } - public IRequestProgressObservable, IEnumerable> MonitorUntil(IPartialItemsRequest, TItem> request, - CancellationToken cancellationToken) + public IRequestProgressObservable, IEnumerable> MonitorUntil( + IPartialItemsRequest, TItem> request, + CancellationToken cancellationToken + ) { request.PartialResultToken ??= new ProgressToken(Guid.NewGuid().ToString()); if (_activeObservables.TryGetValue(request.PartialResultToken, out var o) && o is IRequestProgressObservable, IEnumerable> observable) @@ -96,14 +107,18 @@ public IRequestProgressObservable, IEnumerable> Monito return observable; } - observable = new PartialItemsRequestProgressObservable>(_serializer,request.PartialResultToken, MakeRequest(request), - x => x, cancellationToken, () => _activeObservables.TryRemove(request.PartialResultToken, out var disposable)); + observable = new PartialItemsRequestProgressObservable>( + _serializer, request.PartialResultToken, MakeRequest(request), + x => x, cancellationToken, () => _activeObservables.TryRemove(request.PartialResultToken, out var disposable) + ); _activeObservables.TryAdd(request.PartialResultToken, observable); return observable; } - public IRequestProgressObservable, TResponse> MonitorUntil(IPartialItemsRequest request, - Func, TResponse> factory, CancellationToken cancellationToken) + public IRequestProgressObservable, TResponse> MonitorUntil( + IPartialItemsRequest request, + Func, TResponse> factory, CancellationToken cancellationToken + ) where TResponse : IEnumerable { request.PartialResultToken ??= new ProgressToken(Guid.NewGuid().ToString()); @@ -112,8 +127,10 @@ public IRequestProgressObservable, TResponse> MonitorUntil(_serializer,request.PartialResultToken, MakeRequest(request), factory, cancellationToken, - () => _activeObservables.TryRemove(request.PartialResultToken, out var disposable)); + observable = new PartialItemsRequestProgressObservable( + _serializer, request.PartialResultToken, MakeRequest(request), factory, cancellationToken, + () => _activeObservables.TryRemove(request.PartialResultToken, out var disposable) + ); _activeObservables.TryAdd(request.PartialResultToken, observable); return observable; } @@ -126,8 +143,10 @@ public IRequestProgressObservable MonitorUntil(IPartialItemsReques return observable; } - observable = new PartialItemsRequestProgressObservable(_serializer,request.PartialResultToken, MakeRequest(request), x => new Container(x), cancellationToken, - () => _activeObservables.TryRemove(request.PartialResultToken, out var disposable)); + observable = new PartialItemsRequestProgressObservable( + _serializer, request.PartialResultToken, MakeRequest(request), x => new Container(x), cancellationToken, + () => _activeObservables.TryRemove(request.PartialResultToken, out var disposable) + ); _activeObservables.TryAdd(request.PartialResultToken, observable); return observable; } @@ -152,7 +171,9 @@ public IProgressObserver For(IPartialItemRequest(request.PartialResultToken, _router, _serializer, cancellationToken, () => _activeObservers.TryRemove(request.PartialResultToken, out var disposable)); + observer = new ProgressObserver( + request.PartialResultToken, _router, _serializer, cancellationToken, () => _activeObservers.TryRemove(request.PartialResultToken, out var disposable) + ); _activeObservers.TryAdd(request.PartialResultToken, observer); return observer; } @@ -166,30 +187,32 @@ public IProgressObserver> For(IPartialItems return observer; } - observer = new ProgressObserver>(request.PartialResultToken, _router, _serializer, cancellationToken, () => _activeObservers.TryRemove(request.PartialResultToken, out var disposable)); + observer = new ProgressObserver>( + request.PartialResultToken, _router, _serializer, cancellationToken, () => _activeObservers.TryRemove(request.PartialResultToken, out var disposable) + ); _activeObservers.TryAdd(request.PartialResultToken, observer); return observer; } - private IObservable MakeRequest(IRequest request) - { + private IObservable MakeRequest(IRequest request) => // Has problems with wanting custom exceptions around cancellation. // Observable.FromAsync(ct => _router.SendRequest(request, ct)) - return Observable.Create(async (observer, ct) => { - try - { - observer.OnNext(await _router.SendRequest(request, ct)); - observer.OnCompleted(); - } - catch (OperationCanceledException e) - { - observer.OnError(e); + Observable.Create( + async (observer, ct) => { + try + { + observer.OnNext(await _router.SendRequest(request, ct)); + observer.OnCompleted(); + } + catch (OperationCanceledException e) + { + observer.OnError(e); + } + catch (Exception e) + { + observer.OnError(e); + } } - catch (Exception e) - { - observer.OnError(e); - } - }); - } + ); } } diff --git a/src/Protocol/Progress/ProgressObservable.cs b/src/Protocol/Progress/ProgressObservable.cs index 4855b72e2..d36866947 100644 --- a/src/Protocol/Progress/ProgressObservable.cs +++ b/src/Protocol/Progress/ProgressObservable.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Progress { - class ProgressObservable : IProgressObservable, IObserver + internal class ProgressObservable : IProgressObservable, IObserver { private readonly Func _factory; private readonly CompositeDisposable _disposable; @@ -17,7 +17,7 @@ public ProgressObservable(ProgressToken token, Func factory, Action d { _factory = factory; _dataSubject = new ReplaySubject(1); - _disposable = new CompositeDisposable() {Disposable.Create(_dataSubject.OnCompleted), Disposable.Create(disposal)}; + _disposable = new CompositeDisposable { Disposable.Create(_dataSubject.OnCompleted), Disposable.Create(disposal) }; ProgressToken = token; if (_dataSubject is IDisposable disposable) @@ -36,14 +36,8 @@ public ProgressObservable(ProgressToken token, Func factory, Action d public void OnNext(JToken value) => _dataSubject.OnNext(value); - public void Dispose() - { - _disposable.Dispose(); - } + public void Dispose() => _disposable.Dispose(); - public IDisposable Subscribe(IObserver observer) - { - return _disposable.IsDisposed ? Disposable.Empty : _dataSubject.Select(_factory).Subscribe(observer); - } + public IDisposable Subscribe(IObserver observer) => _disposable.IsDisposed ? Disposable.Empty : _dataSubject.Select(_factory).Subscribe(observer); } } diff --git a/src/Protocol/Progress/ProgressObserver.cs b/src/Protocol/Progress/ProgressObserver.cs index 46f14955e..97201d9bb 100644 --- a/src/Protocol/Progress/ProgressObserver.cs +++ b/src/Protocol/Progress/ProgressObserver.cs @@ -1,4 +1,5 @@ using System; +using System.Reactive; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; @@ -9,13 +10,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Progress { - class ProgressObserver : IProgressObserver + internal class ProgressObserver : IProgressObserver { private readonly IResponseRouter _responseRouter; private readonly ISerializer _serializer; private readonly Action _disposal; - private readonly TaskCompletionSource _completionSource; - private bool _isComplete = false; + private readonly TaskCompletionSource _completionSource; + private bool _isComplete; public static ProgressObserver Noop { get; } = new ProgressObserver(new ProgressToken(nameof(Noop)), null, null, CancellationToken.None, () => { }); @@ -25,17 +26,18 @@ public ProgressObserver( IResponseRouter responseRouter, ISerializer serializer, CancellationToken cancellationToken, - Action disposal) + Action disposal + ) { _responseRouter = responseRouter; _serializer = serializer; _disposal = disposal; ProgressToken = token; CancellationToken = cancellationToken; - _completionSource = new TaskCompletionSource(); + _completionSource = new TaskCompletionSource(); } - public TaskAwaiter GetAwaiter() => _completionSource.Task.GetAwaiter(); + public TaskAwaiter GetAwaiter() => _completionSource.Task.GetAwaiter(); public ProgressToken ProgressToken { get; } public CancellationToken CancellationToken { get; } public Type ParamsType { get; } = typeof(T); @@ -43,7 +45,7 @@ public ProgressObserver( public void OnCompleted() { if (_isComplete) return; - _completionSource.TrySetResult(System.Reactive.Unit.Default); + _completionSource.TrySetResult(Unit.Default); _isComplete = true; } @@ -57,15 +59,14 @@ void IObserver.OnError(Exception error) public void OnNext(T value) { if (_isComplete) return; - _responseRouter.SendNotification(new ProgressParams() { - Token = ProgressToken, - Value = JToken.FromObject(value, _serializer.JsonSerializer) - }); + _responseRouter.SendNotification( + new ProgressParams { + Token = ProgressToken, + Value = JToken.FromObject(value, _serializer.JsonSerializer) + } + ); } - public void Dispose() - { - _disposal(); - } + public void Dispose() => _disposal(); } } diff --git a/src/Protocol/Progress/RequestProgressObservable.cs b/src/Protocol/Progress/RequestProgressObservable.cs index a181b8783..d9872ae61 100644 --- a/src/Protocol/Progress/RequestProgressObservable.cs +++ b/src/Protocol/Progress/RequestProgressObservable.cs @@ -12,7 +12,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Progress { - class RequestProgressObservable : IRequestProgressObservable, IObserver + internal class RequestProgressObservable : IRequestProgressObservable, IObserver { private readonly ISerializer _serializer; private readonly ISubject _dataSubject; @@ -25,12 +25,13 @@ public RequestProgressObservable( IObservable requestResult, Func factory, CancellationToken cancellationToken, - Action disposal) + Action disposal + ) { _serializer = serializer; _dataSubject = new ReplaySubject(1); var request = requestResult.Do(_ => { }, OnError, OnCompleted).Replay(1); - _disposable = new CompositeDisposable() {request.Connect(), Disposable.Create(disposal)}; + _disposable = new CompositeDisposable { request.Connect(), Disposable.Create(disposal) }; _task = _dataSubject.ForkJoin(requestResult, factory).ToTask(cancellationToken); _task.ContinueWith(x => Dispose()); @@ -51,15 +52,9 @@ public RequestProgressObservable( public void OnNext(JToken value) => _dataSubject.OnNext(value.ToObject(_serializer.JsonSerializer)); - public void Dispose() - { - _disposable.Dispose(); - } + public void Dispose() => _disposable.Dispose(); - public IDisposable Subscribe(IObserver observer) - { - return _disposable.IsDisposed ? Disposable.Empty : _dataSubject.Subscribe(observer); - } + public IDisposable Subscribe(IObserver observer) => _disposable.IsDisposed ? Disposable.Empty : _dataSubject.Subscribe(observer); public Task AsTask() => _task; public TaskAwaiter GetAwaiter() => _task.GetAwaiter(); diff --git a/src/Protocol/Serialization/ContractResolver.cs b/src/Protocol/Serialization/ContractResolver.cs index 295ebb5dd..761afc9bd 100644 --- a/src/Protocol/Serialization/ContractResolver.cs +++ b/src/Protocol/Serialization/ContractResolver.cs @@ -11,7 +11,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization { - class ContractResolver : DefaultContractResolver + internal class ContractResolver : DefaultContractResolver { private readonly CompletionItemKind[] _completionItemKinds; private readonly CompletionItemTag[] _completionItemTags; @@ -30,7 +30,8 @@ public ContractResolver( SymbolTag[] documentSymbolTags, SymbolTag[] workspaceSymbolTags, DiagnosticTag[] diagnosticTags, - CodeActionKind[] codeActionKinds) + CodeActionKind[] codeActionKinds + ) { _completionItemKinds = completionItemKinds; _completionItemTags = completionItemTags; @@ -52,7 +53,7 @@ protected override JsonObjectContract CreateObjectContract(Type objectType) foreach (var property in contract.Properties) { var isSupportedGetter = property.PropertyType.GetTypeInfo() - .GetProperty(nameof(Supports.IsSupported), BindingFlags.Public | BindingFlags.Instance); + .GetProperty(nameof(Supports.IsSupported), BindingFlags.Public | BindingFlags.Instance); property.NullValueHandling = NullValueHandling.Ignore; property.GetIsSpecified = o => { var propertyValue = property.ValueProvider.GetValue(o); @@ -69,7 +70,7 @@ protected override JsonProperty CreateProperty(MemberInfo member, MemberSerializ { var property = base.CreateProperty(member, memberSerialization); if (member.GetCustomAttributes(true).Any() - || property.DeclaringType.Name.EndsWith("Capabilities") + || property.DeclaringType.Name.EndsWith("Capabilities") ) { property.NullValueHandling = NullValueHandling.Ignore; @@ -146,28 +147,21 @@ protected override JsonProperty CreateProperty(MemberInfo member, MemberSerializ return property; } - class SupportsValueProvider : IValueProvider + private class SupportsValueProvider : IValueProvider { private readonly IValueProvider _valueProvider; - public SupportsValueProvider(IValueProvider valueProvider) - { - _valueProvider = valueProvider; - } - public void SetValue(object target, object value) - { - _valueProvider.SetValue(target, value); - } + public SupportsValueProvider(IValueProvider valueProvider) => _valueProvider = valueProvider; - public object GetValue(object target) - { - return _valueProvider.GetValue(target) switch { + public void SetValue(object target, object value) => _valueProvider.SetValue(target, value); + + public object GetValue(object target) => + _valueProvider.GetValue(target) switch { ISupports supports when supports.IsSupported => supports, - _ => null + _ => null }; - } } - class RangeValueProvider : IValueProvider + private class RangeValueProvider : IValueProvider where T : struct { private readonly IValueProvider _valueProvider; @@ -181,10 +175,7 @@ public RangeValueProvider(IValueProvider valueProvider, T[] validValues) _defaultValue = validValues[0]; } - public void SetValue(object target, object value) - { - _valueProvider.SetValue(target, value); - } + public void SetValue(object target, object value) => _valueProvider.SetValue(target, value); public object GetValue(object target) { @@ -198,7 +189,7 @@ public object GetValue(object target) } } - class ArrayRangeValueProvider : IValueProvider + private class ArrayRangeValueProvider : IValueProvider where T : struct { private readonly IValueProvider _valueProvider; @@ -210,10 +201,7 @@ public ArrayRangeValueProvider(IValueProvider valueProvider, T[] validValues) _validValues = validValues; } - public void SetValue(object target, object value) - { - _valueProvider.SetValue(target, value); - } + public void SetValue(object target, object value) => _valueProvider.SetValue(target, value); public object GetValue(object target) { diff --git a/src/Protocol/Serialization/Converters/AggregateCompletionListConverter.cs b/src/Protocol/Serialization/Converters/AggregateCompletionListConverter.cs index 0e6e8df80..81ec16238 100644 --- a/src/Protocol/Serialization/Converters/AggregateCompletionListConverter.cs +++ b/src/Protocol/Serialization/Converters/AggregateCompletionListConverter.cs @@ -22,6 +22,7 @@ public override void WriteJson(JsonWriter writer, AggregateResponse false; - public override AggregateResponse ReadJson(JsonReader reader, Type objectType, AggregateResponse existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override AggregateResponse ReadJson( + JsonReader reader, Type objectType, AggregateResponse existingValue, bool hasExistingValue, JsonSerializer serializer + ) => throw new NotImplementedException(); } } diff --git a/src/Protocol/Serialization/Converters/BooleanNumberStringConverter.cs b/src/Protocol/Serialization/Converters/BooleanNumberStringConverter.cs index de0111215..96a0f0452 100644 --- a/src/Protocol/Serialization/Converters/BooleanNumberStringConverter.cs +++ b/src/Protocol/Serialization/Converters/BooleanNumberStringConverter.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class BooleanNumberStringConverter : JsonConverter + internal class BooleanNumberStringConverter : JsonConverter { public override void WriteJson(JsonWriter writer, BooleanNumberString value, JsonSerializer serializer) { @@ -18,17 +18,17 @@ public override BooleanNumberString ReadJson(JsonReader reader, Type objectType, { if (reader.TokenType == JsonToken.Integer) { - return new BooleanNumberString((long)reader.Value); + return new BooleanNumberString((long) reader.Value); } if (reader.TokenType == JsonToken.String) { - return new BooleanNumberString((string)reader.Value); + return new BooleanNumberString((string) reader.Value); } if (reader.TokenType == JsonToken.Boolean) { - return new BooleanNumberString((bool)reader.Value); + return new BooleanNumberString((bool) reader.Value); } return new BooleanNumberString(); diff --git a/src/Protocol/Serialization/Converters/BooleanOrConverter.cs b/src/Protocol/Serialization/Converters/BooleanOrConverter.cs index da05460d2..abf59e949 100644 --- a/src/Protocol/Serialization/Converters/BooleanOrConverter.cs +++ b/src/Protocol/Serialization/Converters/BooleanOrConverter.cs @@ -6,19 +6,21 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class BooleanOrConverter : JsonConverter + internal class BooleanOrConverter : JsonConverter { private static readonly MethodInfo WriteJsonGenericMethod = typeof(BooleanOrConverter) - .GetTypeInfo() - .GetMethod(nameof(WriteJsonGeneric), BindingFlags.NonPublic | BindingFlags.Static); + .GetTypeInfo() + .GetMethod(nameof(WriteJsonGeneric), BindingFlags.NonPublic | BindingFlags.Static); + private static readonly MethodInfo ReadJsonGenericMethod = typeof(BooleanOrConverter) - .GetTypeInfo() - .GetMethod(nameof(ReadJsonGeneric), BindingFlags.NonPublic | BindingFlags.Static); + .GetTypeInfo() + .GetMethod(nameof(ReadJsonGeneric), BindingFlags.NonPublic | BindingFlags.Static); + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) return; WriteJsonGenericMethod.MakeGenericMethod(value.GetType().GetTypeInfo().GenericTypeArguments[0]) - .Invoke(null, new object[] { writer, value, serializer }); + .Invoke(null, new[] { writer, value, serializer }); } private static void WriteJsonGeneric(JsonWriter writer, BooleanOr value, JsonSerializer serializer) @@ -42,14 +44,14 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist { var parentType = objectType.GetTypeInfo().GenericTypeArguments[0]; return ReadJsonGenericMethod.MakeGenericMethod(parentType) - .Invoke(null, new object[] { reader, existingValue, serializer }); + .Invoke(null, new[] { reader, existingValue, serializer }); } private static BooleanOr ReadJsonGeneric(JsonReader reader, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Boolean) { - return new BooleanOr((bool)reader.Value); + return new BooleanOr((bool) reader.Value); } if (reader.TokenType == JsonToken.StartObject) diff --git a/src/Protocol/Serialization/Converters/BooleanStringConverter.cs b/src/Protocol/Serialization/Converters/BooleanStringConverter.cs index 43434a654..d48166146 100644 --- a/src/Protocol/Serialization/Converters/BooleanStringConverter.cs +++ b/src/Protocol/Serialization/Converters/BooleanStringConverter.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class BooleanStringConverter : JsonConverter + internal class BooleanStringConverter : JsonConverter { public override void WriteJson(JsonWriter writer, BooleanString value, JsonSerializer serializer) { @@ -17,9 +17,9 @@ public override BooleanString ReadJson(JsonReader reader, Type objectType, Boole switch (reader.TokenType) { case JsonToken.String: - return new BooleanString((string)reader.Value); + return new BooleanString((string) reader.Value); case JsonToken.Boolean: - return new BooleanString((bool)reader.Value); + return new BooleanString((bool) reader.Value); } return new BooleanString(); diff --git a/src/Protocol/Serialization/Converters/CommandOrCodeActionConverter.cs b/src/Protocol/Serialization/Converters/CommandOrCodeActionConverter.cs index 2e6e41eff..078523c58 100644 --- a/src/Protocol/Serialization/Converters/CommandOrCodeActionConverter.cs +++ b/src/Protocol/Serialization/Converters/CommandOrCodeActionConverter.cs @@ -28,15 +28,13 @@ public override CommandOrCodeAction ReadJson(JsonReader reader, Type objectType, var result = JObject.Load(reader); // Commands have a name, CodeActions do not - JToken command = result["command"]; + var command = result["command"]; if (command?.Type == JTokenType.String) { return new CommandOrCodeAction(result.ToObject()); } - else - { - return new CommandOrCodeAction(result.ToObject()); - } + + return new CommandOrCodeAction(result.ToObject()); } public override bool CanRead => true; diff --git a/src/Protocol/Serialization/Converters/CompletionListConverter.cs b/src/Protocol/Serialization/Converters/CompletionListConverter.cs index 440c9cde8..701d9f473 100644 --- a/src/Protocol/Serialization/Converters/CompletionListConverter.cs +++ b/src/Protocol/Serialization/Converters/CompletionListConverter.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class CompletionListConverter : JsonConverter + internal class CompletionListConverter : JsonConverter { public override void WriteJson(JsonWriter writer, CompletionList value, JsonSerializer serializer) { @@ -27,6 +27,7 @@ public override void WriteJson(JsonWriter writer, CompletionList value, JsonSeri { serializer.Serialize(writer, item); } + writer.WriteEndArray(); writer.WriteEndObject(); } diff --git a/src/Protocol/Serialization/Converters/DiagnosticCodeConverter.cs b/src/Protocol/Serialization/Converters/DiagnosticCodeConverter.cs index aa84db5df..886e354ec 100644 --- a/src/Protocol/Serialization/Converters/DiagnosticCodeConverter.cs +++ b/src/Protocol/Serialization/Converters/DiagnosticCodeConverter.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class DiagnosticCodeConverter : JsonConverter + internal class DiagnosticCodeConverter : JsonConverter { public override void WriteJson(JsonWriter writer, DiagnosticCode value, JsonSerializer serializer) { @@ -12,8 +12,10 @@ public override void WriteJson(JsonWriter writer, DiagnosticCode value, JsonSeri if (value.IsString) serializer.Serialize(writer, value.String); } - public override DiagnosticCode ReadJson(JsonReader reader, Type objectType, DiagnosticCode existingValue, - bool hasExistingValue, JsonSerializer serializer) + public override DiagnosticCode ReadJson( + JsonReader reader, Type objectType, DiagnosticCode existingValue, + bool hasExistingValue, JsonSerializer serializer + ) { if (reader.TokenType == JsonToken.String) { diff --git a/src/Protocol/Serialization/Converters/DocumentUriConverter.cs b/src/Protocol/Serialization/Converters/DocumentUriConverter.cs index 105594798..6bfbdf349 100644 --- a/src/Protocol/Serialization/Converters/DocumentUriConverter.cs +++ b/src/Protocol/Serialization/Converters/DocumentUriConverter.cs @@ -7,15 +7,18 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class DocumentUriConverter : JsonConverter + internal class DocumentUriConverter : JsonConverter { - public override DocumentUri ReadJson(JsonReader reader, Type objectType, DocumentUri existingValue, - bool hasExistingValue, JsonSerializer serializer) + public override DocumentUri ReadJson( + JsonReader reader, Type objectType, DocumentUri existingValue, + bool hasExistingValue, JsonSerializer serializer + ) { if (reader.TokenType == JsonToken.Null) { return null; } + if (reader.TokenType == JsonToken.String) { try diff --git a/src/Protocol/Serialization/Converters/EnumLikeStringConverter.cs b/src/Protocol/Serialization/Converters/EnumLikeStringConverter.cs index a4d5b8827..16eac0212 100644 --- a/src/Protocol/Serialization/Converters/EnumLikeStringConverter.cs +++ b/src/Protocol/Serialization/Converters/EnumLikeStringConverter.cs @@ -5,22 +5,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - 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) - { - return reader.TokenType switch { + JsonSerializer serializer + ) => + reader.TokenType switch { JsonToken.String => (IEnumLikeString) Activator.CreateInstance(objectType, (string) reader.Value), - _ => (IEnumLikeString) Activator.CreateInstance(objectType, null) + _ => (IEnumLikeString) Activator.CreateInstance(objectType, null) }; - } public override bool CanRead => true; } diff --git a/src/Protocol/Serialization/Converters/LocationOrLocationLinkConverter.cs b/src/Protocol/Serialization/Converters/LocationOrLocationLinkConverter.cs index 660741faa..73dce0794 100644 --- a/src/Protocol/Serialization/Converters/LocationOrLocationLinkConverter.cs +++ b/src/Protocol/Serialization/Converters/LocationOrLocationLinkConverter.cs @@ -22,10 +22,8 @@ public override LocationOrLocationLink ReadJson(JsonReader reader, Type objectTy { return new LocationOrLocationLink(obj.ToObject()); } - else - { - return new LocationOrLocationLink(obj.ToObject()); - } + + return new LocationOrLocationLink(obj.ToObject()); } public override bool CanRead => true; diff --git a/src/Protocol/Serialization/Converters/LocationOrLocationLinksConverter.cs b/src/Protocol/Serialization/Converters/LocationOrLocationLinksConverter.cs index c0d1cb3cc..2f4733d78 100644 --- a/src/Protocol/Serialization/Converters/LocationOrLocationLinksConverter.cs +++ b/src/Protocol/Serialization/Converters/LocationOrLocationLinksConverter.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class LocationOrLocationLinksConverter : JsonConverter + internal class LocationOrLocationLinksConverter : JsonConverter { public override void WriteJson(JsonWriter writer, LocationOrLocationLinks value, JsonSerializer serializer) { @@ -21,13 +21,16 @@ public override void WriteJson(JsonWriter writer, LocationOrLocationLinks value, serializer.Serialize(writer, v); } - public override LocationOrLocationLinks ReadJson(JsonReader reader, Type objectType, LocationOrLocationLinks existingValue, bool hasExistingValue, JsonSerializer serializer) + public override LocationOrLocationLinks ReadJson( + JsonReader reader, Type objectType, LocationOrLocationLinks existingValue, bool hasExistingValue, JsonSerializer serializer + ) { if (reader.TokenType == JsonToken.StartArray) { return new LocationOrLocationLinks(JArray.Load(reader).ToObject>(serializer)); } - else if (reader.TokenType == JsonToken.StartObject) + + if (reader.TokenType == JsonToken.StartObject) { return new LocationOrLocationLinks(JObject.Load(reader).ToObject(serializer)); } diff --git a/src/Protocol/Serialization/Converters/MarkedStringCollectionConverter.cs b/src/Protocol/Serialization/Converters/MarkedStringCollectionConverter.cs index 482d0f6f2..5fe9d2cae 100644 --- a/src/Protocol/Serialization/Converters/MarkedStringCollectionConverter.cs +++ b/src/Protocol/Serialization/Converters/MarkedStringCollectionConverter.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class MarkedStringCollectionConverter : JsonConverter> + internal class MarkedStringCollectionConverter : JsonConverter> { public override void WriteJson(JsonWriter writer, Container value, JsonSerializer serializer) { @@ -21,17 +21,21 @@ public override void WriteJson(JsonWriter writer, Container value, serializer.Serialize(writer, v); } - public override Container ReadJson(JsonReader reader, Type objectType, Container existingValue, bool hasExistingValue, JsonSerializer serializer) + public override Container ReadJson( + JsonReader reader, Type objectType, Container existingValue, bool hasExistingValue, JsonSerializer serializer + ) { if (reader.TokenType == JsonToken.StartArray) { return new Container(JArray.Load(reader).ToObject>(serializer)); } - else if (reader.TokenType == JsonToken.StartObject) + + if (reader.TokenType == JsonToken.StartObject) { return new Container(JObject.Load(reader).ToObject(serializer)); } - else if (reader.TokenType == JsonToken.String) + + if (reader.TokenType == JsonToken.String) { return new Container(reader.Value as string); } diff --git a/src/Protocol/Serialization/Converters/MarkedStringConverter.cs b/src/Protocol/Serialization/Converters/MarkedStringConverter.cs index 5cff15be0..f9c873ea1 100644 --- a/src/Protocol/Serialization/Converters/MarkedStringConverter.cs +++ b/src/Protocol/Serialization/Converters/MarkedStringConverter.cs @@ -5,7 +5,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class MarkedStringConverter : JsonConverter + internal class MarkedStringConverter : JsonConverter { public override void WriteJson(JsonWriter writer, MarkedString value, JsonSerializer serializer) { @@ -31,6 +31,7 @@ public override MarkedString ReadJson(JsonReader reader, Type objectType, Marked var result = JObject.Load(reader); return new MarkedString(result["language"]?.Value(), result["value"]?.Value()); } + if (reader.TokenType == JsonToken.String) { return new MarkedString(reader.Value as string); diff --git a/src/Protocol/Serialization/Converters/MarkedStringsOrMarkupContentConverter.cs b/src/Protocol/Serialization/Converters/MarkedStringsOrMarkupContentConverter.cs index 21c138a84..196ae284f 100644 --- a/src/Protocol/Serialization/Converters/MarkedStringsOrMarkupContentConverter.cs +++ b/src/Protocol/Serialization/Converters/MarkedStringsOrMarkupContentConverter.cs @@ -19,18 +19,22 @@ public override void WriteJson(JsonWriter writer, MarkedStringsOrMarkupContent v } } - public override MarkedStringsOrMarkupContent ReadJson(JsonReader reader, Type objectType, MarkedStringsOrMarkupContent existingValue, bool hasExistingValue, JsonSerializer serializer) + public override MarkedStringsOrMarkupContent ReadJson( + JsonReader reader, Type objectType, MarkedStringsOrMarkupContent existingValue, bool hasExistingValue, JsonSerializer serializer + ) { if (reader.TokenType == JsonToken.StartObject) { var result = JObject.Load(reader); return new MarkedStringsOrMarkupContent(result.ToObject(serializer)); } + if (reader.TokenType == JsonToken.StartArray) { var result = JArray.Load(reader); return new MarkedStringsOrMarkupContent(result.ToObject>(serializer)); } + if (reader.TokenType == JsonToken.String) { return new MarkedStringsOrMarkupContent(reader.Value as string); diff --git a/src/Protocol/Serialization/Converters/NullableDiagnosticCodeConverter.cs b/src/Protocol/Serialization/Converters/NullableDiagnosticCodeConverter.cs index 902adc7de..34566394b 100644 --- a/src/Protocol/Serialization/Converters/NullableDiagnosticCodeConverter.cs +++ b/src/Protocol/Serialization/Converters/NullableDiagnosticCodeConverter.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class NullableDiagnosticCodeConverter : JsonConverter + internal class NullableDiagnosticCodeConverter : JsonConverter { public override void WriteJson(JsonWriter writer, DiagnosticCode? value, JsonSerializer serializer) { @@ -19,8 +19,10 @@ public override void WriteJson(JsonWriter writer, DiagnosticCode? value, JsonSer } } - public override DiagnosticCode? ReadJson(JsonReader reader, Type objectType, DiagnosticCode? existingValue, - bool hasExistingValue, JsonSerializer serializer) + public override DiagnosticCode? ReadJson( + JsonReader reader, Type objectType, DiagnosticCode? existingValue, + bool hasExistingValue, JsonSerializer serializer + ) { if (reader.TokenType == JsonToken.String) { @@ -37,4 +39,4 @@ public override void WriteJson(JsonWriter writer, DiagnosticCode? value, JsonSer public override bool CanRead => true; } -} \ No newline at end of file +} diff --git a/src/Protocol/Serialization/Converters/NumberEnumConverter.cs b/src/Protocol/Serialization/Converters/NumberEnumConverter.cs index b9b106e30..f318cad3b 100644 --- a/src/Protocol/Serialization/Converters/NumberEnumConverter.cs +++ b/src/Protocol/Serialization/Converters/NumberEnumConverter.cs @@ -5,17 +5,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class NumberEnumConverter : JsonConverter + internal class NumberEnumConverter : JsonConverter { - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - new JValue(value).WriteTo(writer); - } + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => new JValue(value).WriteTo(writer); - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - return Enum.Parse(Nullable.GetUnderlyingType(objectType) ?? objectType, reader.Value.ToString()); - } + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) => Enum.Parse( + Nullable.GetUnderlyingType(objectType) ?? objectType, reader.Value.ToString() + ); public override bool CanRead => true; diff --git a/src/Protocol/Serialization/Converters/ParameterInformationLabelConverter.cs b/src/Protocol/Serialization/Converters/ParameterInformationLabelConverter.cs index 8f96e3f6c..0c9deaf00 100644 --- a/src/Protocol/Serialization/Converters/ParameterInformationLabelConverter.cs +++ b/src/Protocol/Serialization/Converters/ParameterInformationLabelConverter.cs @@ -12,20 +12,24 @@ public override void WriteJson(JsonWriter writer, ParameterInformationLabel valu if (value.IsLabel) serializer.Serialize(writer, value.Label); if (value.IsRange) - serializer.Serialize(writer, new [] { value.Range.start, value.Range.end }); + serializer.Serialize(writer, new[] { value.Range.start, value.Range.end }); } - public override ParameterInformationLabel ReadJson(JsonReader reader, Type objectType, ParameterInformationLabel existingValue, bool hasExistingValue, JsonSerializer serializer) + public override ParameterInformationLabel ReadJson( + JsonReader reader, Type objectType, ParameterInformationLabel existingValue, bool hasExistingValue, JsonSerializer serializer + ) { if (reader.TokenType == JsonToken.String) { - return new ParameterInformationLabel((string)reader.Value); + return new ParameterInformationLabel((string) reader.Value); } + if (reader.TokenType == JsonToken.StartArray) { var a = JArray.Load(reader); - return new ParameterInformationLabel((a[0].ToObject(), a[1].ToObject())); + return new ParameterInformationLabel(( a[0].ToObject(), a[1].ToObject() )); } + throw new NotSupportedException(); } diff --git a/src/Protocol/Serialization/Converters/ProgressTokenConverter.cs b/src/Protocol/Serialization/Converters/ProgressTokenConverter.cs index c2fbd75bc..6be01b373 100644 --- a/src/Protocol/Serialization/Converters/ProgressTokenConverter.cs +++ b/src/Protocol/Serialization/Converters/ProgressTokenConverter.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class ProgressTokenConverter : JsonConverter + internal class ProgressTokenConverter : JsonConverter { public override void WriteJson(JsonWriter writer, ProgressToken value, JsonSerializer serializer) { @@ -17,12 +17,12 @@ public override ProgressToken ReadJson(JsonReader reader, Type objectType, Progr { if (reader.TokenType == JsonToken.Integer) { - return new ProgressToken((long)reader.Value); + return new ProgressToken((long) reader.Value); } if (reader.TokenType == JsonToken.String) { - return new ProgressToken((string)reader.Value); + return new ProgressToken((string) reader.Value); } return new ProgressToken(string.Empty); diff --git a/src/Protocol/Serialization/Converters/RangeOrPlaceholderRangeConverter.cs b/src/Protocol/Serialization/Converters/RangeOrPlaceholderRangeConverter.cs index 31bac1f90..fe8658cb2 100644 --- a/src/Protocol/Serialization/Converters/RangeOrPlaceholderRangeConverter.cs +++ b/src/Protocol/Serialization/Converters/RangeOrPlaceholderRangeConverter.cs @@ -5,7 +5,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class RangeOrPlaceholderRangeConverter : JsonConverter + internal class RangeOrPlaceholderRangeConverter : JsonConverter { public override void WriteJson(JsonWriter writer, RangeOrPlaceholderRange value, JsonSerializer serializer) { @@ -19,10 +19,9 @@ public override void WriteJson(JsonWriter writer, RangeOrPlaceholderRange value, } } - public override RangeOrPlaceholderRange ReadJson(JsonReader reader, Type objectType, RangeOrPlaceholderRange existingValue, bool hasExistingValue, JsonSerializer serializer) - { - return new RangeOrPlaceholderRange((Range) null); - } + public override RangeOrPlaceholderRange ReadJson( + JsonReader reader, Type objectType, RangeOrPlaceholderRange existingValue, bool hasExistingValue, JsonSerializer serializer + ) => new RangeOrPlaceholderRange((Range) null); public override bool CanRead => false; } diff --git a/src/Protocol/Serialization/Converters/SemanticTokensFullOrDeltaConverter.cs b/src/Protocol/Serialization/Converters/SemanticTokensFullOrDeltaConverter.cs index 6c2b59768..33f334569 100644 --- a/src/Protocol/Serialization/Converters/SemanticTokensFullOrDeltaConverter.cs +++ b/src/Protocol/Serialization/Converters/SemanticTokensFullOrDeltaConverter.cs @@ -24,17 +24,17 @@ public override void WriteJson(JsonWriter writer, SemanticTokensFullOrDelta valu } } - public override SemanticTokensFullOrDelta ReadJson(JsonReader reader, Type objectType, SemanticTokensFullOrDelta existingValue, bool hasExistingValue, JsonSerializer serializer) + public override SemanticTokensFullOrDelta ReadJson( + JsonReader reader, Type objectType, SemanticTokensFullOrDelta existingValue, bool hasExistingValue, JsonSerializer serializer + ) { var obj = JObject.Load(reader); if (obj.ContainsKey("data")) { return new SemanticTokensFullOrDelta(obj.ToObject()); } - else - { - return new SemanticTokensFullOrDelta(obj.ToObject()); - } + + return new SemanticTokensFullOrDelta(obj.ToObject()); } public override bool CanRead => true; diff --git a/src/Protocol/Serialization/Converters/SemanticTokensFullOrDeltaPartialResultConverter.cs b/src/Protocol/Serialization/Converters/SemanticTokensFullOrDeltaPartialResultConverter.cs index f131bcd72..4619a6863 100644 --- a/src/Protocol/Serialization/Converters/SemanticTokensFullOrDeltaPartialResultConverter.cs +++ b/src/Protocol/Serialization/Converters/SemanticTokensFullOrDeltaPartialResultConverter.cs @@ -24,17 +24,17 @@ public override void WriteJson(JsonWriter writer, SemanticTokensFullOrDeltaParti } } - public override SemanticTokensFullOrDeltaPartialResult ReadJson(JsonReader reader, Type objectType, SemanticTokensFullOrDeltaPartialResult existingValue, bool hasExistingValue, JsonSerializer serializer) + public override SemanticTokensFullOrDeltaPartialResult ReadJson( + JsonReader reader, Type objectType, SemanticTokensFullOrDeltaPartialResult existingValue, bool hasExistingValue, JsonSerializer serializer + ) { var obj = JObject.Load(reader); if (obj.ContainsKey("data")) { return new SemanticTokensFullOrDeltaPartialResult(obj.ToObject()); } - else - { - return new SemanticTokensFullOrDeltaPartialResult(obj.ToObject()); - } + + return new SemanticTokensFullOrDeltaPartialResult(obj.ToObject()); } public override bool CanRead => true; diff --git a/src/Protocol/Serialization/Converters/StringOrMarkupContentConverter.cs b/src/Protocol/Serialization/Converters/StringOrMarkupContentConverter.cs index 0d91478c5..c76b03fec 100644 --- a/src/Protocol/Serialization/Converters/StringOrMarkupContentConverter.cs +++ b/src/Protocol/Serialization/Converters/StringOrMarkupContentConverter.cs @@ -25,12 +25,13 @@ public override StringOrMarkupContent ReadJson(JsonReader reader, Type objectTyp { var result = JObject.Load(reader); return new StringOrMarkupContent( - new MarkupContent() { + new MarkupContent { Kind = Enum.TryParse(result["kind"]?.Value(), true, out var kind) ? kind : MarkupKind.PlainText, Value = result["value"]?.Value() } ); } + if (reader.TokenType == JsonToken.String) { return new StringOrMarkupContent(reader.Value as string); diff --git a/src/Protocol/Serialization/Converters/SupportsConverter.cs b/src/Protocol/Serialization/Converters/SupportsConverter.cs index a18e3783b..8da995067 100644 --- a/src/Protocol/Serialization/Converters/SupportsConverter.cs +++ b/src/Protocol/Serialization/Converters/SupportsConverter.cs @@ -4,33 +4,36 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class SupportsConverter : JsonConverter + internal class SupportsConverter : JsonConverter { private static readonly MethodInfo OfValueMethod = typeof(Supports) - .GetTypeInfo() - .GetMethod(nameof(Supports.OfValue), BindingFlags.Static | BindingFlags.Public); + .GetTypeInfo() + .GetMethod(nameof(Supports.OfValue), BindingFlags.Static | BindingFlags.Public); + private static readonly MethodInfo OfBooleanMethod = typeof(Supports) - .GetTypeInfo() - .GetMethod(nameof(Supports.OfBoolean), BindingFlags.Static | BindingFlags.Public); + .GetTypeInfo() + .GetMethod(nameof(Supports.OfBoolean), BindingFlags.Static | BindingFlags.Public); private static readonly PropertyInfo ValueProperty = typeof(Supports<>) - .GetTypeInfo() - .GetProperty(nameof(Supports.Value), BindingFlags.Public | BindingFlags.Instance); + .GetTypeInfo() + .GetProperty(nameof(Supports.Value), BindingFlags.Public | BindingFlags.Instance); private static readonly PropertyInfo IsSupportedProperty = typeof(Supports<>) - .GetTypeInfo() - .GetProperty(nameof(Supports.IsSupported), BindingFlags.Public | BindingFlags.Instance); + .GetTypeInfo() + .GetProperty(nameof(Supports.IsSupported), BindingFlags.Public | BindingFlags.Instance); public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var isSupported = value?.GetType().GetTypeInfo() - ?.GetProperty(nameof(Supports.IsSupported), BindingFlags.Public | BindingFlags.Instance) - ?.GetValue(value) as bool?; + ?.GetProperty(nameof(Supports.IsSupported), BindingFlags.Public | BindingFlags.Instance) + ?.GetValue(value) as bool?; if (isSupported == true) { - serializer.Serialize(writer, value.GetType().GetTypeInfo() - .GetProperty(nameof(Supports.Value), BindingFlags.Public | BindingFlags.Instance) - .GetValue(value)); + serializer.Serialize( + writer, value.GetType().GetTypeInfo() + .GetProperty(nameof(Supports.Value), BindingFlags.Public | BindingFlags.Instance) + .GetValue(value) + ); } else { @@ -45,11 +48,12 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist { if (targetType == typeof(bool)) { - return new Supports(true, (bool)reader.Value); + return new Supports(true, (bool) reader.Value); } + return OfBooleanMethod - .MakeGenericMethod(targetType) - .Invoke(null, new [] { reader.Value }); + .MakeGenericMethod(targetType) + .Invoke(null, new[] { reader.Value }); } if (targetType == typeof(bool)) @@ -60,8 +64,8 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist var target = serializer.Deserialize(reader, targetType); return OfValueMethod - .MakeGenericMethod(targetType) - .Invoke(null, new[] {target}); + .MakeGenericMethod(targetType) + .Invoke(null, new[] { target }); } public override bool CanRead => true; diff --git a/src/Protocol/Serialization/Converters/SymbolInformationOrDocumentSymbolConverter.cs b/src/Protocol/Serialization/Converters/SymbolInformationOrDocumentSymbolConverter.cs index eb66599b6..7c813c962 100644 --- a/src/Protocol/Serialization/Converters/SymbolInformationOrDocumentSymbolConverter.cs +++ b/src/Protocol/Serialization/Converters/SymbolInformationOrDocumentSymbolConverter.cs @@ -23,7 +23,9 @@ public override void WriteJson(JsonWriter writer, SymbolInformationOrDocumentSym } } - public override SymbolInformationOrDocumentSymbol ReadJson(JsonReader reader, Type objectType, SymbolInformationOrDocumentSymbol existingValue, bool hasExistingValue, JsonSerializer serializer) + public override SymbolInformationOrDocumentSymbol ReadJson( + JsonReader reader, Type objectType, SymbolInformationOrDocumentSymbol existingValue, bool hasExistingValue, JsonSerializer serializer + ) { var result = JObject.Load(reader); @@ -32,10 +34,8 @@ public override SymbolInformationOrDocumentSymbol ReadJson(JsonReader reader, Ty { return new SymbolInformationOrDocumentSymbol(result.ToObject()); } - else - { - return new SymbolInformationOrDocumentSymbol(result.ToObject()); - } + + return new SymbolInformationOrDocumentSymbol(result.ToObject()); } public override bool CanRead => true; diff --git a/src/Protocol/Serialization/Converters/TextDocumentSyncConverter.cs b/src/Protocol/Serialization/Converters/TextDocumentSyncConverter.cs index 4055e641d..48f9ba612 100644 --- a/src/Protocol/Serialization/Converters/TextDocumentSyncConverter.cs +++ b/src/Protocol/Serialization/Converters/TextDocumentSyncConverter.cs @@ -5,7 +5,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class TextDocumentSyncConverter : JsonConverter + internal class TextDocumentSyncConverter : JsonConverter { public override void WriteJson(JsonWriter writer, TextDocumentSync value, JsonSerializer serializer) { @@ -23,7 +23,7 @@ public override TextDocumentSync ReadJson(JsonReader reader, Type objectType, Te { if (reader.TokenType == JsonToken.Integer) { - return new TextDocumentSync((TextDocumentSyncKind)Convert.ToInt32(reader.Value)); + return new TextDocumentSync((TextDocumentSyncKind) Convert.ToInt32(reader.Value)); } return new TextDocumentSync(JObject.Load(reader).ToObject(serializer)); diff --git a/src/Protocol/Serialization/Converters/ValueTupleContractResolver.cs b/src/Protocol/Serialization/Converters/ValueTupleContractResolver.cs index 754a53ba4..1459b002e 100644 --- a/src/Protocol/Serialization/Converters/ValueTupleContractResolver.cs +++ b/src/Protocol/Serialization/Converters/ValueTupleContractResolver.cs @@ -4,17 +4,14 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { - class ValueTupleContractResolver : JsonConverter<(T1, T2)> + internal class ValueTupleContractResolver : JsonConverter<(T1, T2)> { - public override void WriteJson(JsonWriter writer, (T1, T2) value, JsonSerializer serializer) - { - serializer.Serialize(writer, new object[] { value.Item1, value.Item2 }); - } + public override void WriteJson(JsonWriter writer, (T1, T2) value, JsonSerializer serializer) => serializer.Serialize(writer, new object[] { value.Item1, value.Item2 }); public override (T1, T2) ReadJson(JsonReader reader, Type objectType, (T1, T2) existingValue, bool hasExistingValue, JsonSerializer serializer) { var a = JArray.Load(reader); - return (a.ToObject(), a.ToObject()); + return ( a.ToObject(), a.ToObject() ); } } -} \ No newline at end of file +} diff --git a/src/Protocol/Serialization/Converters/WorkspaceEditDocumentChangeConverter.cs b/src/Protocol/Serialization/Converters/WorkspaceEditDocumentChangeConverter.cs index de3695e89..c247adef3 100644 --- a/src/Protocol/Serialization/Converters/WorkspaceEditDocumentChangeConverter.cs +++ b/src/Protocol/Serialization/Converters/WorkspaceEditDocumentChangeConverter.cs @@ -15,7 +15,9 @@ public override void WriteJson(JsonWriter writer, WorkspaceEditDocumentChange va if (value.IsTextDocumentEdit) serializer.Serialize(writer, value.TextDocumentEdit); } - public override WorkspaceEditDocumentChange ReadJson(JsonReader reader, Type objectType, WorkspaceEditDocumentChange existingValue, bool hasExistingValue, JsonSerializer serializer) + public override WorkspaceEditDocumentChange ReadJson( + JsonReader reader, Type objectType, WorkspaceEditDocumentChange existingValue, bool hasExistingValue, JsonSerializer serializer + ) { var obj = JObject.Load(reader); if (obj.ContainsKey("kind")) @@ -33,10 +35,8 @@ public override WorkspaceEditDocumentChange ReadJson(JsonReader reader, Type obj throw new NotSupportedException("Object with " + kind + " is not supported"); } } - else - { - return new WorkspaceEditDocumentChange(obj.ToObject()); - } + + return new WorkspaceEditDocumentChange(obj.ToObject()); } public override bool CanRead => true; diff --git a/src/Protocol/Serialization/ISerializer.cs b/src/Protocol/Serialization/ISerializer.cs index b51e923eb..54a8770cb 100644 --- a/src/Protocol/Serialization/ISerializer.cs +++ b/src/Protocol/Serialization/ISerializer.cs @@ -2,7 +2,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization { - public interface ISerializer : OmniSharp.Extensions.JsonRpc.ISerializer + public interface ISerializer : JsonRpc.ISerializer { void SetClientCapabilities(ClientVersion clientVersion, ClientCapabilities clientCapabilities); } diff --git a/src/Protocol/Serialization/OptionalAttribute.cs b/src/Protocol/Serialization/OptionalAttribute.cs index de8b6c2e0..e00916d22 100644 --- a/src/Protocol/Serialization/OptionalAttribute.cs +++ b/src/Protocol/Serialization/OptionalAttribute.cs @@ -3,5 +3,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization { [AttributeUsage(AttributeTargets.Property)] - class OptionalAttribute : Attribute { } + internal class OptionalAttribute : Attribute + { + } } diff --git a/src/Protocol/Serialization/Serializer.cs b/src/Protocol/Serialization/Serializer.cs index f474bba88..08819b141 100644 --- a/src/Protocol/Serialization/Serializer.cs +++ b/src/Protocol/Serialization/Serializer.cs @@ -6,41 +6,41 @@ using OmniSharp.Extensions.JsonRpc.Serialization; using OmniSharp.Extensions.JsonRpc.Serialization.Converters; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; -using OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters; using OmniSharp.Extensions.LanguageServer.Protocol.Models; +using OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters; namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization { public class Serializer : JsonRpcSerializer, ISerializer { private static readonly CompletionItemKind[] DefaultCompletionItemKinds = Enum - .GetValues(typeof(CompletionItemKind)) - .Cast() - .ToArray(); + .GetValues(typeof(CompletionItemKind)) + .Cast() + .ToArray(); private static readonly CompletionItemTag[] DefaultCompletionItemTags = Enum - .GetValues(typeof(CompletionItemTag)) - .Cast() - .ToArray(); + .GetValues(typeof(CompletionItemTag)) + .Cast() + .ToArray(); private static readonly SymbolKind[] DefaultSymbolKinds = Enum.GetValues(typeof(SymbolKind)) - .Cast() - .ToArray(); + .Cast() + .ToArray(); private static readonly SymbolTag[] DefaultSymbolTags = Enum.GetValues(typeof(SymbolTag)) - .Cast() - .ToArray(); + .Cast() + .ToArray(); private static readonly DiagnosticTag[] DefaultDiagnosticTags = Enum.GetValues(typeof(DiagnosticTag)) - .Cast() - .ToArray(); + .Cast() + .ToArray(); private static readonly CodeActionKind[] DefaultCodeActionKinds = typeof(CodeActionKind).GetFields(BindingFlags.Static | BindingFlags.Public) - .Select(z => z.GetValue(null) ) - .Cast() - .ToArray(); + .Select(z => z.GetValue(null)) + .Cast() + .ToArray(); - public ClientVersion ClientVersion { get; private set; } + public ClientVersion ClientVersion { get; } public static Serializer Instance { get; } = new Serializer(); @@ -48,10 +48,7 @@ public Serializer() : this(ClientVersion.Lsp3) { } - public Serializer(ClientVersion clientVersion) - { - ClientVersion = clientVersion; - } + public Serializer(ClientVersion clientVersion) => ClientVersion = clientVersion; protected override JsonSerializer CreateSerializer() @@ -156,6 +153,7 @@ public void SetClientCapabilities(ClientVersion clientVersion, ClientCapabilitie { documentSymbolKinds = symbolKindSet.ToArray(); } + var valueSet = symbol?.TagSupport.Value?.ValueSet; if (valueSet != null) { @@ -171,6 +169,7 @@ public void SetClientCapabilities(ClientVersion clientVersion, ClientCapabilitie { workspaceSymbolKinds = symbolKindSet.ToArray(); } + var tagSupportSet = symbol?.TagSupport.Value?.ValueSet; if (tagSupportSet != null) { diff --git a/src/Protocol/Server/Capabilities/CodeActionOptions.cs b/src/Protocol/Server/Capabilities/CodeActionOptions.cs index 2aa5e47aa..04be75d70 100644 --- a/src/Protocol/Server/Capabilities/CodeActionOptions.cs +++ b/src/Protocol/Server/Capabilities/CodeActionOptions.cs @@ -16,12 +16,10 @@ public class CodeActionOptions : WorkDoneProgressOptions, ICodeActionOptions [Optional] public Container CodeActionKinds { get; set; } - public static CodeActionOptions Of(ICodeActionOptions options, IEnumerable descriptors) - { - return new CodeActionOptions() { + public static CodeActionOptions Of(ICodeActionOptions options, IEnumerable descriptors) => + new CodeActionOptions { CodeActionKinds = options.CodeActionKinds, WorkDoneProgress = options.WorkDoneProgress, }; - } } } diff --git a/src/Protocol/Server/Capabilities/CodeLensOptions.cs b/src/Protocol/Server/Capabilities/CodeLensOptions.cs index 692ce6ef0..5a8a9eed8 100644 --- a/src/Protocol/Server/Capabilities/CodeLensOptions.cs +++ b/src/Protocol/Server/Capabilities/CodeLensOptions.cs @@ -8,22 +8,20 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { /// - /// Code Lens options. + /// Code Lens options. /// public class CodeLensOptions : WorkDoneProgressOptions, ICodeLensOptions { /// - /// Code lens has a resolve provider as well. + /// Code lens has a resolve provider as well. /// [Optional] public bool ResolveProvider { get; set; } - public static CodeLensOptions Of(ICodeLensOptions options, IEnumerable descriptors) - { - return new CodeLensOptions() { + public static CodeLensOptions Of(ICodeLensOptions options, IEnumerable descriptors) => + new CodeLensOptions { ResolveProvider = options.ResolveProvider || descriptors.Any(z => z.HandlerType == typeof(ICodeLensResolveHandler)), WorkDoneProgress = options.WorkDoneProgress }; - } } } diff --git a/src/Protocol/Server/Capabilities/CompletionOptions.cs b/src/Protocol/Server/Capabilities/CompletionOptions.cs index 572bb6b62..a0cb70271 100644 --- a/src/Protocol/Server/Capabilities/CompletionOptions.cs +++ b/src/Protocol/Server/Capabilities/CompletionOptions.cs @@ -8,7 +8,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { /// - /// Completion options. + /// Completion options. /// public class CompletionOptions : WorkDoneProgressOptions, ICompletionOptions { @@ -42,15 +42,12 @@ public class CompletionOptions : WorkDoneProgressOptions, ICompletionOptions [Optional] public Container AllCommitCharacters { get; set; } - public static CompletionOptions Of(ICompletionOptions options, IEnumerable descriptors) - { - return new CompletionOptions() - { + public static CompletionOptions Of(ICompletionOptions options, IEnumerable descriptors) => + new CompletionOptions { ResolveProvider = options.ResolveProvider || descriptors.Any(z => z.HandlerType == typeof(ICompletionResolveHandler)), AllCommitCharacters = options.AllCommitCharacters, TriggerCharacters = options.TriggerCharacters, WorkDoneProgress = options.WorkDoneProgress, }; - } } } diff --git a/src/Protocol/Server/Capabilities/DeclarationOptions.cs b/src/Protocol/Server/Capabilities/DeclarationOptions.cs index 35640a2a5..c706ff6cd 100644 --- a/src/Protocol/Server/Capabilities/DeclarationOptions.cs +++ b/src/Protocol/Server/Capabilities/DeclarationOptions.cs @@ -6,12 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class DeclarationOptions : StaticWorkDoneTextDocumentRegistrationOptions, IDeclarationOptions { - public static DeclarationOptions Of(IDeclarationOptions options, IEnumerable descriptors) - { - return new DeclarationOptions() - { + public static DeclarationOptions Of(IDeclarationOptions options, IEnumerable descriptors) => + new DeclarationOptions { WorkDoneProgress = options.WorkDoneProgress }; - } } } diff --git a/src/Protocol/Server/Capabilities/DefinitionOptions.cs b/src/Protocol/Server/Capabilities/DefinitionOptions.cs index 62a081c0e..11d6445f1 100644 --- a/src/Protocol/Server/Capabilities/DefinitionOptions.cs +++ b/src/Protocol/Server/Capabilities/DefinitionOptions.cs @@ -6,12 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class DefinitionOptions : StaticWorkDoneTextDocumentRegistrationOptions, IDefinitionOptions { - public static DefinitionOptions Of(IDefinitionOptions options, IEnumerable descriptors) - { - return new DefinitionOptions() - { + public static DefinitionOptions Of(IDefinitionOptions options, IEnumerable descriptors) => + new DefinitionOptions { WorkDoneProgress = options.WorkDoneProgress, }; - } } } diff --git a/src/Protocol/Server/Capabilities/DocumentColorOptions.cs b/src/Protocol/Server/Capabilities/DocumentColorOptions.cs index 351f1057f..983eb8ddf 100644 --- a/src/Protocol/Server/Capabilities/DocumentColorOptions.cs +++ b/src/Protocol/Server/Capabilities/DocumentColorOptions.cs @@ -6,11 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class DocumentColorOptions : StaticWorkDoneTextDocumentRegistrationOptions, IDocumentColorOptions { - public static DocumentColorOptions Of(IDocumentColorOptions options, IEnumerable descriptors) - { - return new DocumentColorOptions() { + public static DocumentColorOptions Of(IDocumentColorOptions options, IEnumerable descriptors) => + new DocumentColorOptions { WorkDoneProgress = options.WorkDoneProgress, }; - } } } diff --git a/src/Protocol/Server/Capabilities/DocumentFormattingOptions.cs b/src/Protocol/Server/Capabilities/DocumentFormattingOptions.cs index 296ad3645..0adda0e79 100644 --- a/src/Protocol/Server/Capabilities/DocumentFormattingOptions.cs +++ b/src/Protocol/Server/Capabilities/DocumentFormattingOptions.cs @@ -6,12 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class DocumentFormattingOptions : WorkDoneProgressOptions, IDocumentFormattingOptions { - public static DocumentFormattingOptions Of(IDocumentFormattingOptions options, IEnumerable descriptors) - { - return new DocumentFormattingOptions() - { + public static DocumentFormattingOptions Of(IDocumentFormattingOptions options, IEnumerable descriptors) => + new DocumentFormattingOptions { WorkDoneProgress = options.WorkDoneProgress }; - } } } diff --git a/src/Protocol/Server/Capabilities/DocumentHighlightOptions.cs b/src/Protocol/Server/Capabilities/DocumentHighlightOptions.cs index 335d0b07a..f0d3fb1ef 100644 --- a/src/Protocol/Server/Capabilities/DocumentHighlightOptions.cs +++ b/src/Protocol/Server/Capabilities/DocumentHighlightOptions.cs @@ -6,12 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class DocumentHighlightOptions : WorkDoneProgressOptions, IDocumentHighlightOptions { - public static DocumentHighlightOptions Of(IDocumentHighlightOptions options, IEnumerable descriptors) - { - return new DocumentHighlightOptions() - { + public static DocumentHighlightOptions Of(IDocumentHighlightOptions options, IEnumerable descriptors) => + new DocumentHighlightOptions { WorkDoneProgress = options.WorkDoneProgress }; - } } } diff --git a/src/Protocol/Server/Capabilities/DocumentLinkOptions.cs b/src/Protocol/Server/Capabilities/DocumentLinkOptions.cs index 8e6cae866..58d54e74f 100644 --- a/src/Protocol/Server/Capabilities/DocumentLinkOptions.cs +++ b/src/Protocol/Server/Capabilities/DocumentLinkOptions.cs @@ -8,22 +8,20 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { /// - /// Document link options + /// Document link options /// public class DocumentLinkOptions : WorkDoneProgressOptions, IDocumentLinkOptions { /// - /// Document links have a resolve provider as well. + /// Document links have a resolve provider as well. /// [Optional] public bool ResolveProvider { get; set; } - public static DocumentLinkOptions Of(IDocumentLinkOptions options, IEnumerable descriptors) - { - return new DocumentLinkOptions() { - ResolveProvider = options.ResolveProvider || descriptors.Any(z => z.HandlerType == typeof(IDocumentLinkResolveHandler)) , + public static DocumentLinkOptions Of(IDocumentLinkOptions options, IEnumerable descriptors) => + new DocumentLinkOptions { + ResolveProvider = options.ResolveProvider || descriptors.Any(z => z.HandlerType == typeof(IDocumentLinkResolveHandler)), WorkDoneProgress = options.WorkDoneProgress, }; - } } } diff --git a/src/Protocol/Server/Capabilities/DocumentOnTypeFormattingOptions.cs b/src/Protocol/Server/Capabilities/DocumentOnTypeFormattingOptions.cs index 3ad5f25ac..2dc12e6d1 100644 --- a/src/Protocol/Server/Capabilities/DocumentOnTypeFormattingOptions.cs +++ b/src/Protocol/Server/Capabilities/DocumentOnTypeFormattingOptions.cs @@ -6,28 +6,25 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { /// - /// Format document on type options + /// Format document on type options /// public class DocumentOnTypeFormattingOptions : IDocumentOnTypeFormattingOptions { /// - /// A character on which formatting should be triggered, like `}`. + /// A character on which formatting should be triggered, like `}`. /// public string FirstTriggerCharacter { get; set; } /// - /// More trigger characters. + /// More trigger characters. /// [Optional] public Container MoreTriggerCharacter { get; set; } - public static DocumentOnTypeFormattingOptions Of(IDocumentOnTypeFormattingOptions options, IEnumerable descriptors) - { - return new DocumentOnTypeFormattingOptions() - { + public static DocumentOnTypeFormattingOptions Of(IDocumentOnTypeFormattingOptions options, IEnumerable descriptors) => + new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = options.FirstTriggerCharacter, MoreTriggerCharacter = options.MoreTriggerCharacter, }; - } } } diff --git a/src/Protocol/Server/Capabilities/DocumentRangeFormattingOptions.cs b/src/Protocol/Server/Capabilities/DocumentRangeFormattingOptions.cs index d9416bcff..a570b54cc 100644 --- a/src/Protocol/Server/Capabilities/DocumentRangeFormattingOptions.cs +++ b/src/Protocol/Server/Capabilities/DocumentRangeFormattingOptions.cs @@ -6,13 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class DocumentRangeFormattingOptions : WorkDoneProgressOptions, IDocumentRangeFormattingOptions { - public static DocumentRangeFormattingOptions Of(IDocumentRangeFormattingOptions options, IEnumerable descriptors) - { - return new DocumentRangeFormattingOptions() - { + public static DocumentRangeFormattingOptions Of(IDocumentRangeFormattingOptions options, IEnumerable descriptors) => + new DocumentRangeFormattingOptions { WorkDoneProgress = options.WorkDoneProgress, - }; - } } } diff --git a/src/Protocol/Server/Capabilities/DocumentSymbolOptions.cs b/src/Protocol/Server/Capabilities/DocumentSymbolOptions.cs index ace0ed2ac..bacb2e66f 100644 --- a/src/Protocol/Server/Capabilities/DocumentSymbolOptions.cs +++ b/src/Protocol/Server/Capabilities/DocumentSymbolOptions.cs @@ -6,12 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class DocumentSymbolOptions : WorkDoneProgressOptions, IDocumentSymbolOptions { - public static DocumentSymbolOptions Of(IDocumentSymbolOptions options, IEnumerable descriptors) - { - return new DocumentSymbolOptions() { + public static DocumentSymbolOptions Of(IDocumentSymbolOptions options, IEnumerable descriptors) => + new DocumentSymbolOptions { WorkDoneProgress = options.WorkDoneProgress, - }; - } } } diff --git a/src/Protocol/Server/Capabilities/DocumentSymbolOptionsOptions.cs b/src/Protocol/Server/Capabilities/DocumentSymbolOptionsOptions.cs index c0352c5bc..ac087f598 100644 --- a/src/Protocol/Server/Capabilities/DocumentSymbolOptionsOptions.cs +++ b/src/Protocol/Server/Capabilities/DocumentSymbolOptionsOptions.cs @@ -6,12 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class DocumentSymbolOptionsOptions : WorkDoneProgressOptions, IDocumentSymbolOptionsOptions { - public static DocumentSymbolOptionsOptions Of(IDocumentSymbolOptionsOptions options, IEnumerable descriptors) - { - return new DocumentSymbolOptionsOptions() - { + public static DocumentSymbolOptionsOptions Of(IDocumentSymbolOptionsOptions options, IEnumerable descriptors) => + new DocumentSymbolOptionsOptions { WorkDoneProgress = options.WorkDoneProgress }; - } } } diff --git a/src/Protocol/Server/Capabilities/ExecuteCommandOptions.cs b/src/Protocol/Server/Capabilities/ExecuteCommandOptions.cs index 2e659d1eb..b284283c8 100644 --- a/src/Protocol/Server/Capabilities/ExecuteCommandOptions.cs +++ b/src/Protocol/Server/Capabilities/ExecuteCommandOptions.cs @@ -6,21 +6,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { /// - /// Execute command options. + /// Execute command options. /// public class ExecuteCommandOptions : WorkDoneProgressOptions, IExecuteCommandOptions { /// - /// The commands to be executed on the server + /// The commands to be executed on the server /// public Container Commands { get; set; } - public static ExecuteCommandOptions Of(IEnumerable options, IEnumerable descriptors) - { - return new ExecuteCommandOptions() { + public static ExecuteCommandOptions Of(IEnumerable options, IEnumerable descriptors) => + new ExecuteCommandOptions { Commands = options.SelectMany(x => x.Commands).ToArray(), WorkDoneProgress = options.Any(x => x.WorkDoneProgress) }; - } } } diff --git a/src/Protocol/Server/Capabilities/FoldingRangeOptions.cs b/src/Protocol/Server/Capabilities/FoldingRangeOptions.cs index 00e176cbe..7d0dddb85 100644 --- a/src/Protocol/Server/Capabilities/FoldingRangeOptions.cs +++ b/src/Protocol/Server/Capabilities/FoldingRangeOptions.cs @@ -6,11 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class FoldingRangeOptions : StaticWorkDoneTextDocumentRegistrationOptions, IFoldingRangeOptions { - public static FoldingRangeOptions Of(IFoldingRangeOptions options, IEnumerable descriptors) - { - return new FoldingRangeOptions() { + public static FoldingRangeOptions Of(IFoldingRangeOptions options, IEnumerable descriptors) => + new FoldingRangeOptions { WorkDoneProgress = options.WorkDoneProgress, }; - } } } diff --git a/src/Protocol/Server/Capabilities/HoverOptions.cs b/src/Protocol/Server/Capabilities/HoverOptions.cs index 7bcea1e06..24f5d1d76 100644 --- a/src/Protocol/Server/Capabilities/HoverOptions.cs +++ b/src/Protocol/Server/Capabilities/HoverOptions.cs @@ -6,13 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class HoverOptions : WorkDoneProgressOptions, IHoverOptions { - public static HoverOptions Of(IHoverOptions options, IEnumerable descriptors) - { - return new HoverOptions() - { + public static HoverOptions Of(IHoverOptions options, IEnumerable descriptors) => + new HoverOptions { WorkDoneProgress = options.WorkDoneProgress, - }; - } } } diff --git a/src/Protocol/Server/Capabilities/ImplementationOptions.cs b/src/Protocol/Server/Capabilities/ImplementationOptions.cs index 6c1c90628..7e0d6cfa5 100644 --- a/src/Protocol/Server/Capabilities/ImplementationOptions.cs +++ b/src/Protocol/Server/Capabilities/ImplementationOptions.cs @@ -6,14 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class ImplementationOptions : StaticWorkDoneTextDocumentRegistrationOptions, IImplementationOptions { - public static ImplementationOptions Of(IImplementationOptions options, IEnumerable descriptors) - { - return new ImplementationOptions() - { + public static ImplementationOptions Of(IImplementationOptions options, IEnumerable descriptors) => + new ImplementationOptions { WorkDoneProgress = options.WorkDoneProgress, - - }; - } } } diff --git a/src/Protocol/Server/Capabilities/ReferencesOptions.cs b/src/Protocol/Server/Capabilities/ReferencesOptions.cs index 210efe79a..cabac031b 100644 --- a/src/Protocol/Server/Capabilities/ReferencesOptions.cs +++ b/src/Protocol/Server/Capabilities/ReferencesOptions.cs @@ -6,13 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class ReferencesOptions : WorkDoneProgressOptions, IReferencesOptions { - public static ReferencesOptions Of(IReferencesOptions options, IEnumerable descriptors) - { - return new ReferencesOptions() - { + public static ReferencesOptions Of(IReferencesOptions options, IEnumerable descriptors) => + new ReferencesOptions { WorkDoneProgress = options.WorkDoneProgress, - }; - } } } diff --git a/src/Protocol/Server/Capabilities/RenameOptions.cs b/src/Protocol/Server/Capabilities/RenameOptions.cs index 6ccc7bc78..0b5815696 100644 --- a/src/Protocol/Server/Capabilities/RenameOptions.cs +++ b/src/Protocol/Server/Capabilities/RenameOptions.cs @@ -15,12 +15,10 @@ public class RenameOptions : WorkDoneProgressOptions, IRenameOptions [Optional] public bool PrepareProvider { get; set; } - public static RenameOptions Of(IRenameOptions options, IEnumerable descriptors) - { - return new RenameOptions() { + public static RenameOptions Of(IRenameOptions options, IEnumerable descriptors) => + new RenameOptions { PrepareProvider = options.PrepareProvider || descriptors.Any(z => z.HandlerType == typeof(IPrepareRenameHandler)), WorkDoneProgress = options.WorkDoneProgress }; - } } } diff --git a/src/Protocol/Server/Capabilities/SaveOptions.cs b/src/Protocol/Server/Capabilities/SaveOptions.cs index ad75eca8a..4a9085e98 100644 --- a/src/Protocol/Server/Capabilities/SaveOptions.cs +++ b/src/Protocol/Server/Capabilities/SaveOptions.cs @@ -3,12 +3,12 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { /// - /// Save options. + /// Save options. /// public class SaveOptions { /// - /// The client is supposed to include the content on save. + /// The client is supposed to include the content on save. /// [Optional] public bool IncludeText { get; set; } diff --git a/src/Protocol/Server/Capabilities/SelectionRangeOptions.cs b/src/Protocol/Server/Capabilities/SelectionRangeOptions.cs index c7a43671d..ae4da3a59 100644 --- a/src/Protocol/Server/Capabilities/SelectionRangeOptions.cs +++ b/src/Protocol/Server/Capabilities/SelectionRangeOptions.cs @@ -6,12 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class SelectionRangeOptions : StaticWorkDoneTextDocumentRegistrationOptions, ISelectionRangeOptions { - public static SelectionRangeOptions Of(ISelectionRangeOptions options, IEnumerable descriptors) - { - return new SelectionRangeOptions() - { + public static SelectionRangeOptions Of(ISelectionRangeOptions options, IEnumerable descriptors) => + new SelectionRangeOptions { WorkDoneProgress = options.WorkDoneProgress, }; - } } } diff --git a/src/Protocol/Server/Capabilities/ServerCapabilities.cs b/src/Protocol/Server/Capabilities/ServerCapabilities.cs index 718538256..187914880 100644 --- a/src/Protocol/Server/Capabilities/ServerCapabilities.cs +++ b/src/Protocol/Server/Capabilities/ServerCapabilities.cs @@ -14,110 +14,110 @@ public class ServerCapabilities // Create the ability to look at the client capabilities to determine what parts we need to answer now (completion for example) /// - /// Defines how text documents are synced. Is either a detailed structure defining each notification or - /// for backwards compatibility the TextDocumentSyncKind number. + /// Defines how text documents are synced. Is either a detailed structure defining each notification or + /// for backwards compatibility the TextDocumentSyncKind number. /// [Optional] public TextDocumentSync TextDocumentSync { get; set; } /// - /// The server provides hover support. + /// The server provides hover support. /// [Optional] public BooleanOr HoverProvider { get; set; } /// - /// The server provides completion support. + /// The server provides completion support. /// [Optional] public CompletionOptions CompletionProvider { get; set; } /// - /// The server provides signature help support. + /// The server provides signature help support. /// [Optional] public SignatureHelpOptions SignatureHelpProvider { get; set; } /// - /// The server provides goto definition support. + /// The server provides goto definition support. /// [Optional] public BooleanOr DefinitionProvider { get; set; } /// - /// The server provides find references support. + /// The server provides find references support. /// [Optional] public BooleanOr ReferencesProvider { get; set; } /// - /// The server provides document highlight support. + /// The server provides document highlight support. /// [Optional] public BooleanOr DocumentHighlightProvider { get; set; } /// - /// The server provides document symbol support. + /// The server provides document symbol support. /// [Optional] public BooleanOr DocumentSymbolProvider { get; set; } /// - /// The server provides workspace symbol support. + /// The server provides workspace symbol support. /// [Optional] public BooleanOr WorkspaceSymbolProvider { get; set; } /// - /// The server provides code actions. + /// The server provides code actions. /// [Optional] public BooleanOr CodeActionProvider { get; set; } /// - /// The server provides code lens. + /// The server provides code lens. /// [Optional] public CodeLensOptions CodeLensProvider { get; set; } /// - /// The server provides document formatting. + /// The server provides document formatting. /// [Optional] public BooleanOr DocumentFormattingProvider { get; set; } /// - /// The server provides document range formatting. + /// The server provides document range formatting. /// [Optional] public BooleanOr DocumentRangeFormattingProvider { get; set; } /// - /// The server provides document formatting on typing. + /// The server provides document formatting on typing. /// [Optional] public DocumentOnTypeFormattingOptions DocumentOnTypeFormattingProvider { get; set; } /// - /// The server provides rename support. + /// The server provides rename support. /// [Optional] public BooleanOr RenameProvider { get; set; } /// - /// The server provides document link support. + /// The server provides document link support. /// [Optional] public DocumentLinkOptions DocumentLinkProvider { get; set; } /// - /// The server provides execute command support. + /// The server provides execute command support. /// [Optional] public ExecuteCommandOptions ExecuteCommandProvider { get; set; } /// - /// Experimental server capabilities. + /// Experimental server capabilities. /// [Optional] public IDictionary Experimental { get; set; } = new Dictionary(); diff --git a/src/Protocol/Server/Capabilities/SignatureHelpOptions.cs b/src/Protocol/Server/Capabilities/SignatureHelpOptions.cs index 0377c88d4..b0026ad5b 100644 --- a/src/Protocol/Server/Capabilities/SignatureHelpOptions.cs +++ b/src/Protocol/Server/Capabilities/SignatureHelpOptions.cs @@ -6,7 +6,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { /// - /// Signature help options. + /// Signature help options. /// public class SignatureHelpOptions : WorkDoneProgressOptions, ISignatureHelpOptions { @@ -28,9 +28,7 @@ public class SignatureHelpOptions : WorkDoneProgressOptions, ISignatureHelpOptio [Optional] public Container RetriggerCharacters { get; set; } - public static SignatureHelpOptions Of(ISignatureHelpOptions options, IEnumerable descriptors) - { - return new SignatureHelpOptions() { TriggerCharacters = options.TriggerCharacters, RetriggerCharacters = options.RetriggerCharacters, WorkDoneProgress = options.WorkDoneProgress }; - } + public static SignatureHelpOptions Of(ISignatureHelpOptions options, IEnumerable descriptors) => new SignatureHelpOptions + { TriggerCharacters = options.TriggerCharacters, RetriggerCharacters = options.RetriggerCharacters, WorkDoneProgress = options.WorkDoneProgress }; } } diff --git a/src/Protocol/Server/Capabilities/SynchronizationOptions.cs b/src/Protocol/Server/Capabilities/SynchronizationOptions.cs index 2eee3730d..dfc3e1c80 100644 --- a/src/Protocol/Server/Capabilities/SynchronizationOptions.cs +++ b/src/Protocol/Server/Capabilities/SynchronizationOptions.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { /// - /// Signature help options. + /// Signature help options. /// public class SynchronizationOptions : ISynchronizationOptions { @@ -28,9 +28,7 @@ public class SynchronizationOptions : ISynchronizationOptions [Optional] public bool DidSave { get; set; } - public static SynchronizationOptions Of(ISynchronizationOptions options) - { - return new SynchronizationOptions() { WillSave = options.WillSave, DidSave = options.DidSave, WillSaveWaitUntil = options.WillSaveWaitUntil }; - } + public static SynchronizationOptions Of(ISynchronizationOptions options) => new SynchronizationOptions + { WillSave = options.WillSave, DidSave = options.DidSave, WillSaveWaitUntil = options.WillSaveWaitUntil }; } } diff --git a/src/Protocol/Server/Capabilities/TextDocumentSync.cs b/src/Protocol/Server/Capabilities/TextDocumentSync.cs index be2d1f505..4e8565bbe 100644 --- a/src/Protocol/Server/Capabilities/TextDocumentSync.cs +++ b/src/Protocol/Server/Capabilities/TextDocumentSync.cs @@ -6,28 +6,17 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities [JsonConverter(typeof(TextDocumentSyncConverter))] public class TextDocumentSync { - public TextDocumentSync(TextDocumentSyncKind kind) - { - Kind = kind; - } - public TextDocumentSync(TextDocumentSyncOptions value) - { - Options = value; - } - public bool HasKind => this.Options == null; + public TextDocumentSync(TextDocumentSyncKind kind) => Kind = kind; + + public TextDocumentSync(TextDocumentSyncOptions value) => Options = value; + public bool HasKind => Options == null; public TextDocumentSyncKind Kind { get; set; } - public bool HasOptions => this.Options != null; + public bool HasOptions => Options != null; public TextDocumentSyncOptions Options { get; set; } - public object Value => Options ?? (object)Kind; + public object Value => Options ?? (object) Kind; - public static implicit operator TextDocumentSync(TextDocumentSyncKind value) - { - return new TextDocumentSync(value); - } + public static implicit operator TextDocumentSync(TextDocumentSyncKind value) => new TextDocumentSync(value); - public static implicit operator TextDocumentSync(TextDocumentSyncOptions value) - { - return new TextDocumentSync(value); - } + public static implicit operator TextDocumentSync(TextDocumentSyncOptions value) => new TextDocumentSync(value); } } diff --git a/src/Protocol/Server/Capabilities/TextDocumentSyncKind.cs b/src/Protocol/Server/Capabilities/TextDocumentSyncKind.cs index e112fa1f3..fc0b522b8 100644 --- a/src/Protocol/Server/Capabilities/TextDocumentSyncKind.cs +++ b/src/Protocol/Server/Capabilities/TextDocumentSyncKind.cs @@ -4,26 +4,26 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { /// - /// Defines how the host (editor) should sync document changes to the language server. + /// Defines how the host (editor) should sync document changes to the language server. /// [JsonConverter(typeof(NumberEnumConverter))] public enum TextDocumentSyncKind { /// - /// Documents should not be synced at all. + /// Documents should not be synced at all. /// None = 0, /// - /// Documents are synced by always sending the full content - /// of the document. + /// Documents are synced by always sending the full content + /// of the document. /// Full = 1, /// - /// Documents are synced by sending the full content on open. - /// After that only incremental updates to the document are - /// send. + /// Documents are synced by sending the full content on open. + /// After that only incremental updates to the document are + /// send. /// Incremental = 2, } diff --git a/src/Protocol/Server/Capabilities/TextDocumentSyncOptions.cs b/src/Protocol/Server/Capabilities/TextDocumentSyncOptions.cs index 6496d6df6..69d7e8d40 100644 --- a/src/Protocol/Server/Capabilities/TextDocumentSyncOptions.cs +++ b/src/Protocol/Server/Capabilities/TextDocumentSyncOptions.cs @@ -9,28 +9,32 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities public class TextDocumentSyncOptions : ITextDocumentSyncOptions { /// - /// Open and close notifications are sent to the server. + /// Open and close notifications are sent to the server. /// [Optional] public bool OpenClose { get; set; } + /// - /// Change notificatins are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full - /// and TextDocumentSyncKindIncremental. + /// Change notificatins are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full + /// and TextDocumentSyncKindIncremental. /// [Optional] public TextDocumentSyncKind Change { get; set; } + /// - /// Will save notifications are sent to the server. + /// Will save notifications are sent to the server. /// [Optional] public bool WillSave { get; set; } + /// - /// Will save wait until requests are sent to the server. + /// Will save wait until requests are sent to the server. /// [Optional] public bool WillSaveWaitUntil { get; set; } + /// - /// Save notifications are sent to the server. + /// Save notifications are sent to the server. /// [Optional] public BooleanOr Save { get; set; } @@ -42,16 +46,15 @@ public static TextDocumentSyncOptions Of(IEnumerable o { change = options .Where(x => x.Change != TextDocumentSyncKind.None) - .Min(z => z.Change); + .Min(z => z.Change); } - return new TextDocumentSyncOptions() - { + + return new TextDocumentSyncOptions { OpenClose = options.Any(z => z.OpenClose), Change = change, WillSave = options.Any(z => z.WillSave), WillSaveWaitUntil = options.Any(z => z.WillSaveWaitUntil), - Save = new SaveOptions() - { + Save = new SaveOptions { IncludeText = options.Any(z => z.Save.IsValue && z.Save.Value.IncludeText) } }; diff --git a/src/Protocol/Server/Capabilities/TypeDefinitionOptions.cs b/src/Protocol/Server/Capabilities/TypeDefinitionOptions.cs index 4b2835f97..4cd9cb6c8 100644 --- a/src/Protocol/Server/Capabilities/TypeDefinitionOptions.cs +++ b/src/Protocol/Server/Capabilities/TypeDefinitionOptions.cs @@ -6,12 +6,9 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class TypeDefinitionOptions : StaticWorkDoneTextDocumentRegistrationOptions, ITypeDefinitionOptions { - public static TypeDefinitionOptions Of(ITypeDefinitionOptions options, IEnumerable descriptors) - { - return new TypeDefinitionOptions() - { + public static TypeDefinitionOptions Of(ITypeDefinitionOptions options, IEnumerable descriptors) => + new TypeDefinitionOptions { WorkDoneProgress = options.WorkDoneProgress }; - } } } diff --git a/src/Protocol/Server/ClientLanguageServer.cs b/src/Protocol/Server/ClientLanguageServer.cs index 35350cc04..537b08dd3 100644 --- a/src/Protocol/Server/ClientLanguageServer.cs +++ b/src/Protocol/Server/ClientLanguageServer.cs @@ -1,14 +1,15 @@ using System; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { internal class ClientLanguageServer : LanguageProtocolProxy, IClientLanguageServer { - public ClientLanguageServer(IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, - ILanguageProtocolSettings languageProtocolSettings) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) + public ClientLanguageServer( + IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, + ILanguageProtocolSettings languageProtocolSettings + ) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) { } } diff --git a/src/Protocol/Server/GeneralLanguageServer.cs b/src/Protocol/Server/GeneralLanguageServer.cs index 4155db61f..55ef2167a 100644 --- a/src/Protocol/Server/GeneralLanguageServer.cs +++ b/src/Protocol/Server/GeneralLanguageServer.cs @@ -1,14 +1,15 @@ using System; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { internal class GeneralLanguageServer : LanguageProtocolProxy, IGeneralLanguageServer { - public GeneralLanguageServer(IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, - ILanguageProtocolSettings languageProtocolSettings) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) + public GeneralLanguageServer( + IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, + ILanguageProtocolSettings languageProtocolSettings + ) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) { } } diff --git a/src/Protocol/Server/IClientLanguageServer.cs b/src/Protocol/Server/IClientLanguageServer.cs index d425186cb..f55f079be 100644 --- a/src/Protocol/Server/IClientLanguageServer.cs +++ b/src/Protocol/Server/IClientLanguageServer.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { - public interface IClientLanguageServer : ILanguageServerProxy { } + public interface IClientLanguageServer : ILanguageServerProxy + { + } } diff --git a/src/Protocol/Server/IGeneralLanguageServer.cs b/src/Protocol/Server/IGeneralLanguageServer.cs index b105392b5..f422cf305 100644 --- a/src/Protocol/Server/IGeneralLanguageServer.cs +++ b/src/Protocol/Server/IGeneralLanguageServer.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { - public interface IGeneralLanguageServer : ILanguageServerProxy { } + public interface IGeneralLanguageServer : ILanguageServerProxy + { + } } diff --git a/src/Protocol/Server/ILanguageServerConfiguration.cs b/src/Protocol/Server/ILanguageServerConfiguration.cs index 873442339..b11bfd6cd 100644 --- a/src/Protocol/Server/ILanguageServerConfiguration.cs +++ b/src/Protocol/Server/ILanguageServerConfiguration.cs @@ -16,9 +16,9 @@ public interface ILanguageServerConfiguration : IConfiguration /// /// Gets the current configuration for a given document uri - /// This re-uses all the sections from the s that + /// This re-uses all the sections from the s that /// the root configuration uses. - /// + /// /// This will watch for changes of the scoped documents and update the configuration. /// /// diff --git a/src/Protocol/Server/ILanguageServerWorkspaceFolderManager.cs b/src/Protocol/Server/ILanguageServerWorkspaceFolderManager.cs index 861eababe..6d25fd1dc 100644 --- a/src/Protocol/Server/ILanguageServerWorkspaceFolderManager.cs +++ b/src/Protocol/Server/ILanguageServerWorkspaceFolderManager.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { diff --git a/src/Protocol/Server/IOnLanguageServerInitialize.cs b/src/Protocol/Server/IOnLanguageServerInitialize.cs index 2de587ecc..18c7cfc10 100644 --- a/src/Protocol/Server/IOnLanguageServerInitialize.cs +++ b/src/Protocol/Server/IOnLanguageServerInitialize.cs @@ -7,10 +7,10 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { /// /// Gives your class or handler an opportunity to interact with - /// the before it is processed by the server + /// the before it is processed by the server /// public interface IOnLanguageServerInitialize : IEventingHandler { Task OnInitialize(ILanguageServer server, InitializeParams request, CancellationToken cancellationToken); } -} \ No newline at end of file +} diff --git a/src/Protocol/Server/IOnLanguageServerInitialized.cs b/src/Protocol/Server/IOnLanguageServerInitialized.cs index 321728139..7d9f50855 100644 --- a/src/Protocol/Server/IOnLanguageServerInitialized.cs +++ b/src/Protocol/Server/IOnLanguageServerInitialized.cs @@ -7,10 +7,10 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { /// /// Gives your class or handler an opportunity to interact with - /// the and after it is processed by the server but before it is sent to the client + /// the and after it is processed by the server but before it is sent to the client /// public interface IOnLanguageServerInitialized : IEventingHandler { Task OnInitialized(ILanguageServer server, InitializeParams request, InitializeResult result, CancellationToken cancellationToken); } -} \ No newline at end of file +} diff --git a/src/Protocol/Server/IOnLanguageServerStarted.cs b/src/Protocol/Server/IOnLanguageServerStarted.cs index 12ac23ff4..071857d46 100644 --- a/src/Protocol/Server/IOnLanguageServerStarted.cs +++ b/src/Protocol/Server/IOnLanguageServerStarted.cs @@ -6,7 +6,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { /// /// Gives your class or handler an opportunity to interact with - /// the after the connection has been established. + /// the after the connection has been established. /// public interface IOnLanguageServerStarted : IEventingHandler { diff --git a/src/Protocol/Server/IScopedConfiguration.cs b/src/Protocol/Server/IScopedConfiguration.cs index a134454a4..d69f519d5 100644 --- a/src/Protocol/Server/IScopedConfiguration.cs +++ b/src/Protocol/Server/IScopedConfiguration.cs @@ -3,5 +3,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { - public interface IScopedConfiguration : IDisposable, IConfiguration { } + public interface IScopedConfiguration : IDisposable, IConfiguration + { + } } diff --git a/src/Protocol/Server/ISetTraceHandler.cs b/src/Protocol/Server/ISetTraceHandler.cs index 7f56de2aa..ea87b47ea 100644 --- a/src/Protocol/Server/ISetTraceHandler.cs +++ b/src/Protocol/Server/ISetTraceHandler.cs @@ -8,8 +8,10 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { - [Parallel, Method(GeneralNames.SetTrace, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IClientLanguageClient), typeof(ILanguageClient))] + [Parallel] + [Method(GeneralNames.SetTrace, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IClientLanguageClient), typeof(ILanguageClient))] public interface ISetTraceHandler : IJsonRpcNotificationHandler { } diff --git a/src/Protocol/Server/ITextDocumentLanguageServer.cs b/src/Protocol/Server/ITextDocumentLanguageServer.cs index 2e02a498a..c6480be2c 100644 --- a/src/Protocol/Server/ITextDocumentLanguageServer.cs +++ b/src/Protocol/Server/ITextDocumentLanguageServer.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { - public interface ITextDocumentLanguageServer : ILanguageServerProxy { } + public interface ITextDocumentLanguageServer : ILanguageServerProxy + { + } } diff --git a/src/Protocol/Server/IWorkspaceLanguageServer.cs b/src/Protocol/Server/IWorkspaceLanguageServer.cs index ec17458bd..e61f6af75 100644 --- a/src/Protocol/Server/IWorkspaceLanguageServer.cs +++ b/src/Protocol/Server/IWorkspaceLanguageServer.cs @@ -1,4 +1,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { - public interface IWorkspaceLanguageServer : ILanguageServerProxy { } + public interface IWorkspaceLanguageServer : ILanguageServerProxy + { + } } diff --git a/src/Protocol/Server/OnLanguageServerInitializeDelegate.cs b/src/Protocol/Server/OnLanguageServerInitializeDelegate.cs index 1dee38c38..0f35a91d7 100644 --- a/src/Protocol/Server/OnLanguageServerInitializeDelegate.cs +++ b/src/Protocol/Server/OnLanguageServerInitializeDelegate.cs @@ -6,7 +6,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { /// /// Gives your class or handler an opportunity to interact with - /// the before it is processed by the server + /// the before it is processed by the server /// public delegate Task OnLanguageServerInitializeDelegate(ILanguageServer server, InitializeParams request, CancellationToken cancellationToken); } diff --git a/src/Protocol/Server/OnLanguageServerInitializedDelegate.cs b/src/Protocol/Server/OnLanguageServerInitializedDelegate.cs index 0e84f1077..f4d9f3654 100644 --- a/src/Protocol/Server/OnLanguageServerInitializedDelegate.cs +++ b/src/Protocol/Server/OnLanguageServerInitializedDelegate.cs @@ -6,7 +6,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { /// /// Gives your class or handler an opportunity to interact with - /// the and after it is processed by the server but before it is sent to the client + /// the and after it is processed by the server but before it is sent to the client /// public delegate Task OnLanguageServerInitializedDelegate(ILanguageServer server, InitializeParams request, InitializeResult response, CancellationToken cancellationToken); } diff --git a/src/Protocol/Server/OnLanguageServerStartedDelegate.cs b/src/Protocol/Server/OnLanguageServerStartedDelegate.cs index 589307d55..24d454935 100644 --- a/src/Protocol/Server/OnLanguageServerStartedDelegate.cs +++ b/src/Protocol/Server/OnLanguageServerStartedDelegate.cs @@ -1,12 +1,11 @@ using System.Threading; using System.Threading.Tasks; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { /// /// Gives your class or handler an opportunity to interact with - /// the after the connection has been established. + /// the after the connection has been established. /// public delegate Task OnLanguageServerStartedDelegate(ILanguageServer server, CancellationToken cancellationToken); } diff --git a/src/Protocol/Server/TextDocumentLanguageServer.cs b/src/Protocol/Server/TextDocumentLanguageServer.cs index c25d6c068..a95005d5e 100644 --- a/src/Protocol/Server/TextDocumentLanguageServer.cs +++ b/src/Protocol/Server/TextDocumentLanguageServer.cs @@ -1,14 +1,15 @@ using System; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { internal class TextDocumentLanguageServer : LanguageProtocolProxy, ITextDocumentLanguageServer { - public TextDocumentLanguageServer(IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, - ILanguageProtocolSettings languageProtocolSettings) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) + public TextDocumentLanguageServer( + IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, + ILanguageProtocolSettings languageProtocolSettings + ) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) { } } diff --git a/src/Protocol/Server/WindowLanguageServer.cs b/src/Protocol/Server/WindowLanguageServer.cs index 14cbfee8d..705544de5 100644 --- a/src/Protocol/Server/WindowLanguageServer.cs +++ b/src/Protocol/Server/WindowLanguageServer.cs @@ -1,14 +1,15 @@ using System; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { internal class WindowLanguageServer : LanguageProtocolProxy, IWindowLanguageServer { - public WindowLanguageServer(IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, - ILanguageProtocolSettings languageProtocolSettings) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) + public WindowLanguageServer( + IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, + ILanguageProtocolSettings languageProtocolSettings + ) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) { } } diff --git a/src/Protocol/Server/WorkDone/IServerWorkDoneManager.cs b/src/Protocol/Server/WorkDone/IServerWorkDoneManager.cs index 64a4d0e85..66ba5a8a0 100644 --- a/src/Protocol/Server/WorkDone/IServerWorkDoneManager.cs +++ b/src/Protocol/Server/WorkDone/IServerWorkDoneManager.cs @@ -17,18 +17,26 @@ public interface IServerWorkDoneManager : IWorkDoneProgressCancelHandler /// Creates a that will send all of its progress information to the same source. /// The other side can cancel this, so the should be respected. /// - Task Create(ProgressToken progressToken, WorkDoneProgressBegin begin, Func onError = null, Func onComplete = null, CancellationToken cancellationToken = default); + Task Create( + ProgressToken progressToken, WorkDoneProgressBegin begin, Func onError = null, Func onComplete = null, + CancellationToken cancellationToken = default + ); /// /// Creates a that will send all of its progress information to the same source. /// The other side can cancel this, so the should be respected. /// - Task Create(WorkDoneProgressBegin begin, Func onError = null, Func onComplete = null, CancellationToken cancellationToken = default); + Task Create( + WorkDoneProgressBegin begin, Func onError = null, Func onComplete = null, + CancellationToken cancellationToken = default + ); /// /// Creates a for a request where the client is already listening to work done. /// - IWorkDoneObserver For(IWorkDoneProgressParams request, WorkDoneProgressBegin begin, Func onError = null, - Func onComplete = null); + IWorkDoneObserver For( + IWorkDoneProgressParams request, WorkDoneProgressBegin begin, Func onError = null, + Func onComplete = null + ); } } diff --git a/src/Protocol/Server/WorkDone/LanguageServerWorkDoneManager.cs b/src/Protocol/Server/WorkDone/LanguageServerWorkDoneManager.cs index f1e77ec69..3871a10a9 100644 --- a/src/Protocol/Server/WorkDone/LanguageServerWorkDoneManager.cs +++ b/src/Protocol/Server/WorkDone/LanguageServerWorkDoneManager.cs @@ -7,16 +7,14 @@ using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Window; using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone { - class LanguageServerWorkDoneManager : IServerWorkDoneManager + internal class LanguageServerWorkDoneManager : IServerWorkDoneManager { private readonly IResponseRouter _router; private readonly ISerializer _serializer; - private bool _supported; private readonly ConcurrentDictionary _activeObserverTokens = new ConcurrentDictionary(EqualityComparer.Default); @@ -30,22 +28,22 @@ public LanguageServerWorkDoneManager(IResponseRouter router, ISerializer seriali _serializer = serializer; } - public void Initialized(WindowClientCapabilities windowClientCapabilities) - { - _supported = windowClientCapabilities.WorkDoneProgress.IsSupported && - windowClientCapabilities.WorkDoneProgress.Value; - } + public void Initialized(WindowClientCapabilities windowClientCapabilities) => + IsSupported = windowClientCapabilities.WorkDoneProgress.IsSupported && + windowClientCapabilities.WorkDoneProgress.Value; - public bool IsSupported => _supported; + public bool IsSupported { get; private set; } /// /// Creates a that will send all of its progress information to the same source. /// The other side can cancel this, so the should be respected. /// - public async Task Create(ProgressToken progressToken, WorkDoneProgressBegin begin, - Func onError = null, Func onComplete = null, CancellationToken cancellationToken = default) + public async Task Create( + ProgressToken progressToken, WorkDoneProgressBegin begin, + Func onError = null, Func onComplete = null, CancellationToken cancellationToken = default + ) { - if (!_supported) + if (!IsSupported) { return NoopWorkDoneObserver.Instance; } @@ -55,9 +53,9 @@ public async Task Create(ProgressToken progressToken, WorkDon return item; } - await _router.SendRequest(new WorkDoneProgressCreateParams() {Token = progressToken}, cancellationToken); + await _router.SendRequest(new WorkDoneProgressCreateParams { Token = progressToken }, cancellationToken); - onError ??= error => new WorkDoneProgressEnd() { + onError ??= error => new WorkDoneProgressEnd { Message = error.ToString() }; @@ -83,20 +81,22 @@ public async Task Create(ProgressToken progressToken, WorkDon /// Creates a that will send all of its progress information to the same source. /// The other side can cancel this, so the should be respected. /// - public Task Create(WorkDoneProgressBegin begin, - Func onError = null, Func onComplete = null, CancellationToken cancellationToken = default) - { - return Create(new ProgressToken(Guid.NewGuid().ToString()), begin, onError, onComplete, cancellationToken); - } + public Task Create( + WorkDoneProgressBegin begin, + Func onError = null, Func onComplete = null, CancellationToken cancellationToken = default + ) => + Create(new ProgressToken(Guid.NewGuid().ToString()), begin, onError, onComplete, cancellationToken); /// /// Creates a that will send all of its progress information to the same source. /// - public IWorkDoneObserver For(IWorkDoneProgressParams request, + public IWorkDoneObserver For( + IWorkDoneProgressParams request, WorkDoneProgressBegin begin, Func onError = null, - Func onComplete = null) + Func onComplete = null + ) { - if (!_supported || request.WorkDoneToken == null) + if (!IsSupported || request.WorkDoneToken == null) { return NoopWorkDoneObserver.Instance; } @@ -106,7 +106,7 @@ public IWorkDoneObserver For(IWorkDoneProgressParams request, return item; } - onError ??= error => new WorkDoneProgressEnd() { + onError ??= error => new WorkDoneProgressEnd { Message = error.ToString() }; @@ -127,8 +127,9 @@ public IWorkDoneObserver For(IWorkDoneProgressParams request, return observer; } - Task IRequestHandler.Handle( - WorkDoneProgressCancelParams request, CancellationToken cancellationToken) + Task IRequestHandler.Handle( + WorkDoneProgressCancelParams request, CancellationToken cancellationToken + ) { if (_activeObserverTokens.TryRemove(request.Token, out var cts)) { @@ -137,7 +138,7 @@ public IWorkDoneObserver For(IWorkDoneProgressParams request, _activeObservers.TryRemove(request.Token, out var observer); - return MediatR.Unit.Task; + return Unit.Task; } } } diff --git a/src/Protocol/Server/WorkDone/NoopWorkDoneObserver.cs b/src/Protocol/Server/WorkDone/NoopWorkDoneObserver.cs index 68352bbde..453a406bf 100644 --- a/src/Protocol/Server/WorkDone/NoopWorkDoneObserver.cs +++ b/src/Protocol/Server/WorkDone/NoopWorkDoneObserver.cs @@ -3,21 +3,31 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone { - class NoopWorkDoneObserver : IWorkDoneObserver + internal class NoopWorkDoneObserver : IWorkDoneObserver { public static NoopWorkDoneObserver Instance = new NoopWorkDoneObserver(); + private NoopWorkDoneObserver() { + } + public void OnCompleted() + { } - public void OnCompleted() {} - public void OnError(Exception error) {} + public void OnError(Exception error) + { + } - public void OnNext(WorkDoneProgress value) {} + public void OnNext(WorkDoneProgress value) + { + } public ProgressToken WorkDoneToken { get; } = new ProgressToken("Noop"); - public void OnNext(string message, double? percentage, bool? cancellable) {} + + public void OnNext(string message, double? percentage, bool? cancellable) + { + } public void Dispose() { diff --git a/src/Protocol/Server/WorkDone/WorkDoneObserver.cs b/src/Protocol/Server/WorkDone/WorkDoneObserver.cs index 0f6586190..12b9e770a 100644 --- a/src/Protocol/Server/WorkDone/WorkDoneObserver.cs +++ b/src/Protocol/Server/WorkDone/WorkDoneObserver.cs @@ -7,9 +7,8 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone { - class WorkDoneObserver : IWorkDoneObserver + internal class WorkDoneObserver : IWorkDoneObserver { - private readonly ProgressToken _progressToken; private readonly IResponseRouter _router; private readonly ISerializer _serializer; private readonly Func _onError; @@ -23,41 +22,42 @@ public WorkDoneObserver( WorkDoneProgressBegin begin, Func onError, Func onComplete, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { - _progressToken = progressToken; + WorkDoneToken = progressToken; _router = router; _serializer = serializer; _onError = onError; _onComplete = onComplete; - _disposable = new CompositeDisposable {Disposable.Create(OnCompleted)}; + _disposable = new CompositeDisposable { Disposable.Create(OnCompleted) }; cancellationToken.Register(Dispose); OnNext(begin); } public void OnCompleted() => _router.SendNotification( - _progressToken.Create(_onComplete?.Invoke() ?? new WorkDoneProgressEnd() {Message = ""}, _serializer.JsonSerializer) + WorkDoneToken.Create(_onComplete?.Invoke() ?? new WorkDoneProgressEnd { Message = "" }, _serializer.JsonSerializer) ); void IObserver.OnError(Exception error) => _router.SendNotification( - _progressToken.Create(_onError?.Invoke(error) ?? new WorkDoneProgressEnd() {Message = error.ToString()}, _serializer.JsonSerializer) + WorkDoneToken.Create(_onError?.Invoke(error) ?? new WorkDoneProgressEnd { Message = error.ToString() }, _serializer.JsonSerializer) ); public void OnNext(WorkDoneProgress value) => _router.SendNotification( - _progressToken.Create(value, _serializer.JsonSerializer) - ); + WorkDoneToken.Create(value, _serializer.JsonSerializer) + ); - public ProgressToken WorkDoneToken => _progressToken; + public ProgressToken WorkDoneToken { get; } - public void OnNext(string message, double? percentage, bool? cancellable) - { - OnNext(new WorkDoneProgressReport() { - Cancellable = cancellable, - Message = message, - Percentage = percentage - }); - } + public void OnNext(string message, double? percentage, bool? cancellable) => + OnNext( + new WorkDoneProgressReport { + Cancellable = cancellable, + Message = message, + Percentage = percentage + } + ); public void Dispose() => _disposable?.Dispose(); } diff --git a/src/Protocol/Server/WorkspaceLanguageServer.cs b/src/Protocol/Server/WorkspaceLanguageServer.cs index 0aa7515c0..d74dc0377 100644 --- a/src/Protocol/Server/WorkspaceLanguageServer.cs +++ b/src/Protocol/Server/WorkspaceLanguageServer.cs @@ -1,14 +1,15 @@ using System; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server { internal class WorkspaceLanguageServer : LanguageProtocolProxy, IWorkspaceLanguageServer { - public WorkspaceLanguageServer(IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, - ILanguageProtocolSettings languageProtocolSettings) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) + public WorkspaceLanguageServer( + IResponseRouter requestRouter, IServiceProvider serviceProvider, IProgressManager progressManager, + ILanguageProtocolSettings languageProtocolSettings + ) : base(requestRouter, serviceProvider, progressManager, languageProtocolSettings) { } } diff --git a/src/Protocol/Shared/ILspHandlerDescriptor.cs b/src/Protocol/Shared/ILspHandlerDescriptor.cs index 01c4ab86c..08640d814 100644 --- a/src/Protocol/Shared/ILspHandlerDescriptor.cs +++ b/src/Protocol/Shared/ILspHandlerDescriptor.cs @@ -1,7 +1,5 @@ using System; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol.Client; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Shared { diff --git a/src/Protocol/Shared/LspHandlerDescriptor.cs b/src/Protocol/Shared/LspHandlerDescriptor.cs index 1d62381e3..fbd08a573 100644 --- a/src/Protocol/Shared/LspHandlerDescriptor.cs +++ b/src/Protocol/Shared/LspHandlerDescriptor.cs @@ -5,15 +5,13 @@ using System.Reflection; using MediatR; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Shared { [DebuggerDisplay("{Key}:{Method}")] - class LspHandlerDescriptor : ILspHandlerDescriptor, IDisposable, IEquatable + internal class LspHandlerDescriptor : ILspHandlerDescriptor, IDisposable, IEquatable { private readonly Action _disposeAction; private readonly Func _allowsDynamicRegistration; @@ -30,7 +28,8 @@ public LspHandlerDescriptor( Type capabilityType, RequestProcessType? requestProcessType, Action disposeAction, - ILspHandlerTypeDescriptor typeDescriptor) + ILspHandlerTypeDescriptor typeDescriptor + ) { _disposeAction = disposeAction; Id = Guid.NewGuid(); @@ -47,13 +46,13 @@ public LspHandlerDescriptor( Response = typeDescriptor?.ResponseType ?? @params?.GetInterfaces() - .FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IRequest<>))? - .GetGenericArguments()[0] ?? typeof(Unit); + .FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IRequest<>))? + .GetGenericArguments()[0] ?? typeof(Unit); // If multiple are implemented this behavior is unknown CanBeResolvedHandlerType = handler.GetType().GetTypeInfo() - .ImplementedInterfaces - .FirstOrDefault(x => typeof(ICanBeResolvedHandler).IsAssignableFrom(x)); + .ImplementedInterfaces + .FirstOrDefault(x => typeof(ICanBeResolvedHandler).IsAssignableFrom(x)); HasReturnType = Response != null && Response != typeof(Unit); @@ -64,8 +63,12 @@ public LspHandlerDescriptor( ); IsNotification = typeof(IJsonRpcNotificationHandler).IsAssignableFrom(handlerType) || handlerType - .GetInterfaces().Any(z => - z.IsGenericType && typeof(IJsonRpcNotificationHandler<>).IsAssignableFrom(z.GetGenericTypeDefinition())); + .GetInterfaces().Any( + z => + z.IsGenericType && typeof(IJsonRpcNotificationHandler<>).IsAssignableFrom( + z.GetGenericTypeDefinition() + ) + ); IsRequest = !IsNotification; RequestProcessType = requestProcessType; TypeDescriptor = typeDescriptor; @@ -99,23 +102,15 @@ public LspHandlerDescriptor( public RequestProcessType? RequestProcessType { get; } public ILspHandlerTypeDescriptor TypeDescriptor { get; } - public void Dispose() - { - _disposeAction(); - } + public void Dispose() => _disposeAction(); - public override bool Equals(object obj) - { - return Equals(obj as LspHandlerDescriptor); - } + public override bool Equals(object obj) => Equals(obj as LspHandlerDescriptor); - public bool Equals(LspHandlerDescriptor other) - { - return other != null && - EqualityComparer.Default.Equals(HandlerType, other.HandlerType) && - Method == other.Method && - Key == other.Key; - } + public bool Equals(LspHandlerDescriptor other) => + other != null && + EqualityComparer.Default.Equals(HandlerType, other.HandlerType) && + Method == other.Method && + Key == other.Key; public override int GetHashCode() { @@ -126,14 +121,9 @@ public override int GetHashCode() return hashCode; } - public static bool operator ==(LspHandlerDescriptor descriptor1, LspHandlerDescriptor descriptor2) - { - return EqualityComparer.Default.Equals(descriptor1, descriptor2); - } + public static bool operator ==(LspHandlerDescriptor descriptor1, LspHandlerDescriptor descriptor2) => + EqualityComparer.Default.Equals(descriptor1, descriptor2); - public static bool operator !=(LspHandlerDescriptor descriptor1, LspHandlerDescriptor descriptor2) - { - return !(descriptor1 == descriptor2); - } + public static bool operator !=(LspHandlerDescriptor descriptor1, LspHandlerDescriptor descriptor2) => !( descriptor1 == descriptor2 ); } } diff --git a/src/Protocol/Shared/LspHandlerTypeDescriptor.cs b/src/Protocol/Shared/LspHandlerTypeDescriptor.cs index 60886d7f4..cccf06c59 100644 --- a/src/Protocol/Shared/LspHandlerTypeDescriptor.cs +++ b/src/Protocol/Shared/LspHandlerTypeDescriptor.cs @@ -9,15 +9,15 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Shared { [DebuggerDisplay("{" + nameof(Method) + "}")] - class LspHandlerTypeDescriptor : HandlerTypeDescriptor, ILspHandlerTypeDescriptor + internal class LspHandlerTypeDescriptor : HandlerTypeDescriptor, ILspHandlerTypeDescriptor { public LspHandlerTypeDescriptor(Type handlerType) : base(handlerType) { PartialItemsType = ParamsType.GetInterfaces().FirstOrDefault(z => z.IsGenericType && typeof(IPartialItems<>).IsAssignableFrom(z.GetGenericTypeDefinition())) - ?.GetGenericArguments()[0]; + ?.GetGenericArguments()[0]; HasPartialItems = PartialItemsType != null; PartialItemType = ParamsType.GetInterfaces().FirstOrDefault(z => z.IsGenericType && typeof(IPartialItem<>).IsAssignableFrom(z.GetGenericTypeDefinition())) - ?.GetGenericArguments()[0]; + ?.GetGenericArguments()[0]; HasPartialItem = PartialItemType != null; RegistrationType = HandlerTypeDescriptorHelper.UnwrapGenericType(typeof(IRegistration<>), handlerType); HasRegistration = RegistrationType != null && RegistrationType != typeof(object); diff --git a/src/Protocol/Shared/LspHandlerTypeDescriptorHelper.cs b/src/Protocol/Shared/LspHandlerTypeDescriptorHelper.cs index 173e8a686..8c57baf4d 100644 --- a/src/Protocol/Shared/LspHandlerTypeDescriptorHelper.cs +++ b/src/Protocol/Shared/LspHandlerTypeDescriptorHelper.cs @@ -19,37 +19,36 @@ static LspHandlerTypeDescriptorHelper() try { KnownHandlers = HandlerTypeDescriptorHelper.KnownHandlers.Values - .Select(x => new LspHandlerTypeDescriptor(x.HandlerType) as ILspHandlerTypeDescriptor) - .ToImmutableSortedDictionary(x => x.Method, x => x, StringComparer.Ordinal); + .Select(x => new LspHandlerTypeDescriptor(x.HandlerType) as ILspHandlerTypeDescriptor) + .ToImmutableSortedDictionary(x => x.Method, x => x, StringComparer.Ordinal); } catch (Exception e) { - throw new AggregateException($"Failed", e); + throw new AggregateException("Failed", e); } } public static ILspHandlerTypeDescriptor GetHandlerTypeForRegistrationOptions(object registrationOptions) { var registrationType = registrationOptions.GetType(); - var interfaces = new HashSet(registrationOptions.GetType().GetInterfaces() - .Except(registrationType.BaseType?.GetInterfaces() ?? Enumerable.Empty())); - return interfaces.SelectMany(x => - KnownHandlers.Values - .Where(z => z.HasRegistration) - .Where(z => x.IsAssignableFrom(z.RegistrationType))) - .FirstOrDefault(); + var interfaces = new HashSet( + registrationOptions.GetType().GetInterfaces() + .Except(registrationType.BaseType?.GetInterfaces() ?? Enumerable.Empty()) + ); + return interfaces.SelectMany( + x => + KnownHandlers.Values + .Where(z => z.HasRegistration) + .Where(z => x.IsAssignableFrom(z.RegistrationType)) + ) + .FirstOrDefault(); } - public static ILspHandlerTypeDescriptor GetHandlerTypeDescriptor(string method) - { - return KnownHandlers.TryGetValue(method, out var descriptor) ? descriptor : null; - } + public static ILspHandlerTypeDescriptor GetHandlerTypeDescriptor(string method) => KnownHandlers.TryGetValue(method, out var descriptor) ? descriptor : null; - public static ILspHandlerTypeDescriptor GetHandlerTypeDescriptor() - { - return KnownHandlers.Values.FirstOrDefault(x => x.InterfaceType == typeof(T)) ?? - GetHandlerTypeDescriptor(HandlerTypeDescriptorHelper.GetMethodName(typeof(T))); - } + public static ILspHandlerTypeDescriptor GetHandlerTypeDescriptor() => + KnownHandlers.Values.FirstOrDefault(x => x.InterfaceType == typeof(T)) ?? + GetHandlerTypeDescriptor(HandlerTypeDescriptorHelper.GetMethodName(typeof(T))); public static ILspHandlerTypeDescriptor GetHandlerTypeDescriptor(Type type) { diff --git a/src/Protocol/Supports.cs b/src/Protocol/Supports.cs index 68f7f99d4..9c7d42100 100644 --- a/src/Protocol/Supports.cs +++ b/src/Protocol/Supports.cs @@ -6,11 +6,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol public struct Supports : ISupports { private readonly bool? _isSupported; + public Supports(bool? isSupported, T value) { _isSupported = isSupported; Value = value; } + public Supports(T value) { _isSupported = true; @@ -20,7 +22,7 @@ public Supports(T value) public Supports(bool? isSupported) { _isSupported = isSupported; - Value = default(T); + Value = default; } public T Value { get; set; } @@ -28,28 +30,17 @@ public Supports(bool? isSupported) public Type ValueType => typeof(T); object ISupports.Value => Value; - public static implicit operator T(Supports value) - { - return value.Value; - } + public static implicit operator T(Supports value) => value.Value; - public static implicit operator Supports(T value) - { - return new Supports(!EqualityComparer.Default.Equals(value, default), value); - } + public static implicit operator Supports(T value) => new Supports(!EqualityComparer.Default.Equals(value, default), value); } public static class Supports { public static Supports OfValue(T value) - where T : class - { - return new Supports(!EqualityComparer.Default.Equals(value, default), value); - } + where T : class => + new Supports(!EqualityComparer.Default.Equals(value, default), value); - public static Supports OfBoolean(bool? isSupported) - { - return new Supports(isSupported); - } + public static Supports OfBoolean(bool? isSupported) => new Supports(isSupported); } } diff --git a/src/Protocol/TextDocumentNames.cs b/src/Protocol/TextDocumentNames.cs index c4fbac49f..1505ca792 100644 --- a/src/Protocol/TextDocumentNames.cs +++ b/src/Protocol/TextDocumentNames.cs @@ -36,17 +36,11 @@ public static class TextDocumentNames public const string WillSaveWaitUntil = "textDocument/willSaveWaitUntil"; public const string PublishDiagnostics = "textDocument/publishDiagnostics"; public const string FoldingRange = "textDocument/foldingRange"; - [Obsolete(Constants.Proposal)] - public const string PrepareCallHierarchy = "textDocument/prepareCallHierarchy"; - [Obsolete(Constants.Proposal)] - public const string CallHierarchyIncoming = "callHierarchy/incomingCalls"; - [Obsolete(Constants.Proposal)] - public const string CallHierarchyOutgoing = "callHierarchy/outgoingCalls"; - [Obsolete(Constants.Proposal)] - public const string SemanticTokensFull = "textDocument/semanticTokens/full"; - [Obsolete(Constants.Proposal)] - public const string SemanticTokensFullDelta = "textDocument/semanticTokens/full/delta"; - [Obsolete(Constants.Proposal)] - public const string SemanticTokensRange = "textDocument/semanticTokens/range"; + [Obsolete(Constants.Proposal)] public const string PrepareCallHierarchy = "textDocument/prepareCallHierarchy"; + [Obsolete(Constants.Proposal)] public const string CallHierarchyIncoming = "callHierarchy/incomingCalls"; + [Obsolete(Constants.Proposal)] public const string CallHierarchyOutgoing = "callHierarchy/outgoingCalls"; + [Obsolete(Constants.Proposal)] public const string SemanticTokensFull = "textDocument/semanticTokens/full"; + [Obsolete(Constants.Proposal)] public const string SemanticTokensFullDelta = "textDocument/semanticTokens/full/delta"; + [Obsolete(Constants.Proposal)] public const string SemanticTokensRange = "textDocument/semanticTokens/range"; } } diff --git a/src/Protocol/Window/ILogMessageHandler.cs b/src/Protocol/Window/ILogMessageHandler.cs index 953c9b8b5..71cc15f42 100644 --- a/src/Protocol/Window/ILogMessageHandler.cs +++ b/src/Protocol/Window/ILogMessageHandler.cs @@ -8,9 +8,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Window { - [Parallel, Method(WindowNames.LogMessage, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] - public interface ILogMessageHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(WindowNames.LogMessage, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] + public interface ILogMessageHandler : IJsonRpcNotificationHandler + { + } public abstract class LogMessageHandler : ILogMessageHandler { @@ -19,54 +23,26 @@ public abstract class LogMessageHandler : ILogMessageHandler public static partial class LogMessageExtensions { - public static void Log(this ILanguageServer mediator, LogMessageParams @params) - { - mediator.LogMessage(@params); - } + public static void Log(this ILanguageServer mediator, LogMessageParams @params) => mediator.LogMessage(@params); - public static void LogError(this ILanguageServer mediator, string message) - { - mediator.LogMessage(new LogMessageParams() { Type = MessageType.Error, Message = message }); - } + public static void LogError(this ILanguageServer mediator, string message) => mediator.LogMessage(new LogMessageParams { Type = MessageType.Error, Message = message }); - public static void Log(this ILanguageServer mediator, string message) - { - mediator.LogMessage(new LogMessageParams() { Type = MessageType.Log, Message = message }); - } + public static void Log(this ILanguageServer mediator, string message) => mediator.LogMessage(new LogMessageParams { Type = MessageType.Log, Message = message }); - public static void LogWarning(this ILanguageServer mediator, string message) - { - mediator.LogMessage(new LogMessageParams() { Type = MessageType.Warning, Message = message }); - } + public static void LogWarning(this ILanguageServer mediator, string message) => mediator.LogMessage(new LogMessageParams { Type = MessageType.Warning, Message = message }); - public static void LogInfo(this ILanguageServer mediator, string message) - { - mediator.LogMessage(new LogMessageParams() { Type = MessageType.Info, Message = message }); - } + public static void LogInfo(this ILanguageServer mediator, string message) => mediator.LogMessage(new LogMessageParams { Type = MessageType.Info, Message = message }); - public static void Log(this IWindowLanguageServer mediator, LogMessageParams @params) - { - mediator.LogMessage(@params); - } + public static void Log(this IWindowLanguageServer mediator, LogMessageParams @params) => mediator.LogMessage(@params); - public static void LogError(this IWindowLanguageServer mediator, string message) - { - mediator.LogMessage(new LogMessageParams() { Type = MessageType.Error, Message = message }); - } + public static void LogError(this IWindowLanguageServer mediator, string message) => + mediator.LogMessage(new LogMessageParams { Type = MessageType.Error, Message = message }); - public static void Log(this IWindowLanguageServer mediator, string message) - { - mediator.LogMessage(new LogMessageParams() { Type = MessageType.Log, Message = message }); - } + public static void Log(this IWindowLanguageServer mediator, string message) => mediator.LogMessage(new LogMessageParams { Type = MessageType.Log, Message = message }); - public static void LogWarning(this IWindowLanguageServer mediator, string message) - { - mediator.LogMessage(new LogMessageParams() { Type = MessageType.Warning, Message = message }); - } + public static void LogWarning(this IWindowLanguageServer mediator, string message) => + mediator.LogMessage(new LogMessageParams { Type = MessageType.Warning, Message = message }); - public static void LogInfo(this IWindowLanguageServer mediator, string message) - { - mediator.LogMessage(new LogMessageParams() { Type = MessageType.Info, Message = message }); - } + public static void LogInfo(this IWindowLanguageServer mediator, string message) => mediator.LogMessage(new LogMessageParams { Type = MessageType.Info, Message = message }); } } diff --git a/src/Protocol/Window/IShowMessageHandler.cs b/src/Protocol/Window/IShowMessageHandler.cs index 570ce6c16..9afe6de58 100644 --- a/src/Protocol/Window/IShowMessageHandler.cs +++ b/src/Protocol/Window/IShowMessageHandler.cs @@ -1,18 +1,20 @@ -using System; using System.Threading; using System.Threading.Tasks; using MediatR; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; -using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Window { - [Parallel, Method(WindowNames.ShowMessage, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] - public interface IShowMessageHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(WindowNames.ShowMessage, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] + public interface IShowMessageHandler : IJsonRpcNotificationHandler + { + } public abstract class ShowMessageHandler : IShowMessageHandler { @@ -21,54 +23,28 @@ public abstract class ShowMessageHandler : IShowMessageHandler public static partial class ShowMessageExtensions { - public static void Show(this ILanguageServer mediator, ShowMessageParams @params) - { - mediator.ShowMessage(@params); - } + public static void Show(this ILanguageServer mediator, ShowMessageParams @params) => mediator.ShowMessage(@params); - public static void ShowError(this ILanguageServer mediator, string message) - { - mediator.ShowMessage(new ShowMessageParams() { Type = MessageType.Error, Message = message }); - } + public static void ShowError(this ILanguageServer mediator, string message) => mediator.ShowMessage(new ShowMessageParams { Type = MessageType.Error, Message = message }); - public static void Show(this ILanguageServer mediator, string message) - { - mediator.ShowMessage(new ShowMessageParams() { Type = MessageType.Log, Message = message }); - } + public static void Show(this ILanguageServer mediator, string message) => mediator.ShowMessage(new ShowMessageParams { Type = MessageType.Log, Message = message }); - public static void ShowWarning(this ILanguageServer mediator, string message) - { - mediator.ShowMessage(new ShowMessageParams() { Type = MessageType.Warning, Message = message }); - } + public static void ShowWarning(this ILanguageServer mediator, string message) => + mediator.ShowMessage(new ShowMessageParams { Type = MessageType.Warning, Message = message }); - public static void ShowInfo(this ILanguageServer mediator, string message) - { - mediator.ShowMessage(new ShowMessageParams() { Type = MessageType.Info, Message = message }); - } + public static void ShowInfo(this ILanguageServer mediator, string message) => mediator.ShowMessage(new ShowMessageParams { Type = MessageType.Info, Message = message }); - public static void Show(this IWindowLanguageServer mediator, ShowMessageParams @params) - { - mediator.ShowMessage(@params); - } + public static void Show(this IWindowLanguageServer mediator, ShowMessageParams @params) => mediator.ShowMessage(@params); - public static void ShowError(this IWindowLanguageServer mediator, string message) - { - mediator.ShowMessage(new ShowMessageParams() { Type = MessageType.Error, Message = message }); - } + public static void ShowError(this IWindowLanguageServer mediator, string message) => + mediator.ShowMessage(new ShowMessageParams { Type = MessageType.Error, Message = message }); - public static void Show(this IWindowLanguageServer mediator, string message) - { - mediator.ShowMessage(new ShowMessageParams() { Type = MessageType.Log, Message = message }); - } + public static void Show(this IWindowLanguageServer mediator, string message) => mediator.ShowMessage(new ShowMessageParams { Type = MessageType.Log, Message = message }); - public static void ShowWarning(this IWindowLanguageServer mediator, string message) - { - mediator.ShowMessage(new ShowMessageParams() { Type = MessageType.Warning, Message = message }); - } + public static void ShowWarning(this IWindowLanguageServer mediator, string message) => + mediator.ShowMessage(new ShowMessageParams { Type = MessageType.Warning, Message = message }); - public static void ShowInfo(this IWindowLanguageServer mediator, string message) - { - mediator.ShowMessage(new ShowMessageParams() { Type = MessageType.Info, Message = message }); - } + public static void ShowInfo(this IWindowLanguageServer mediator, string message) => + mediator.ShowMessage(new ShowMessageParams { Type = MessageType.Info, Message = message }); } } diff --git a/src/Protocol/Window/IShowMessageRequestHandler.cs b/src/Protocol/Window/IShowMessageRequestHandler.cs index 32b2a66b7..07f311e53 100644 --- a/src/Protocol/Window/IShowMessageRequestHandler.cs +++ b/src/Protocol/Window/IShowMessageRequestHandler.cs @@ -7,9 +7,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Window { - [Serial, Method(WindowNames.ShowMessageRequest, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] - public interface IShowMessageRequestHandler : IJsonRpcRequestHandler { } + [Serial] + [Method(WindowNames.ShowMessageRequest, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] + public interface IShowMessageRequestHandler : IJsonRpcRequestHandler + { + } public abstract class ShowMessageRequestHandler : IShowMessageRequestHandler { diff --git a/src/Protocol/Window/ITelemetryEventHandler.cs b/src/Protocol/Window/ITelemetryEventHandler.cs index cb4ee8212..c05966837 100644 --- a/src/Protocol/Window/ITelemetryEventHandler.cs +++ b/src/Protocol/Window/ITelemetryEventHandler.cs @@ -8,9 +8,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Window { - [Parallel, Method(WindowNames.TelemetryEvent, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] - public interface ITelemetryEventHandler : IJsonRpcNotificationHandler { } + [Parallel] + [Method(WindowNames.TelemetryEvent, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] + public interface ITelemetryEventHandler : IJsonRpcNotificationHandler + { + } public abstract class TelemetryEventHandler : ITelemetryEventHandler { diff --git a/src/Protocol/Window/IWorkDoneProgressCancelHandler.cs b/src/Protocol/Window/IWorkDoneProgressCancelHandler.cs index 135395216..c1ccb6893 100644 --- a/src/Protocol/Window/IWorkDoneProgressCancelHandler.cs +++ b/src/Protocol/Window/IWorkDoneProgressCancelHandler.cs @@ -8,8 +8,10 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Window { - [Parallel, Method(WindowNames.WorkDoneProgressCancel, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IWindowLanguageClient), typeof(ILanguageClient))] + [Parallel] + [Method(WindowNames.WorkDoneProgressCancel, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWindowLanguageClient), typeof(ILanguageClient))] public interface IWorkDoneProgressCancelHandler : IJsonRpcNotificationHandler { } @@ -21,18 +23,18 @@ public abstract class WorkDoneProgressCancelHandler : IWorkDoneProgressCancelHan public static partial class WorkDoneProgressCancelExtensions { - public static void SendWorkDoneProgressCancel(this IWindowLanguageClient mediator, IWorkDoneProgressParams @params) - { - mediator.SendNotification(WindowNames.WorkDoneProgressCancel, new WorkDoneProgressCancelParams() { - Token = @params.WorkDoneToken - }); - } + public static void SendWorkDoneProgressCancel(this IWindowLanguageClient mediator, IWorkDoneProgressParams @params) => + mediator.SendNotification( + WindowNames.WorkDoneProgressCancel, new WorkDoneProgressCancelParams { + Token = @params.WorkDoneToken + } + ); - public static void SendWorkDoneProgressCancel(this IWindowLanguageClient mediator, ProgressToken token) - { - mediator.SendNotification(WindowNames.WorkDoneProgressCancel, new WorkDoneProgressCancelParams() { - Token = token - }); - } + public static void SendWorkDoneProgressCancel(this IWindowLanguageClient mediator, ProgressToken token) => + mediator.SendNotification( + WindowNames.WorkDoneProgressCancel, new WorkDoneProgressCancelParams { + Token = token + } + ); } } diff --git a/src/Protocol/Window/IWorkDoneProgressCreateHandler.cs b/src/Protocol/Window/IWorkDoneProgressCreateHandler.cs index e22f76767..72cd7b048 100644 --- a/src/Protocol/Window/IWorkDoneProgressCreateHandler.cs +++ b/src/Protocol/Window/IWorkDoneProgressCreateHandler.cs @@ -8,9 +8,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Window { - [Parallel, Method(WindowNames.WorkDoneProgressCreate, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] - public interface IWorkDoneProgressCreateHandler : IJsonRpcRequestHandler { } + [Parallel] + [Method(WindowNames.WorkDoneProgressCreate, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))] + public interface IWorkDoneProgressCreateHandler : IJsonRpcRequestHandler + { + } public abstract class WorkDoneProgressCreateHandler : IWorkDoneProgressCreateHandler { diff --git a/src/Protocol/Workspace/IApplyEditHandler.cs b/src/Protocol/Workspace/IApplyEditHandler.cs index 7e81dbd48..969dd4922 100644 --- a/src/Protocol/Workspace/IApplyEditHandler.cs +++ b/src/Protocol/Workspace/IApplyEditHandler.cs @@ -1,17 +1,19 @@ -using System; using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; -using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Workspace { - [Parallel, Method(WorkspaceNames.ApplyEdit, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IWorkspaceLanguageServer), typeof(ILanguageServer))] - public interface IApplyWorkspaceEditHandler : IJsonRpcRequestHandler { } + [Parallel] + [Method(WorkspaceNames.ApplyEdit, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageServer), typeof(ILanguageServer))] + public interface IApplyWorkspaceEditHandler : IJsonRpcRequestHandler + { + } public abstract class ApplyWorkspaceEditHandler : IApplyWorkspaceEditHandler { diff --git a/src/Protocol/Workspace/IConfigurationHandler.cs b/src/Protocol/Workspace/IConfigurationHandler.cs index c4afb1da1..c7017f0eb 100644 --- a/src/Protocol/Workspace/IConfigurationHandler.cs +++ b/src/Protocol/Workspace/IConfigurationHandler.cs @@ -1,18 +1,20 @@ -using System; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; -using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Workspace { - [Parallel, Method(WorkspaceNames.Configuration, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IWorkspaceLanguageServer), typeof(ILanguageServer))] - public interface IConfigurationHandler : IJsonRpcRequestHandler> { } + [Parallel] + [Method(WorkspaceNames.Configuration, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageServer), typeof(ILanguageServer))] + public interface IConfigurationHandler : IJsonRpcRequestHandler> + { + } public abstract class ConfigurationHandler : IConfigurationHandler { diff --git a/src/Protocol/Workspace/IDidChangeConfigurationHandler.cs b/src/Protocol/Workspace/IDidChangeConfigurationHandler.cs index 24e396e78..966fad989 100644 --- a/src/Protocol/Workspace/IDidChangeConfigurationHandler.cs +++ b/src/Protocol/Workspace/IDidChangeConfigurationHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Threading; using System.Threading.Tasks; using MediatR; @@ -7,14 +6,15 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Workspace { - [Serial, Method(WorkspaceNames.DidChangeConfiguration, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] + [Serial] + [Method(WorkspaceNames.DidChangeConfiguration, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] public interface IDidChangeConfigurationHandler : IJsonRpcNotificationHandler, - IRegistration, ICapability + IRegistration, ICapability { } diff --git a/src/Protocol/Workspace/IDidChangeWatchedFilesHandler.cs b/src/Protocol/Workspace/IDidChangeWatchedFilesHandler.cs index a515e7703..a5b520eca 100644 --- a/src/Protocol/Workspace/IDidChangeWatchedFilesHandler.cs +++ b/src/Protocol/Workspace/IDidChangeWatchedFilesHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Threading; using System.Threading.Tasks; using MediatR; @@ -7,21 +6,22 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Workspace { - [Serial, Method(WorkspaceNames.DidChangeWatchedFiles, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] - public interface IDidChangeWatchedFilesHandler : IJsonRpcNotificationHandler, IRegistration, ICapability { } + [Serial] + [Method(WorkspaceNames.DidChangeWatchedFiles, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] + public interface IDidChangeWatchedFilesHandler : IJsonRpcNotificationHandler, IRegistration, + ICapability + { + } public abstract class DidChangeWatchedFilesHandler : IDidChangeWatchedFilesHandler { private readonly DidChangeWatchedFilesRegistrationOptions _options; - public DidChangeWatchedFilesHandler(DidChangeWatchedFilesRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public DidChangeWatchedFilesHandler(DidChangeWatchedFilesRegistrationOptions registrationOptions) => _options = registrationOptions; public DidChangeWatchedFilesRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(DidChangeWatchedFilesParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Workspace/IDidChangeWorkspaceFoldersHandler.cs b/src/Protocol/Workspace/IDidChangeWorkspaceFoldersHandler.cs index f5f7cc334..f8ae20910 100644 --- a/src/Protocol/Workspace/IDidChangeWorkspaceFoldersHandler.cs +++ b/src/Protocol/Workspace/IDidChangeWorkspaceFoldersHandler.cs @@ -1,18 +1,17 @@ -using System; using System.Threading; using System.Threading.Tasks; using MediatR; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Client; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace OmniSharp.Extensions.LanguageServer.Protocol.Workspace { - [Parallel, Method(WorkspaceNames.DidChangeWorkspaceFolders, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] + [Parallel] + [Method(WorkspaceNames.DidChangeWorkspaceFolders, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] public interface IDidChangeWorkspaceFoldersHandler : IJsonRpcNotificationHandler, IRegistration { } @@ -20,10 +19,7 @@ public interface IDidChangeWorkspaceFoldersHandler : IJsonRpcNotificationHandler public abstract class DidChangeWorkspaceFoldersHandler : IDidChangeWorkspaceFoldersHandler { private readonly object _registrationOptions; - public DidChangeWorkspaceFoldersHandler(object registrationOptions) - { - _registrationOptions = registrationOptions; - } + public DidChangeWorkspaceFoldersHandler(object registrationOptions) => _registrationOptions = registrationOptions; public object GetRegistrationOptions() => _registrationOptions; public abstract Task Handle(DidChangeWorkspaceFoldersParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/Workspace/IExecuteCommandHandler.cs b/src/Protocol/Workspace/IExecuteCommandHandler.cs index a99b92d14..0601e7028 100644 --- a/src/Protocol/Workspace/IExecuteCommandHandler.cs +++ b/src/Protocol/Workspace/IExecuteCommandHandler.cs @@ -13,18 +13,19 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Workspace { - [Serial, Method(WorkspaceNames.ExecuteCommand, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] - public interface IExecuteCommandHandler : IJsonRpcRequestHandler, IRegistration, ICapability { } + [Serial] + [Method(WorkspaceNames.ExecuteCommand, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient))] + public interface IExecuteCommandHandler : IJsonRpcRequestHandler, IRegistration, ICapability + { + } public abstract class ExecuteCommandHandler : IExecuteCommandHandler { private readonly ExecuteCommandRegistrationOptions _options; - public ExecuteCommandHandler(ExecuteCommandRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public ExecuteCommandHandler(ExecuteCommandRegistrationOptions registrationOptions) => _options = registrationOptions; public ExecuteCommandRegistrationOptions GetRegistrationOptions() => _options; public abstract Task Handle(ExecuteCommandParams request, CancellationToken cancellationToken); @@ -36,10 +37,8 @@ public abstract class ExecuteCommandHandlerBase : ExecuteCommandHandler { private readonly ISerializer _serializer; - public ExecuteCommandHandlerBase(string command, ISerializer serializer) : base(new ExecuteCommandRegistrationOptions() { Commands = new Container(command) }) - { + public ExecuteCommandHandlerBase(string command, ISerializer serializer) : base(new ExecuteCommandRegistrationOptions { Commands = new Container(command) }) => _serializer = serializer; - } public sealed override Task Handle(ExecuteCommandParams request, CancellationToken cancellationToken) { @@ -56,10 +55,8 @@ public abstract class ExecuteCommandHandlerBase : ExecuteCommandHandler { private readonly ISerializer _serializer; - public ExecuteCommandHandlerBase(string command, ISerializer serializer) : base(new ExecuteCommandRegistrationOptions() { Commands = new Container(command) }) - { + public ExecuteCommandHandlerBase(string command, ISerializer serializer) : base(new ExecuteCommandRegistrationOptions { Commands = new Container(command) }) => _serializer = serializer; - } public sealed override Task Handle(ExecuteCommandParams request, CancellationToken cancellationToken) { @@ -78,10 +75,8 @@ public abstract class ExecuteCommandHandlerBase : ExecuteCommandHandl { private readonly ISerializer _serializer; - public ExecuteCommandHandlerBase(string command, ISerializer serializer) : base(new ExecuteCommandRegistrationOptions() { Commands = new Container(command) }) - { + public ExecuteCommandHandlerBase(string command, ISerializer serializer) : base(new ExecuteCommandRegistrationOptions { Commands = new Container(command) }) => _serializer = serializer; - } public sealed override Task Handle(ExecuteCommandParams request, CancellationToken cancellationToken) { @@ -102,10 +97,8 @@ public abstract class ExecuteCommandHandlerBase : ExecuteCommandH { private readonly ISerializer _serializer; - public ExecuteCommandHandlerBase(string command, ISerializer serializer) : base(new ExecuteCommandRegistrationOptions() { Commands = new Container(command) }) - { + public ExecuteCommandHandlerBase(string command, ISerializer serializer) : base(new ExecuteCommandRegistrationOptions { Commands = new Container(command) }) => _serializer = serializer; - } public sealed override Task Handle(ExecuteCommandParams request, CancellationToken cancellationToken) { @@ -128,10 +121,8 @@ public abstract class ExecuteCommandHandlerBase : ExecuteComm { private readonly ISerializer _serializer; - public ExecuteCommandHandlerBase(string command, ISerializer serializer) : base(new ExecuteCommandRegistrationOptions() { Commands = new Container(command) }) - { + public ExecuteCommandHandlerBase(string command, ISerializer serializer) : base(new ExecuteCommandRegistrationOptions { Commands = new Container(command) }) => _serializer = serializer; - } public sealed override Task Handle(ExecuteCommandParams request, CancellationToken cancellationToken) { @@ -156,10 +147,8 @@ public abstract class ExecuteCommandHandlerBase : Execute { private readonly ISerializer _serializer; - public ExecuteCommandHandlerBase(string command, ISerializer serializer) : base(new ExecuteCommandRegistrationOptions() { Commands = new Container(command) }) - { + public ExecuteCommandHandlerBase(string command, ISerializer serializer) : base(new ExecuteCommandRegistrationOptions { Commands = new Container(command) }) => _serializer = serializer; - } public sealed override Task Handle(ExecuteCommandParams request, CancellationToken cancellationToken) { @@ -185,42 +174,39 @@ public sealed override Task Handle(ExecuteCommandParams request, Cancellat public static partial class ExecuteCommandExtensions { public static Task ExecuteCommand(this IWorkspaceLanguageClient mediator, Command @params, CancellationToken cancellationToken = default) - => mediator.ExecuteCommand(new ExecuteCommandParams() { Arguments = @params.Arguments, Command = @params.Name }, cancellationToken); + => mediator.ExecuteCommand(new ExecuteCommandParams { Arguments = @params.Arguments, Command = @params.Name }, cancellationToken); public static Task ExecuteCommand(this ILanguageClient mediator, Command @params, CancellationToken cancellationToken = default) - => mediator.ExecuteCommand(new ExecuteCommandParams() { Arguments = @params.Arguments, Command = @params.Name }, cancellationToken); - - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler(command, handler, _.GetRequiredService())); - } - - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler( - command, - (arg1, capability, token) => handler(arg1, token), - _.GetRequiredService()) + => mediator.ExecuteCommand(new ExecuteCommandParams { Arguments = @params.Arguments, Command = @params.Name }, cancellationToken); + + public static ILanguageServerRegistry OnExecuteCommand( + this ILanguageServerRegistry registry, string command, Func handler + ) => registry.AddHandler(_ => new Handler(command, handler, _.GetRequiredService())); + + public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) => + registry.AddHandler( + _ => new Handler( + command, + (arg1, capability, token) => handler(arg1, token), + _.GetRequiredService() + ) ); - } - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler( - command, - (arg1, capability, token) => handler(arg1), - _.GetRequiredService()) + public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) => + registry.AddHandler( + _ => new Handler( + command, + (arg1, capability, token) => handler(arg1), + _.GetRequiredService() + ) ); - } - class Handler : ExecuteCommandHandlerBase + private class Handler : ExecuteCommandHandlerBase { private readonly Func _handler; - public Handler(string command, Func handler, ISerializer serializer) : base(command, serializer) - { + public Handler(string command, Func handler, ISerializer serializer) : base(command, serializer) => _handler = handler; - } public override async Task Handle(T arg1, CancellationToken cancellationToken) { @@ -229,37 +215,34 @@ public override async Task Handle(T arg1, CancellationToken cancellationTo } } - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler(command, handler, _.GetRequiredService())); - } + public static ILanguageServerRegistry OnExecuteCommand( + this ILanguageServerRegistry registry, string command, Func handler + ) => registry.AddHandler(_ => new Handler(command, handler, _.GetRequiredService())); - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler( - command, - (arg1, arg2, capability, token) => handler(arg1, arg2, token), - _.GetRequiredService()) + public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) => + registry.AddHandler( + _ => new Handler( + command, + (arg1, arg2, capability, token) => handler(arg1, arg2, token), + _.GetRequiredService() + ) ); - } - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler( - command, - (arg1, arg2, capability, token) => handler(arg1, arg2), - _.GetRequiredService()) + public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) => + registry.AddHandler( + _ => new Handler( + command, + (arg1, arg2, capability, token) => handler(arg1, arg2), + _.GetRequiredService() + ) ); - } - class Handler : ExecuteCommandHandlerBase + private class Handler : ExecuteCommandHandlerBase { private readonly Func _handler; - public Handler(string command, Func handler, ISerializer serializer) : base(command, serializer) - { + public Handler(string command, Func handler, ISerializer serializer) : base(command, serializer) => _handler = handler; - } public override async Task Handle(T arg1, T2 arg2, CancellationToken cancellationToken) { @@ -268,37 +251,36 @@ public override async Task Handle(T arg1, T2 arg2, CancellationToken cance } } - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler(command, handler, _.GetRequiredService())); - } + public static ILanguageServerRegistry OnExecuteCommand( + this ILanguageServerRegistry registry, string command, Func handler + ) => registry.AddHandler(_ => new Handler(command, handler, _.GetRequiredService())); - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler( - command, - (arg1, arg2, arg3, capability, token) => handler(arg1, arg2, arg3, token), - _.GetRequiredService()) + public static ILanguageServerRegistry OnExecuteCommand( + this ILanguageServerRegistry registry, string command, Func handler + ) => + registry.AddHandler( + _ => new Handler( + command, + (arg1, arg2, arg3, capability, token) => handler(arg1, arg2, arg3, token), + _.GetRequiredService() + ) ); - } - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler( - command, - (arg1, arg2, arg3, capability, token) => handler(arg1, arg2, arg3), - _.GetRequiredService()) + public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) => + registry.AddHandler( + _ => new Handler( + command, + (arg1, arg2, arg3, capability, token) => handler(arg1, arg2, arg3), + _.GetRequiredService() + ) ); - } - class Handler : ExecuteCommandHandlerBase + private class Handler : ExecuteCommandHandlerBase { private readonly Func _handler; - public Handler(string command, Func handler, ISerializer serializer) : base(command, serializer) - { + public Handler(string command, Func handler, ISerializer serializer) : base(command, serializer) => _handler = handler; - } public override async Task Handle(T arg1, T2 arg2, T3 arg3, CancellationToken cancellationToken) { @@ -307,37 +289,36 @@ public override async Task Handle(T arg1, T2 arg2, T3 arg3, CancellationTo } } - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler(command, handler, _.GetRequiredService())); - } + public static ILanguageServerRegistry OnExecuteCommand( + this ILanguageServerRegistry registry, string command, Func handler + ) => registry.AddHandler(_ => new Handler(command, handler, _.GetRequiredService())); - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler( - command, - (arg1, arg2, arg3, arg4, capability, token) => handler(arg1, arg2, arg3, arg4, token), - _.GetRequiredService()) + public static ILanguageServerRegistry OnExecuteCommand( + this ILanguageServerRegistry registry, string command, Func handler + ) => + registry.AddHandler( + _ => new Handler( + command, + (arg1, arg2, arg3, arg4, capability, token) => handler(arg1, arg2, arg3, arg4, token), + _.GetRequiredService() + ) ); - } - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler( - command, - (arg1, arg2, arg3, arg4, capability, token) => handler(arg1, arg2, arg3, arg4), - _.GetRequiredService()) + public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) => + registry.AddHandler( + _ => new Handler( + command, + (arg1, arg2, arg3, arg4, capability, token) => handler(arg1, arg2, arg3, arg4), + _.GetRequiredService() + ) ); - } - class Handler : ExecuteCommandHandlerBase + private class Handler : ExecuteCommandHandlerBase { private readonly Func _handler; - public Handler(string command, Func handler, ISerializer serializer) : base(command, serializer) - { + public Handler(string command, Func handler, ISerializer serializer) : base(command, serializer) => _handler = handler; - } public override async Task Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, CancellationToken cancellationToken) { @@ -346,37 +327,36 @@ public override async Task Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, Cance } } - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler(command, handler, _.GetRequiredService())); - } + public static ILanguageServerRegistry OnExecuteCommand( + this ILanguageServerRegistry registry, string command, Func handler + ) => registry.AddHandler(_ => new Handler(command, handler, _.GetRequiredService())); - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler( - command, - (arg1, arg2, arg3, arg4, arg5, capability, token) => handler(arg1, arg2, arg3, arg4, arg5, token), - _.GetRequiredService()) + public static ILanguageServerRegistry OnExecuteCommand( + this ILanguageServerRegistry registry, string command, Func handler + ) => + registry.AddHandler( + _ => new Handler( + command, + (arg1, arg2, arg3, arg4, arg5, capability, token) => handler(arg1, arg2, arg3, arg4, arg5, token), + _.GetRequiredService() + ) ); - } - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler( - command, - (arg1, arg2, arg3, arg4, arg5, capability, token) => handler(arg1, arg2, arg3, arg4, arg5), - _.GetRequiredService()) + public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) => + registry.AddHandler( + _ => new Handler( + command, + (arg1, arg2, arg3, arg4, arg5, capability, token) => handler(arg1, arg2, arg3, arg4, arg5), + _.GetRequiredService() + ) ); - } - class Handler : ExecuteCommandHandlerBase + private class Handler : ExecuteCommandHandlerBase { private readonly Func _handler; - public Handler(string command, Func handler, ISerializer serializer) : base(command, serializer) - { - _handler = handler; - } + public Handler(string command, Func handler, ISerializer serializer) : + base(command, serializer) => _handler = handler; public override async Task Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, CancellationToken cancellationToken) { @@ -385,37 +365,39 @@ public override async Task Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, T5 ar } } - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler(command, handler, _.GetRequiredService())); - } + public static ILanguageServerRegistry OnExecuteCommand( + this ILanguageServerRegistry registry, string command, Func handler + ) => registry.AddHandler(_ => new Handler(command, handler, _.GetRequiredService())); - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler( - command, - (arg1, arg2, arg3, arg4, arg5, arg6, capability, token) => handler(arg1, arg2, arg3, arg4, arg5, arg6, token), - _.GetRequiredService()) + public static ILanguageServerRegistry OnExecuteCommand( + this ILanguageServerRegistry registry, string command, Func handler + ) => + registry.AddHandler( + _ => new Handler( + command, + (arg1, arg2, arg3, arg4, arg5, arg6, capability, token) => handler(arg1, arg2, arg3, arg4, arg5, arg6, token), + _.GetRequiredService() + ) ); - } - public static ILanguageServerRegistry OnExecuteCommand(this ILanguageServerRegistry registry, string command, Func handler) - { - return registry.AddHandler(_ => new Handler( - command, - (arg1, arg2, arg3, arg4, arg5, arg6, capability, token) => handler(arg1, arg2, arg3, arg4, arg5, arg6), - _.GetRequiredService()) + public static ILanguageServerRegistry OnExecuteCommand( + this ILanguageServerRegistry registry, string command, Func handler + ) => + registry.AddHandler( + _ => new Handler( + command, + (arg1, arg2, arg3, arg4, arg5, arg6, capability, token) => handler(arg1, arg2, arg3, arg4, arg5, arg6), + _.GetRequiredService() + ) ); - } - class Handler : ExecuteCommandHandlerBase + private class Handler : ExecuteCommandHandlerBase { private readonly Func _handler; - public Handler(string command, Func handler, ISerializer serializer) : base(command, serializer) - { - _handler = handler; - } + public Handler(string command, Func handler, ISerializer serializer) : base( + command, serializer + ) => _handler = handler; public override async Task Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, CancellationToken cancellationToken) { diff --git a/src/Protocol/Workspace/IWorkspaceFoldersHandler.cs b/src/Protocol/Workspace/IWorkspaceFoldersHandler.cs index 01e15fed6..f8f8e2410 100644 --- a/src/Protocol/Workspace/IWorkspaceFoldersHandler.cs +++ b/src/Protocol/Workspace/IWorkspaceFoldersHandler.cs @@ -7,9 +7,13 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Workspace { - [Parallel, Method(WorkspaceNames.WorkspaceFolders, Direction.ServerToClient)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(IWorkspaceLanguageServer), typeof(ILanguageServer))] - public interface IWorkspaceFoldersHandler : IJsonRpcRequestHandler> { } + [Parallel] + [Method(WorkspaceNames.WorkspaceFolders, Direction.ServerToClient)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(IWorkspaceLanguageServer), typeof(ILanguageServer))] + public interface IWorkspaceFoldersHandler : IJsonRpcRequestHandler> + { + } public abstract class WorkspaceFoldersHandler : IWorkspaceFoldersHandler { diff --git a/src/Protocol/Workspace/IWorkspaceSymbolsHandler.cs b/src/Protocol/Workspace/IWorkspaceSymbolsHandler.cs index d1f5d40d5..d7dbffced 100644 --- a/src/Protocol/Workspace/IWorkspaceSymbolsHandler.cs +++ b/src/Protocol/Workspace/IWorkspaceSymbolsHandler.cs @@ -8,19 +8,21 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Workspace { - [Parallel, Method(WorkspaceNames.WorkspaceSymbol, Direction.ClientToServer)] - [GenerateHandlerMethods, GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] - public interface IWorkspaceSymbolsHandler : IJsonRpcRequestHandler>, ICapability, IRegistration { } + [Parallel] + [Method(WorkspaceNames.WorkspaceSymbol, Direction.ClientToServer)] + [GenerateHandlerMethods] + [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] + public interface IWorkspaceSymbolsHandler : IJsonRpcRequestHandler>, ICapability, + IRegistration + { + } public abstract class WorkspaceSymbolsHandler : IWorkspaceSymbolsHandler { protected WorkspaceSymbolCapability Capability { get; private set; } private readonly WorkspaceSymbolRegistrationOptions _options; - public WorkspaceSymbolsHandler(WorkspaceSymbolRegistrationOptions registrationOptions) - { - _options = registrationOptions; - } + public WorkspaceSymbolsHandler(WorkspaceSymbolRegistrationOptions registrationOptions) => _options = registrationOptions; public WorkspaceSymbolRegistrationOptions GetRegistrationOptions() => _options; public abstract Task> Handle(WorkspaceSymbolParams request, CancellationToken cancellationToken); diff --git a/src/Protocol/WorkspaceFolderChange.cs b/src/Protocol/WorkspaceFolderChange.cs index 0b879971e..581c0c1b4 100644 --- a/src/Protocol/WorkspaceFolderChange.cs +++ b/src/Protocol/WorkspaceFolderChange.cs @@ -13,4 +13,4 @@ public WorkspaceFolderChange(WorkspaceFolderEvent @event, WorkspaceFolder folder public WorkspaceFolderEvent Event { get; } public WorkspaceFolder Folder { get; } } -} \ No newline at end of file +} diff --git a/src/Server/ClientCapabilityProvider.cs b/src/Server/ClientCapabilityProvider.cs index 74d20befe..61f1b29fb 100644 --- a/src/Server/ClientCapabilityProvider.cs +++ b/src/Server/ClientCapabilityProvider.cs @@ -27,20 +27,18 @@ public bool HasStaticHandler(Supports capability) // Dynamic registration will cause us to double register things if we report our capabilities staticly. // However if the client does not tell us it's capabilities we should just assume that they do not support // dynamic registraiton but we should report any capabilities statically - if (capability.IsSupported && capability.Value != null && capability.Value.DynamicRegistration == true) return false; + if (capability.IsSupported && capability.Value != null && capability.Value.DynamicRegistration) return false; var handlerTypes = typeof(T).GetTypeInfo().ImplementedInterfaces - .Where(x => x.GetTypeInfo().IsGenericType && x.GetTypeInfo().GetGenericTypeDefinition() == typeof(ConnectedCapability<>)) - .Select(x => x.GetTypeInfo().GetGenericArguments()[0].GetTypeInfo()); + .Where(x => x.GetTypeInfo().IsGenericType && x.GetTypeInfo().GetGenericTypeDefinition() == typeof(ConnectedCapability<>)) + .Select(x => x.GetTypeInfo().GetGenericArguments()[0].GetTypeInfo()); return handlerTypes.Any(_collection.ContainsHandler); } public IOptionsGetter GetStaticOptions(Supports capability) - where T : DynamicCapability, ConnectedCapability - { - return !HasStaticHandler(capability) ? Null : new OptionsGetter(_collection, _supportsProgress); - } + where T : DynamicCapability, ConnectedCapability => + !HasStaticHandler(capability) ? Null : new OptionsGetter(_collection, _supportsProgress); private static readonly IOptionsGetter Null = new NullOptionsGetter(); @@ -70,16 +68,12 @@ TOptions Reduce(Func, IEnumerable< private class NullOptionsGetter : IOptionsGetter { public TOptions Get(Func, TOptions> action) - where TOptions : class - { - return null; - } + where TOptions : class => + null; public TOptions Reduce(Func, IEnumerable, TOptions> action) - where TOptions : class - { - return null; - } + where TOptions : class => + null; } private class OptionsGetter : IOptionsGetter @@ -97,12 +91,13 @@ public TOptions Get(Func x.RegistrationOptions is TInterface cl ? action(cl, _collection) : null) - .FirstOrDefault(x => x != null); + .Select(x => x.RegistrationOptions is TInterface cl ? action(cl, _collection) : null) + .FirstOrDefault(x => x != null); if (value is IWorkDoneProgressOptions wdpo) { wdpo.WorkDoneProgress = _supportsProgress; } + return value; } @@ -110,12 +105,13 @@ public Supports Can(Func x.RegistrationOptions is TInterface cl ? action(cl, _collection) : null) - .FirstOrDefault(x => x != null); + .Select(x => x.RegistrationOptions is TInterface cl ? action(cl, _collection) : null) + .FirstOrDefault(x => x != null); if (options is IWorkDoneProgressOptions wdpo) { wdpo.WorkDoneProgress = _supportsProgress; } + if (options == null) return Supports.OfBoolean(false); @@ -125,9 +121,11 @@ public Supports Can(Func(Func, IEnumerable, TOptions> action) where TOptions : class { - var value = action(_collection - .Select(x => x.RegistrationOptions is TInterface cl ? cl : default) - .Where(x => x != null), _collection); + var value = action( + _collection + .Select(x => x.RegistrationOptions is TInterface cl ? cl : default) + .Where(x => x != null), _collection + ); if (value is IWorkDoneProgressOptions wdpo) { diff --git a/src/Server/Configuration/BaseWorkspaceConfigurationProvider.cs b/src/Server/Configuration/BaseWorkspaceConfigurationProvider.cs index b02345ea7..493afa8d2 100644 --- a/src/Server/Configuration/BaseWorkspaceConfigurationProvider.cs +++ b/src/Server/Configuration/BaseWorkspaceConfigurationProvider.cs @@ -9,7 +9,7 @@ namespace OmniSharp.Extensions.LanguageServer.Server.Configuration { - class BaseWorkspaceConfigurationProvider : ConfigurationProvider + internal class BaseWorkspaceConfigurationProvider : ConfigurationProvider { protected void ParseClientConfiguration(JToken settings, string prefix = null) { @@ -24,12 +24,16 @@ protected void ParseClientConfiguration(JToken settings, string prefix = null) { foreach (var item in JObject.FromObject(settings) - .Descendants() - .Where(p => !p.Any()) - .OfType() - .Select(item => - new KeyValuePair(GetKey(item, prefix), - item.ToString(CultureInfo.InvariantCulture)))) + .Descendants() + .Where(p => !p.Any()) + .OfType() + .Select( + item => + new KeyValuePair( + GetKey(item, prefix), + item.ToString(CultureInfo.InvariantCulture) + ) + )) { Data[item.Key] = item.Value; } @@ -39,10 +43,12 @@ protected void ParseClientConfiguration(JToken settings, string prefix = null) // Might not have been json... try xml. foreach (var item in XDocument.Parse(settings.ToString()) - .Descendants() - .Where(p => !p.Descendants().Any()) - .Select(item => - new KeyValuePair(GetKey(item, prefix), item.ToString()))) + .Descendants() + .Where(p => !p.Descendants().Any()) + .Select( + item => + new KeyValuePair(GetKey(item, prefix), item.ToString()) + )) { Data[item.Key] = item.Value; } diff --git a/src/Server/Configuration/DidChangeConfigurationProvider.cs b/src/Server/Configuration/DidChangeConfigurationProvider.cs index c2372ebce..1f0131be7 100644 --- a/src/Server/Configuration/DidChangeConfigurationProvider.cs +++ b/src/Server/Configuration/DidChangeConfigurationProvider.cs @@ -7,7 +7,6 @@ using System.Threading.Tasks; using MediatR; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; using Newtonsoft.Json.Linq; @@ -15,12 +14,11 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using OmniSharp.Extensions.LanguageServer.Protocol.Shared; using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; namespace OmniSharp.Extensions.LanguageServer.Server.Configuration { - class DidChangeConfigurationProvider : BaseWorkspaceConfigurationProvider, IDidChangeConfigurationHandler, IOnLanguageServerStarted, ILanguageServerConfiguration + internal class DidChangeConfigurationProvider : BaseWorkspaceConfigurationProvider, IDidChangeConfigurationHandler, IOnLanguageServerStarted, ILanguageServerConfiguration { private readonly IEnumerable _configurationItems; private readonly ILogger _logger; @@ -35,13 +33,14 @@ public DidChangeConfigurationProvider( IEnumerable configurationItems, Action configurationBuilderAction, ILogger logger, - IWorkspaceLanguageServer workspaceLanguageServer) + IWorkspaceLanguageServer workspaceLanguageServer + ) { _configurationItems = configurationItems; _logger = logger; _workspaceLanguageServer = workspaceLanguageServer; var builder = new ConfigurationBuilder() - .Add(new DidChangeConfigurationSource(this)); + .Add(new DidChangeConfigurationSource(this)); configurationBuilderAction(builder); _configuration = builder.Build() as ConfigurationRoot; } @@ -80,12 +79,16 @@ private async Task GetWorkspaceConfiguration() } { - var configurations = (await _workspaceLanguageServer.RequestConfiguration(new ConfigurationParams() { - Items = configurationItems - })).ToArray(); + var configurations = ( await _workspaceLanguageServer.RequestConfiguration( + new ConfigurationParams { + Items = configurationItems + } + ) ).ToArray(); - foreach (var (scope, settings) in configurationItems.Zip(configurations, - (scope, settings) => (scope, settings))) + foreach (var (scope, settings) in configurationItems.Zip( + configurations, + (scope, settings) => ( scope, settings ) + )) { ParseClientConfiguration(settings, scope.Section); } @@ -95,25 +98,27 @@ private async Task GetWorkspaceConfiguration() { var scopedConfigurationItems = configurationItems - .SelectMany(scope => - _openScopes.Keys.Select(scopeUri => new ConfigurationItem() { ScopeUri = scopeUri, Section = scope.Section }) - ).ToArray(); + .SelectMany( + scope => + _openScopes.Keys.Select(scopeUri => new ConfigurationItem { ScopeUri = scopeUri, Section = scope.Section }) + ).ToArray(); try { - - var configurations = (await _workspaceLanguageServer.RequestConfiguration(new ConfigurationParams() { - Items = scopedConfigurationItems - })).ToArray(); + var configurations = ( await _workspaceLanguageServer.RequestConfiguration( + new ConfigurationParams { + Items = scopedConfigurationItems + } + ) ).ToArray(); var groups = scopedConfigurationItems - .Zip(configurations, (scope, settings) => (scope, settings)) - .GroupBy(z => z.scope.ScopeUri); + .Zip(configurations, (scope, settings) => ( scope, settings )) + .GroupBy(z => z.scope.ScopeUri); foreach (var group in groups) { if (!_openScopes.TryGetValue(group.Key, out var source)) continue; - source.Update(group.Select(z => (z.scope.Section, z.settings))); + source.Update(group.Select(z => ( z.scope.Section, z.settings ))); } } catch (Exception e) @@ -142,19 +147,23 @@ public async Task GetConfiguration(params ConfigurationItem[] it return new ConfigurationBuilder().AddInMemoryCollection(_configuration.AsEnumerable()).Build(); } - var configurations = await _workspaceLanguageServer.RequestConfiguration(new ConfigurationParams() { - Items = items - }); - var data = items.Zip(configurations, - (scope, settings) => (scope.Section, settings)); + var configurations = await _workspaceLanguageServer.RequestConfiguration( + new ConfigurationParams { + Items = items + } + ); + var data = items.Zip( + configurations, + (scope, settings) => ( scope.Section, settings ) + ); return new ConfigurationBuilder() - // this avoids chaining the configurations - // so that the returned configuration object - // is stateless. - // scoped configuration should be a snapshot of the current state. - .AddInMemoryCollection(_configuration.AsEnumerable()) - .Add(new WorkspaceConfigurationSource(data)) - .Build(); + // this avoids chaining the configurations + // so that the returned configuration object + // is stateless. + // scoped configuration should be a snapshot of the current state. + .AddInMemoryCollection(_configuration.AsEnumerable()) + .Add(new WorkspaceConfigurationSource(data)) + .Build(); } public async Task GetScopedConfiguration(DocumentUri scopeUri) @@ -163,19 +172,24 @@ public async Task GetScopedConfiguration(DocumentUri scope if (scopes.Length == 0) return EmptyDisposableConfiguration.Instance; - var configurations = await _workspaceLanguageServer .RequestConfiguration(new ConfigurationParams() { - Items = scopes.Select(z => new ConfigurationItem() { Section = z.Section, ScopeUri = scopeUri }).ToArray() - }); + var configurations = await _workspaceLanguageServer.RequestConfiguration( + new ConfigurationParams { + Items = scopes.Select(z => new ConfigurationItem { Section = z.Section, ScopeUri = scopeUri }).ToArray() + } + ); - var data = scopes.Zip(configurations, - (scope, settings) => (scope.Section, settings)); + var data = scopes.Zip( + configurations, + (scope, settings) => ( scope.Section, settings ) + ); var config = new DisposableConfiguration( new ConfigurationBuilder() - .AddConfiguration(_configuration), + .AddConfiguration(_configuration), new WorkspaceConfigurationSource(data), Disposable.Create( - () => _openScopes.TryRemove(scopeUri, out _)) + () => _openScopes.TryRemove(scopeUri, out _) + ) ); _openScopes.TryAdd(scopeUri, config); diff --git a/src/Server/Configuration/DidChangeConfigurationSource.cs b/src/Server/Configuration/DidChangeConfigurationSource.cs index 7edf5921c..3abad1f67 100644 --- a/src/Server/Configuration/DidChangeConfigurationSource.cs +++ b/src/Server/Configuration/DidChangeConfigurationSource.cs @@ -2,14 +2,11 @@ namespace OmniSharp.Extensions.LanguageServer.Server.Configuration { - class DidChangeConfigurationSource : IConfigurationSource + internal class DidChangeConfigurationSource : IConfigurationSource { private readonly DidChangeConfigurationProvider _provider; - public DidChangeConfigurationSource(DidChangeConfigurationProvider provider) - { - _provider = provider; - } + public DidChangeConfigurationSource(DidChangeConfigurationProvider provider) => _provider = provider; public IConfigurationProvider Build(IConfigurationBuilder builder) => _provider; } diff --git a/src/Server/Configuration/DisposableConfiguration.cs b/src/Server/Configuration/DisposableConfiguration.cs index db08078fd..87b0c2296 100644 --- a/src/Server/Configuration/DisposableConfiguration.cs +++ b/src/Server/Configuration/DisposableConfiguration.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.LanguageServer.Server.Configuration { - class DisposableConfiguration : IScopedConfiguration + internal class DisposableConfiguration : IScopedConfiguration { private readonly ConfigurationRoot _configuration; private readonly WorkspaceConfigurationSource _configurationSource; diff --git a/src/Server/Configuration/EmptyDisposableConfiguration.cs b/src/Server/Configuration/EmptyDisposableConfiguration.cs index bf3069d24..6252c0a21 100644 --- a/src/Server/Configuration/EmptyDisposableConfiguration.cs +++ b/src/Server/Configuration/EmptyDisposableConfiguration.cs @@ -6,16 +6,16 @@ namespace OmniSharp.Extensions.LanguageServer.Server.Configuration { - class EmptyDisposableConfiguration : IScopedConfiguration + internal class EmptyDisposableConfiguration : IScopedConfiguration { public static EmptyDisposableConfiguration Instance { get; } = new EmptyDisposableConfiguration(); - private ConfigurationRoot _configuration; + private readonly ConfigurationRoot _configuration; - private EmptyDisposableConfiguration() + private EmptyDisposableConfiguration() => _configuration = new ConfigurationBuilder().Build() as ConfigurationRoot; + + void IDisposable.Dispose() { - _configuration = new ConfigurationBuilder().Build() as ConfigurationRoot; } - void IDisposable.Dispose() { } IConfigurationSection IConfiguration.GetSection(string key) => _configuration.GetSection(key); diff --git a/src/Server/Configuration/WorkspaceConfigurationProvider.cs b/src/Server/Configuration/WorkspaceConfigurationProvider.cs index c9bea38c4..44897fd8b 100644 --- a/src/Server/Configuration/WorkspaceConfigurationProvider.cs +++ b/src/Server/Configuration/WorkspaceConfigurationProvider.cs @@ -3,12 +3,9 @@ namespace OmniSharp.Extensions.LanguageServer.Server.Configuration { - class WorkspaceConfigurationProvider : BaseWorkspaceConfigurationProvider + internal class WorkspaceConfigurationProvider : BaseWorkspaceConfigurationProvider { - public WorkspaceConfigurationProvider(IEnumerable<(string key, JToken settings)> configuration) - { - Update(configuration); - } + public WorkspaceConfigurationProvider(IEnumerable<(string key, JToken settings)> configuration) => Update(configuration); internal void Update(IEnumerable<(string key, JToken settings)> values) { @@ -16,6 +13,7 @@ internal void Update(IEnumerable<(string key, JToken settings)> values) { ParseClientConfiguration(settings, key); } + OnReload(); } } diff --git a/src/Server/Configuration/WorkspaceConfigurationSource.cs b/src/Server/Configuration/WorkspaceConfigurationSource.cs index 68793b118..cf63b81c4 100644 --- a/src/Server/Configuration/WorkspaceConfigurationSource.cs +++ b/src/Server/Configuration/WorkspaceConfigurationSource.cs @@ -4,14 +4,11 @@ namespace OmniSharp.Extensions.LanguageServer.Server.Configuration { - class WorkspaceConfigurationSource : IConfigurationSource + internal class WorkspaceConfigurationSource : IConfigurationSource { - private WorkspaceConfigurationProvider _provider; + private readonly WorkspaceConfigurationProvider _provider; - public WorkspaceConfigurationSource(IEnumerable<(string key, JToken settings)> configuration) - { - _provider = new WorkspaceConfigurationProvider(configuration); - } + public WorkspaceConfigurationSource(IEnumerable<(string key, JToken settings)> configuration) => _provider = new WorkspaceConfigurationProvider(configuration); public IConfigurationProvider Build(IConfigurationBuilder builder) => _provider; diff --git a/src/Server/LangaugeServerRegistry.cs b/src/Server/LangaugeServerRegistry.cs index 2edfc99f8..2e25a167c 100644 --- a/src/Server/LangaugeServerRegistry.cs +++ b/src/Server/LangaugeServerRegistry.cs @@ -6,10 +6,11 @@ namespace OmniSharp.Extensions.LanguageServer.Server { - class LangaugeServerRegistry : InterimLanguageProtocolRegistry, ILanguageServerRegistry + internal class LangaugeServerRegistry : InterimLanguageProtocolRegistry, ILanguageServerRegistry { public LangaugeServerRegistry(IServiceProvider serviceProvider, CompositeHandlersManager handlersManager, TextDocumentIdentifiers textDocumentIdentifiers) : base( - serviceProvider, handlersManager, textDocumentIdentifiers) + serviceProvider, handlersManager, textDocumentIdentifiers + ) { } } diff --git a/src/Server/LanguageServer.Shutdown.cs b/src/Server/LanguageServer.Shutdown.cs index be76e9b21..6b8fa89e1 100644 --- a/src/Server/LanguageServer.Shutdown.cs +++ b/src/Server/LanguageServer.Shutdown.cs @@ -23,8 +23,8 @@ public partial class LanguageServer : IExitHandler, IShutdownHandler public void ForcefulShutdown() { - ((IShutdownHandler) this).Handle(ShutdownParams.Instance, CancellationToken.None); - ((IExitHandler) this).Handle(ExitParams.Instance, CancellationToken.None); + ( (IShutdownHandler) this ).Handle(ShutdownParams.Instance, CancellationToken.None); + ( (IExitHandler) this ).Handle(ExitParams.Instance, CancellationToken.None); } async Task IRequestHandler.Handle(ExitParams request, CancellationToken token) @@ -52,6 +52,7 @@ async Task IRequestHandler.Handle(ShutdownParams req { _shutdownSubject.OnCompleted(); } + return Unit.Value; } } diff --git a/src/Server/LanguageServer.cs b/src/Server/LanguageServer.cs index 6548d3390..df199c40b 100644 --- a/src/Server/LanguageServer.cs +++ b/src/Server/LanguageServer.cs @@ -1,42 +1,41 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Reactive.Threading.Tasks; using System.Threading; using System.Threading.Tasks; +using DryIoc; using MediatR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Server.Abstractions; -using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; -using System.Reactive.Disposables; -using DryIoc; -using Microsoft.Extensions.Options; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.General; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; using OmniSharp.Extensions.LanguageServer.Protocol.Server; 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.Window; using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; +using OmniSharp.Extensions.LanguageServer.Server.Abstractions; using OmniSharp.Extensions.LanguageServer.Server.Logging; using OmniSharp.Extensions.LanguageServer.Shared; +using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; namespace OmniSharp.Extensions.LanguageServer.Server { public partial class LanguageServer : JsonRpcServerBase, ILanguageServer, ILanguageProtocolInitializeHandler, ILanguageProtocolInitializedHandler, IAwaitableTermination, - IDisposable + IDisposable { private readonly Connection _connection; private ClientVersion? _clientVersion; @@ -57,11 +56,11 @@ public partial class LanguageServer : JsonRpcServerBase, ILanguageServer, ILangu private Task _initializingTask; private readonly LanguageProtocolSettingsBag _settingsBag; private bool _started; - private int? _concurrency; + private readonly int? _concurrency; internal static IContainer CreateContainer(LanguageServerOptions options, IServiceProvider outerServiceProvider) => JsonRpcServerContainer.Create(outerServiceProvider) - .AddLanguageServerInternals(options, outerServiceProvider); + .AddLanguageServerInternals(options, outerServiceProvider); public static LanguageServer Create(LanguageServerOptions options) => Create(options, null); public static LanguageServer Create(Action optionsAction) => Create(optionsAction, null); @@ -108,10 +107,7 @@ public static async Task From(LanguageServerOptions options, ISe /// /// /// - public static LanguageServer PreInit(Action optionsAction) - { - return Create(optionsAction); - } + public static LanguageServer PreInit(Action optionsAction) => Create(optionsAction); /// /// Create the server without connecting to the client @@ -120,10 +116,7 @@ public static LanguageServer PreInit(Action optionsAction /// /// /// - public static LanguageServer PreInit(LanguageServerOptions options) - { - return Create(options); - } + public static LanguageServer PreInit(LanguageServerOptions options) => Create(options); internal LanguageServer( Connection connection, @@ -150,7 +143,8 @@ internal LanguageServer( SharedHandlerCollection handlerCollection, IProgressManager progressManager, ILanguageServerWorkspaceFolderManager workspaceFolderManager, IEnumerable initializeHandlers, - IEnumerable initializedHandlers) : base(handlerCollection, responseRouter) + IEnumerable initializedHandlers + ) : base(handlerCollection, responseRouter) { Configuration = configuration; @@ -254,7 +248,8 @@ await LanguageProtocolEventingHelper.Run( } async Task IRequestHandler.Handle( - InitializeParams request, CancellationToken token) + InitializeParams request, CancellationToken token + ) { ClientSettings = request; @@ -323,67 +318,70 @@ await LanguageProtocolEventingHelper.Run( var ccp = new ClientCapabilityProvider(_collection, windowCapabilities.WorkDoneProgress); - var serverCapabilities = new ServerCapabilities() { + var serverCapabilities = new ServerCapabilities { CodeActionProvider = ccp.GetStaticOptions(textDocumentCapabilities.CodeAction) - .Get(CodeActionOptions.Of), + .Get(CodeActionOptions.Of), CodeLensProvider = ccp.GetStaticOptions(textDocumentCapabilities.CodeLens) - .Get(CodeLensOptions.Of), + .Get(CodeLensOptions.Of), CompletionProvider = ccp.GetStaticOptions(textDocumentCapabilities.Completion) - .Get(CompletionOptions.Of), + .Get(CompletionOptions.Of), DefinitionProvider = ccp.GetStaticOptions(textDocumentCapabilities.Definition) - .Get(DefinitionOptions.Of), + .Get(DefinitionOptions.Of), DocumentFormattingProvider = ccp.GetStaticOptions(textDocumentCapabilities.Formatting) - .Get(DocumentFormattingOptions.Of), + .Get(DocumentFormattingOptions.Of), DocumentHighlightProvider = ccp.GetStaticOptions(textDocumentCapabilities.DocumentHighlight) - .Get(DocumentHighlightOptions.Of), + .Get(DocumentHighlightOptions.Of), DocumentLinkProvider = ccp.GetStaticOptions(textDocumentCapabilities.DocumentLink) - .Get(DocumentLinkOptions.Of), + .Get(DocumentLinkOptions.Of), DocumentOnTypeFormattingProvider = ccp.GetStaticOptions(textDocumentCapabilities.OnTypeFormatting) - .Get( - DocumentOnTypeFormattingOptions.Of), + .Get( + DocumentOnTypeFormattingOptions.Of + ), DocumentRangeFormattingProvider = ccp.GetStaticOptions(textDocumentCapabilities.RangeFormatting) - .Get(DocumentRangeFormattingOptions - .Of), + .Get( + DocumentRangeFormattingOptions + .Of + ), DocumentSymbolProvider = ccp.GetStaticOptions(textDocumentCapabilities.DocumentSymbol) - .Get(DocumentSymbolOptions.Of), + .Get(DocumentSymbolOptions.Of), ExecuteCommandProvider = ccp.GetStaticOptions(workspaceCapabilities.ExecuteCommand) - .Reduce(ExecuteCommandOptions.Of), + .Reduce(ExecuteCommandOptions.Of), TextDocumentSync = ccp.GetStaticOptions(textDocumentCapabilities.Synchronization) - .Reduce(TextDocumentSyncOptions.Of), + .Reduce(TextDocumentSyncOptions.Of), HoverProvider = ccp.GetStaticOptions(textDocumentCapabilities.Hover) - .Get(HoverOptions.Of), + .Get(HoverOptions.Of), ReferencesProvider = ccp.GetStaticOptions(textDocumentCapabilities.References) - .Get(ReferencesOptions.Of), + .Get(ReferencesOptions.Of), RenameProvider = ccp.GetStaticOptions(textDocumentCapabilities.Rename) - .Get(RenameOptions.Of), + .Get(RenameOptions.Of), SignatureHelpProvider = ccp.GetStaticOptions(textDocumentCapabilities.SignatureHelp) - .Get(SignatureHelpOptions.Of), + .Get(SignatureHelpOptions.Of), WorkspaceSymbolProvider = ccp.GetStaticOptions(workspaceCapabilities.Symbol) - .Get(WorkspaceSymbolOptions.Of), + .Get(WorkspaceSymbolOptions.Of), ImplementationProvider = ccp.GetStaticOptions(textDocumentCapabilities.Implementation) - .Get(ImplementationOptions.Of), + .Get(ImplementationOptions.Of), TypeDefinitionProvider = ccp.GetStaticOptions(textDocumentCapabilities.TypeDefinition) - .Get(TypeDefinitionOptions.Of), + .Get(TypeDefinitionOptions.Of), ColorProvider = ccp.GetStaticOptions(textDocumentCapabilities.ColorProvider) - .Get(DocumentColorOptions.Of), + .Get(DocumentColorOptions.Of), FoldingRangeProvider = ccp.GetStaticOptions(textDocumentCapabilities.FoldingRange) - .Get(FoldingRangeOptions.Of), + .Get(FoldingRangeOptions.Of), SelectionRangeProvider = ccp.GetStaticOptions(textDocumentCapabilities.FoldingRange) - .Get(SelectionRangeOptions.Of), + .Get(SelectionRangeOptions.Of), DeclarationProvider = ccp.GetStaticOptions(textDocumentCapabilities.Declaration) - .Get(DeclarationOptions.Of), + .Get(DeclarationOptions.Of), #pragma warning disable 618 CallHierarchyProvider = ccp.GetStaticOptions(textDocumentCapabilities.CallHierarchy) - .Get(CallHierarchyOptions.Of), + .Get(CallHierarchyOptions.Of), SemanticTokensProvider = ccp.GetStaticOptions(textDocumentCapabilities.SemanticTokens) - .Get(SemanticTokensOptions.Of), + .Get(SemanticTokensOptions.Of), #pragma warning restore 618 }; if (_collection.ContainsHandler(typeof(IDidChangeWorkspaceFoldersHandler))) { - serverCapabilities.Workspace = new WorkspaceServerCapabilities() { - WorkspaceFolders = new WorkspaceFolderOptions() { + serverCapabilities.Workspace = new WorkspaceServerCapabilities { + WorkspaceFolders = new WorkspaceFolderOptions { Supported = true, ChangeNotifications = Guid.NewGuid().ToString() } @@ -396,11 +394,11 @@ await LanguageProtocolEventingHelper.Run( if (_collection.ContainsHandler(typeof(IDidChangeTextDocumentHandler))) { var kinds = _collection - .Select(x => x.Handler) - .OfType() - .Select(x => x.GetRegistrationOptions()?.SyncKind ?? TextDocumentSyncKind.None) - .Where(x => x != TextDocumentSyncKind.None) - .ToArray(); + .Select(x => x.Handler) + .OfType() + .Select(x => x.GetRegistrationOptions()?.SyncKind ?? TextDocumentSyncKind.None) + .Where(x => x != TextDocumentSyncKind.None) + .ToArray(); if (kinds.Any()) { textDocumentSyncKind = kinds.Min(z => z); @@ -413,12 +411,12 @@ await LanguageProtocolEventingHelper.Run( } else { - serverCapabilities.TextDocumentSync = new TextDocumentSyncOptions() { + serverCapabilities.TextDocumentSync = new TextDocumentSyncOptions { Change = textDocumentSyncKind, OpenClose = _collection.ContainsHandler(typeof(IDidOpenTextDocumentHandler)) || _collection.ContainsHandler(typeof(IDidCloseTextDocumentHandler)), Save = _collection.ContainsHandler(typeof(IDidSaveTextDocumentHandler)) - ? new SaveOptions() {IncludeText = true /* TODO: Make configurable */} + ? new SaveOptions { IncludeText = true /* TODO: Make configurable */ } : null, WillSave = _collection.ContainsHandler(typeof(IWillSaveTextDocumentHandler)), WillSaveWaitUntil = _collection.ContainsHandler(typeof(IWillSaveWaitUntilTextDocumentHandler)) @@ -431,7 +429,7 @@ await LanguageProtocolEventingHelper.Run( _serverReceiver.Initialized(); - var result = ServerSettings = new InitializeResult() { + var result = ServerSettings = new InitializeResult { Capabilities = serverCapabilities, ServerInfo = _serverInfo }; @@ -460,7 +458,7 @@ await LanguageProtocolEventingHelper.Run( return result; } - public async Task Handle(InitializedParams @params, CancellationToken token) + public async Task Handle(InitializedParams @params, CancellationToken token) { if (_clientVersion == ClientVersion.Lsp3) { @@ -468,7 +466,7 @@ await LanguageProtocolEventingHelper.Run( _initializeComplete.OnCompleted(); } - return MediatR.Unit.Value; + return Unit.Value; } private async Task DynamicallyRegisterHandlers(Registration[] registrations) @@ -476,7 +474,7 @@ private async Task DynamicallyRegisterHandlers(Registration[] registrations) if (registrations.Length == 0) return; // No dynamic registrations supported by client. - var @params = new RegistrationParams() {Registrations = registrations}; + var @params = new RegistrationParams { Registrations = registrations }; await _initializeComplete; @@ -506,30 +504,31 @@ public IDisposable Register(Action registryAction) static IEnumerable GetUniqueHandlers(CompositeDisposable disposable) { return disposable.OfType() - .Select(z => z.Handler) - .OfType() - .Concat(disposable.OfType().SelectMany(GetUniqueHandlers)) - .Concat(disposable.OfType().SelectMany(GetLspHandlers)) - .Distinct(); + .Select(z => z.Handler) + .OfType() + .Concat(disposable.OfType().SelectMany(GetUniqueHandlers)) + .Concat(disposable.OfType().SelectMany(GetLspHandlers)) + .Distinct(); } + static IEnumerable GetLspHandlers(LspHandlerDescriptorDisposable disposable) { return disposable.Descriptors - .Select(z => z.Handler) - .OfType() - .Distinct(); + .Select(z => z.Handler) + .OfType() + .Distinct(); } Observable.Concat( GetUniqueHandlers(result) - .Select(handler => Observable.FromAsync((ct) => handler.OnInitialize(this, ClientSettings, ct))) - .Merge(), + .Select(handler => Observable.FromAsync(ct => handler.OnInitialize(this, ClientSettings, ct))) + .Merge(), GetUniqueHandlers(result) - .Select(handler => Observable.FromAsync((ct) => handler.OnInitialized(this, ClientSettings, ServerSettings, ct))) - .Merge(), + .Select(handler => Observable.FromAsync(ct => handler.OnInitialized(this, ClientSettings, ServerSettings, ct))) + .Merge(), GetUniqueHandlers(result) - .Select(handler => Observable.FromAsync((ct) => handler.OnStarted(this, ct))) - .Merge() + .Select(handler => Observable.FromAsync(ct => handler.OnStarted(this, ct))) + .Merge() ).Subscribe(); } @@ -555,22 +554,28 @@ private IDisposable RegisterHandlers(IEnumerable collecti wdpo.WorkDoneProgress = WorkDoneManager.IsSupported; } - registrations.Add(new Registration() { - Id = descriptor.Id.ToString(), - Method = descriptor.Method, - RegisterOptions = descriptor.RegistrationOptions - }); + registrations.Add( + new Registration { + Id = descriptor.Id.ToString(), + Method = descriptor.Method, + RegisterOptions = descriptor.RegistrationOptions + } + ); } } // Fire and forget DynamicallyRegisterHandlers(registrations.ToArray()).ToObservable().Subscribe(); - return Disposable.Create(() => { - Client.UnregisterCapability(new UnregistrationParams() { - Unregisterations = registrations.ToArray() - }).ToObservable().Subscribe(); - }); + return Disposable.Create( + () => { + Client.UnregisterCapability( + new UnregistrationParams { + Unregisterations = registrations.ToArray() + } + ).ToObservable().Subscribe(); + } + ); } private IDisposable RegisterHandlers(IDisposable handlerDisposable) @@ -580,7 +585,7 @@ private IDisposable RegisterHandlers(IDisposable handlerDisposable) return new CompositeDisposable(lsp, RegisterHandlers(lsp.Descriptors)); } - if (!(handlerDisposable is CompositeDisposable cd)) return Disposable.Empty; + if (!( handlerDisposable is CompositeDisposable cd )) return Disposable.Empty; cd.Add(RegisterHandlers(cd.OfType().SelectMany(z => z.Descriptors))); return cd; } diff --git a/src/Server/LanguageServerOptions.cs b/src/Server/LanguageServerOptions.cs index c5145123b..e9e9db835 100644 --- a/src/Server/LanguageServerOptions.cs +++ b/src/Server/LanguageServerOptions.cs @@ -1,24 +1,11 @@ using System; -using System.Collections.Generic; -using System.IO.Pipelines; -using System.Reactive.Disposables; -using System.Reflection; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.LanguageServer.Protocol; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; -using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using OmniSharp.Extensions.LanguageServer.Protocol.Shared; -using OmniSharp.Extensions.LanguageServer.Shared; -using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; namespace OmniSharp.Extensions.LanguageServer.Server { @@ -33,62 +20,98 @@ public LanguageServerOptions WithReceiver(ILspServerReceiver receiver) return this; } - ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options) => AddHandler(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options) => + AddHandler(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => AddHandler(method, handlerFunc, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => + AddHandler(method, handlerFunc, options); ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandlers(params IJsonRpcHandler[] handlers) => AddHandlers(handlers); - ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => AddHandler(handlerFunc, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options) => + AddHandler(handlerFunc, options); ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptions options) => AddHandler(handler, options); ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandler(JsonRpcHandlerOptions options) => AddHandler(options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerOptions options) => AddHandler(method, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, JsonRpcHandlerOptions options) => + AddHandler(method, options); ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandler(Type type, JsonRpcHandlerOptions options) => AddHandler(type, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, Type type, JsonRpcHandlerOptions options) => AddHandler(method, type, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.AddHandler(string method, Type type, JsonRpcHandlerOptions options) => + AddHandler(method, type, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnJsonRequest(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions options) => + OnJsonRequest(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnJsonRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnJsonRequest(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnJsonRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnJsonRequest(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry. + OnRequest(string method, Func> handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func> handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => + OnRequest(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnRequest(string method, Func handler, JsonRpcHandlerOptions options) => OnRequest(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnRequest( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnRequest(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnNotification( + string method, Action handler, JsonRpcHandlerOptions options + ) => OnNotification(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions options) => + OnJsonNotification(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnJsonNotification(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Action handler, JsonRpcHandlerOptions options) => OnJsonNotification(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification(string method, Func handler, JsonRpcHandlerOptions options) => + OnJsonNotification(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnJsonNotification( + string method, Action handler, JsonRpcHandlerOptions options + ) => OnJsonNotification(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, JsonRpcHandlerOptions options) => + OnNotification(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnNotification( + string method, Func handler, JsonRpcHandlerOptions options + ) => OnNotification(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry. + OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Action handler, JsonRpcHandlerOptions options) => + OnNotification(method, handler, options); - ILanguageServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + ILanguageServerRegistry IJsonRpcHandlerRegistry. + OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => OnNotification(method, handler, options); + + ILanguageServerRegistry IJsonRpcHandlerRegistry.OnNotification(string method, Func handler, JsonRpcHandlerOptions options) => + OnNotification(method, handler, options); public override IRequestProcessIdentifier RequestProcessIdentifier { get; set; } } diff --git a/src/Server/LanguageServerOptionsExtensions.cs b/src/Server/LanguageServerOptionsExtensions.cs index 583da6f67..7afaa320f 100644 --- a/src/Server/LanguageServerOptionsExtensions.cs +++ b/src/Server/LanguageServerOptionsExtensions.cs @@ -1,17 +1,10 @@ using System; -using System.ComponentModel.DataAnnotations; -using System.IO; -using System.IO.Pipelines; -using System.Reflection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Nerdbank.Streams; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using OmniSharp.Extensions.LanguageServer.Protocol.Shared; using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; namespace OmniSharp.Extensions.LanguageServer.Server @@ -75,7 +68,7 @@ public static LanguageServerOptions ConfigureConfiguration(this LanguageServerOp public static LanguageServerOptions WithConfigurationSection(this LanguageServerOptions options, string sectionName) { - options.Services.AddSingleton(new ConfigurationItem() {Section = sectionName}); + options.Services.AddSingleton(new ConfigurationItem { Section = sectionName }); return options; } diff --git a/src/Server/LanguageServerResolver.cs b/src/Server/LanguageServerResolver.cs index efe1dcd56..975118d9a 100644 --- a/src/Server/LanguageServerResolver.cs +++ b/src/Server/LanguageServerResolver.cs @@ -35,4 +35,4 @@ public void Dispose() foreach (var item in _servers.Values) item.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Server/LanguageServerServiceCollectionExtensions.cs b/src/Server/LanguageServerServiceCollectionExtensions.cs index ba1a0353a..7bb169c16 100644 --- a/src/Server/LanguageServerServiceCollectionExtensions.cs +++ b/src/Server/LanguageServerServiceCollectionExtensions.cs @@ -36,7 +36,7 @@ internal static IContainer AddLanguageServerInternals(this IContainer container, } else { - container.RegisterDelegate(_ => new OnUnhandledExceptionHandler(e => { _.GetRequiredService().ForcefulShutdown(); }), reuse: Reuse.Singleton); + container.RegisterDelegate(_ => new OnUnhandledExceptionHandler(e => { _.GetRequiredService().ForcefulShutdown(); }), Reuse.Singleton); } container.RegisterMany(serviceTypeCondition: type => type.Name.Contains(nameof(TextDocumentLanguageServer)), reuse: Reuse.Singleton); @@ -50,12 +50,13 @@ internal static IContainer AddLanguageServerInternals(this IContainer container, container.RegisterMany( made: Parameters.Of - .Type>(defaultValue: options.ConfigurationBuilderAction), + .Type>(defaultValue: options.ConfigurationBuilderAction), reuse: Reuse.Singleton ); var providedConfiguration = options.Services.FirstOrDefault(z => z.ServiceType == typeof(IConfiguration) && z.ImplementationInstance is IConfiguration); - container.RegisterDelegate(_ => { + container.RegisterDelegate( + _ => { var builder = new ConfigurationBuilder(); var didChangeConfigurationProvider = _.GetRequiredService(); var outerConfiguration = outerServiceProvider?.GetService(); @@ -71,30 +72,31 @@ internal static IContainer AddLanguageServerInternals(this IContainer container, return builder.AddConfiguration(didChangeConfigurationProvider).Build(); }, - reuse: Reuse.Singleton); + Reuse.Singleton + ); container.RegisterMany(serviceTypeCondition: type => type.IsInterface, reuse: Reuse.Singleton); - container.RegisterInstance(options.ServerInfo ?? new ServerInfo() { - Name = Assembly.GetEntryAssembly()?.GetName().Name, - Version = Assembly.GetEntryAssembly()?.GetCustomAttribute() - ?.InformationalVersion ?? - Assembly.GetEntryAssembly()?.GetCustomAttribute()?.Version - }); - - container.RegisterMany(reuse: Reuse.Singleton); - container.RegisterMany(reuse: Reuse.Singleton); - container.RegisterMany(reuse: Reuse.Singleton); - container.RegisterMany(new[] {typeof(ResolveCommandPipeline<,>)}); - container.RegisterMany(reuse: Reuse.Singleton); - container.RegisterMany(reuse: Reuse.Singleton); + container.RegisterInstance( + options.ServerInfo ?? new ServerInfo { + Name = Assembly.GetEntryAssembly()?.GetName().Name, + Version = Assembly.GetEntryAssembly()?.GetCustomAttribute() + ?.InformationalVersion ?? + Assembly.GetEntryAssembly()?.GetCustomAttribute()?.Version + } + ); + + container.RegisterMany(Reuse.Singleton); + container.RegisterMany(Reuse.Singleton); + container.RegisterMany(Reuse.Singleton); + container.RegisterMany(new[] { typeof(ResolveCommandPipeline<,>) }); + container.RegisterMany(Reuse.Singleton); + container.RegisterMany(Reuse.Singleton); return container; } - public static IServiceCollection AddLanguageServer(this IServiceCollection services, Action configureOptions = null) - { - return AddLanguageServer(services, Options.DefaultName, configureOptions); - } + public static IServiceCollection AddLanguageServer(this IServiceCollection services, Action configureOptions = null) => + AddLanguageServer(services, Options.DefaultName, configureOptions); public static IServiceCollection AddLanguageServer(this IServiceCollection services, string name, Action configureOptions = null) { @@ -104,15 +106,19 @@ public static IServiceCollection AddLanguageServer(this IServiceCollection servi { services.RemoveAll(); services.RemoveAll(); - services.AddSingleton(_ => - throw new NotSupportedException("LanguageServer has been registered multiple times, you must use LanguageServer instead")); - services.AddSingleton(_ => - throw new NotSupportedException("LanguageServer has been registered multiple times, you must use LanguageServer instead")); + services.AddSingleton( + _ => + throw new NotSupportedException("LanguageServer has been registered multiple times, you must use LanguageServer instead") + ); + services.AddSingleton( + _ => + throw new NotSupportedException("LanguageServer has been registered multiple times, you must use LanguageServer instead") + ); } services - .AddOptions() - .AddLogging(); + .AddOptions() + .AddLogging(); services.TryAddSingleton(); services.TryAddSingleton(_ => _.GetRequiredService().Get(name)); services.TryAddSingleton(_ => _.GetRequiredService().Get(name)); diff --git a/src/Server/LanguageServerWorkspaceFolderManager.cs b/src/Server/LanguageServerWorkspaceFolderManager.cs index 659272736..9fc41c941 100644 --- a/src/Server/LanguageServerWorkspaceFolderManager.cs +++ b/src/Server/LanguageServerWorkspaceFolderManager.cs @@ -9,21 +9,19 @@ using System.Threading.Tasks; using MediatR; using OmniSharp.Extensions.LanguageServer.Protocol; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server; using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; namespace OmniSharp.Extensions.LanguageServer.Server { - class LanguageServerWorkspaceFolderManager : ILanguageServerWorkspaceFolderManager, IDidChangeWorkspaceFoldersHandler, IOnLanguageServerStarted, IDisposable + internal class LanguageServerWorkspaceFolderManager : ILanguageServerWorkspaceFolderManager, IDidChangeWorkspaceFoldersHandler, IOnLanguageServerStarted, IDisposable { private readonly IWorkspaceLanguageServer _server; private readonly ConcurrentDictionary _workspaceFolders; private readonly ReplaySubject> _workspaceFoldersSubject; private readonly Subject _workspaceFoldersChangedSubject; private readonly object _registrationOptions = new object(); - private bool _isSupported; public LanguageServerWorkspaceFolderManager(IWorkspaceLanguageServer server) { @@ -54,45 +52,50 @@ Task IRequestHandler.Handle(DidChan async Task IOnLanguageServerStarted.OnStarted(ILanguageServer server, CancellationToken cancellationToken) { - _isSupported = server.ClientSettings?.Capabilities?.Workspace?.WorkspaceFolders.IsSupported == true; - if (_isSupported) + IsSupported = server.ClientSettings?.Capabilities?.Workspace?.WorkspaceFolders.IsSupported == true; + if (IsSupported) { await Refresh().LastOrDefaultAsync().ToTask(cancellationToken); } } - public IObservable Refresh() => Observable.Create(observer => { - if (!IsSupported) return Observable.Empty().Subscribe(observer); - return Observable.FromAsync(ct => _server.RequestWorkspaceFolders(new WorkspaceFolderParams(), ct)) - .Do(workspaceFolders => { - var existingFolders = new HashSet(_workspaceFolders.Values.Join(workspaceFolders, z => z.Uri, z => z.Uri, (a, b) => b)); - var additions = new HashSet(); - var removals = new HashSet(); - foreach (var newFolder in workspaceFolders.Except(existingFolders).ToArray()) - { - additions.Add(newFolder); - _workspaceFolders.TryAdd(newFolder.Uri, newFolder); - _workspaceFoldersChangedSubject.OnNext(new WorkspaceFolderChange(WorkspaceFolderEvent.Add, newFolder)); - } + public IObservable Refresh() => Observable.Create( + observer => { + if (!IsSupported) return Observable.Empty().Subscribe(observer); + return Observable.FromAsync(ct => _server.RequestWorkspaceFolders(new WorkspaceFolderParams(), ct)) + .Do( + workspaceFolders => { + var existingFolders = new HashSet(_workspaceFolders.Values.Join(workspaceFolders, z => z.Uri, z => z.Uri, (a, b) => b)); + var additions = new HashSet(); + var removals = new HashSet(); + foreach (var newFolder in workspaceFolders.Except(existingFolders).ToArray()) + { + additions.Add(newFolder); + _workspaceFolders.TryAdd(newFolder.Uri, newFolder); + _workspaceFoldersChangedSubject.OnNext(new WorkspaceFolderChange(WorkspaceFolderEvent.Add, newFolder)); + } - foreach (var oldFolder in _workspaceFolders.Values.Except(workspaceFolders).ToArray()) - { - removals.Add(oldFolder); - _workspaceFolders.TryAdd(oldFolder.Uri, oldFolder); - _workspaceFoldersChangedSubject.OnNext(new WorkspaceFolderChange(WorkspaceFolderEvent.Remove, oldFolder)); - } + foreach (var oldFolder in _workspaceFolders.Values.Except(workspaceFolders).ToArray()) + { + removals.Add(oldFolder); + _workspaceFolders.TryAdd(oldFolder.Uri, oldFolder); + _workspaceFoldersChangedSubject.OnNext(new WorkspaceFolderChange(WorkspaceFolderEvent.Remove, oldFolder)); + } - _workspaceFoldersSubject.OnNext(_workspaceFolders.Values); - }) - .SelectMany(z => _workspaceFolders.Values) - .Subscribe(observer); - }); + _workspaceFoldersSubject.OnNext(_workspaceFolders.Values); + } + ) + .SelectMany(z => _workspaceFolders.Values) + .Subscribe(observer); + } + ); public IObservable Changed => _workspaceFoldersChangedSubject.AsObservable(); public IObservable> WorkspaceFolders => _workspaceFoldersSubject.AsObservable(); public IEnumerable CurrentWorkspaceFolders => _workspaceFolders.Values; - public bool IsSupported => _isSupported; + public bool IsSupported { get; private set; } + public object GetRegistrationOptions() => _registrationOptions; public void Dispose() diff --git a/src/Server/Logging/LanguageServerLogger.cs b/src/Server/Logging/LanguageServerLogger.cs index 9e0900900..523e6614e 100644 --- a/src/Server/Logging/LanguageServerLogger.cs +++ b/src/Server/Logging/LanguageServerLogger.cs @@ -10,7 +10,7 @@ namespace OmniSharp.Extensions.LanguageServer.Server { - class LanguageServerLogger : ILogger + internal class LanguageServerLogger : ILogger { private readonly ILanguageServer _responseRouter; private readonly string _categoryName; @@ -23,32 +23,32 @@ public LanguageServerLogger(ILanguageServer responseRouter, string categoryName, _categoryName = categoryName; } - public IDisposable BeginScope(TState state) - { - return new CompositeDisposable(); - } + public IDisposable BeginScope(TState state) => new CompositeDisposable(); public bool IsEnabled(LogLevel logLevel) => logLevel >= _logLevelGetter(); - 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 + ) { if (logLevel < _logLevelGetter()) return; if (TryGetMessageType(logLevel, out var messageType)) { - _responseRouter.Window.Log(new LogMessageParams() - { - Type = messageType, - Message = _categoryName + ": " + formatter(state, exception) + - (exception != null ? " - " + exception : "") + " | " + - //Hopefully this isn't too expensive in the long run - (state is IEnumerable> dict - ? string.Join(" ", dict.Where(z => z.Key != "{OriginalFormat}").Select(z => $"{z.Key}='{z.Value}'")) - : JsonConvert.SerializeObject(state).Replace("\"", "'") - ) - }); + _responseRouter.Window.Log( + new LogMessageParams { + Type = messageType, + Message = _categoryName + ": " + formatter(state, exception) + + ( exception != null ? " - " + exception : "" ) + " | " + + //Hopefully this isn't too expensive in the long run + ( state is IEnumerable> dict + ? string.Join(" ", dict.Where(z => z.Key != "{OriginalFormat}").Select(z => $"{z.Key}='{z.Value}'")) + : JsonConvert.SerializeObject(state).Replace("\"", "'") + ) + } + ); } } diff --git a/src/Server/Logging/LanguageServerLoggerExtensions.cs b/src/Server/Logging/LanguageServerLoggerExtensions.cs index f87c1188b..88a51ea06 100644 --- a/src/Server/Logging/LanguageServerLoggerExtensions.cs +++ b/src/Server/Logging/LanguageServerLoggerExtensions.cs @@ -8,11 +8,13 @@ public static class LanguageServerLoggerExtensions { public static ILoggingBuilder AddLanguageProtocolLogging(this ILoggingBuilder builder) { - builder.Services.AddSingleton(services => { - var filterOptions = services.GetService>(); + builder.Services.AddSingleton( + services => { + var filterOptions = services.GetService>(); - return new LanguageServerLoggerSettings { MinimumLogLevel = filterOptions.Value.MinLevel }; - }); + return new LanguageServerLoggerSettings { MinimumLogLevel = filterOptions.Value.MinLevel }; + } + ); builder.Services.AddSingleton(); @@ -21,7 +23,7 @@ public static ILoggingBuilder AddLanguageProtocolLogging(this ILoggingBuilder bu public static ILoggingBuilder AddLanguageProtocolLogging(this ILoggingBuilder builder, LogLevel minLevel) { - builder.Services.AddSingleton(_ => new LanguageServerLoggerSettings { MinimumLogLevel = minLevel }); + builder.Services.AddSingleton(_ => new LanguageServerLoggerSettings { MinimumLogLevel = minLevel }); builder.Services.AddSingleton(); return builder; diff --git a/src/Server/Logging/LanguageServerLoggerFilterOptions.cs b/src/Server/Logging/LanguageServerLoggerFilterOptions.cs index 141d8227d..f431a914b 100644 --- a/src/Server/Logging/LanguageServerLoggerFilterOptions.cs +++ b/src/Server/Logging/LanguageServerLoggerFilterOptions.cs @@ -10,10 +10,7 @@ internal class LanguageServerLoggerFilterOptions : IOptionsMonitor _registrations = new List(); private event Action _onChange; - public LanguageServerLoggerFilterOptions(IOptions options) - { - CurrentValue = options.Value; - } + public LanguageServerLoggerFilterOptions(IOptions options) => CurrentValue = options.Value; public LoggerFilterOptions CurrentValue { get; private set; } diff --git a/src/Server/Logging/LanguageServerLoggerProvider.cs b/src/Server/Logging/LanguageServerLoggerProvider.cs index 8fc9479a1..e12ea1bd2 100644 --- a/src/Server/Logging/LanguageServerLoggerProvider.cs +++ b/src/Server/Logging/LanguageServerLoggerProvider.cs @@ -3,7 +3,7 @@ namespace OmniSharp.Extensions.LanguageServer.Server { - class LanguageServerLoggerProvider : ILoggerProvider + internal class LanguageServerLoggerProvider : ILoggerProvider { private readonly ILanguageServer _languageServer; private readonly LanguageServerLoggerSettings _settings; @@ -14,10 +14,7 @@ public LanguageServerLoggerProvider(ILanguageServer languageServer, LanguageServ _settings = settings; } - public ILogger CreateLogger(string categoryName) - { - return new LanguageServerLogger(_languageServer, categoryName, () => _settings.MinimumLogLevel); - } + public ILogger CreateLogger(string categoryName) => new LanguageServerLogger(_languageServer, categoryName, () => _settings.MinimumLogLevel); public void Dispose() { diff --git a/src/Server/LspServerReceiver.cs b/src/Server/LspServerReceiver.cs index a2bc392df..25a218706 100644 --- a/src/Server/LspServerReceiver.cs +++ b/src/Server/LspServerReceiver.cs @@ -42,20 +42,17 @@ public override (IEnumerable results, bool hasResponse) GetRequests(JToke } } - return (newResults, hasResponse); + return ( newResults, hasResponse ); } - public void Initialized() - { - _initialized = true; - } + public void Initialized() => _initialized = true; public override bool ShouldFilterOutput(object value) { if (_initialized) return true; return value is OutgoingResponse || - (value is OutgoingNotification n && (n.Params is LogMessageParams || n.Params is ShowMessageParams || n.Params is TelemetryEventParams)) || - (value is OutgoingRequest r && r.Params is ShowMessageRequestParams); + value is OutgoingNotification n && ( n.Params is LogMessageParams || n.Params is ShowMessageParams || n.Params is TelemetryEventParams ) || + value is OutgoingRequest r && r.Params is ShowMessageRequestParams; } } } diff --git a/src/Server/Matchers/ExecuteCommandMatcher.cs b/src/Server/Matchers/ExecuteCommandMatcher.cs index 958e58731..6a94bcb9c 100644 --- a/src/Server/Matchers/ExecuteCommandMatcher.cs +++ b/src/Server/Matchers/ExecuteCommandMatcher.cs @@ -11,10 +11,7 @@ public class ExecuteCommandMatcher : IHandlerMatcher { private readonly ILogger _logger; - public ExecuteCommandMatcher(ILogger logger) - { - _logger = logger; - } + public ExecuteCommandMatcher(ILogger logger) => _logger = logger; /// /// Finds the first handler that matches the parameters. @@ -29,11 +26,14 @@ public IEnumerable FindHandler(object parameters, IEnumer _logger.LogTrace("Registration options {OptionsName}", executeCommandParams.GetType().FullName); foreach (var descriptor in descriptors) { - if (descriptor.RegistrationOptions is ExecuteCommandRegistrationOptions registrationOptions && registrationOptions.Commands.Any(x => x == executeCommandParams.Command)) + if (descriptor.RegistrationOptions is ExecuteCommandRegistrationOptions registrationOptions + && registrationOptions.Commands.Any(x => x == executeCommandParams.Command)) { - _logger.LogTrace("Checking handler {Method}:{Handler}", + _logger.LogTrace( + "Checking handler {Method}:{Handler}", executeCommandParams.Command, - executeCommandParams.GetType().FullName); + executeCommandParams.GetType().FullName + ); yield return descriptor; } } diff --git a/src/Server/Matchers/ResolveCommandMatcher.cs b/src/Server/Matchers/ResolveCommandMatcher.cs index 960afa6a5..188bc63a9 100644 --- a/src/Server/Matchers/ResolveCommandMatcher.cs +++ b/src/Server/Matchers/ResolveCommandMatcher.cs @@ -1,8 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using MediatR; using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Protocol; @@ -16,10 +13,7 @@ public class ResolveCommandMatcher : IHandlerMatcher { private readonly ILogger _logger; - public ResolveCommandMatcher(ILogger logger) - { - _logger = logger; - } + public ResolveCommandMatcher(ILogger logger) => _logger = logger; /// /// Finds the first handler that matches the parameters. diff --git a/src/Server/Matchers/TextDocumentMatcher.cs b/src/Server/Matchers/TextDocumentMatcher.cs index 41745e805..27352117e 100644 --- a/src/Server/Matchers/TextDocumentMatcher.cs +++ b/src/Server/Matchers/TextDocumentMatcher.cs @@ -9,7 +9,7 @@ namespace OmniSharp.Extensions.LanguageServer.Server.Matchers { - class TextDocumentMatcher : IHandlerMatcher + internal class TextDocumentMatcher : IHandlerMatcher { private readonly ILogger _logger; private readonly TextDocumentIdentifiers _textDocumentIdentifiers; @@ -17,7 +17,8 @@ class TextDocumentMatcher : IHandlerMatcher public TextDocumentMatcher(ILogger logger, TextDocumentIdentifiers textDocumentIdentifiers) { _logger = logger; - _textDocumentIdentifiers = textDocumentIdentifiers; ; + _textDocumentIdentifiers = textDocumentIdentifiers; + ; } public IEnumerable FindHandler(object parameters, IEnumerable descriptors) @@ -25,50 +26,46 @@ public IEnumerable FindHandler(object parameters, IEnumer switch (parameters) { case ITextDocumentIdentifierParams textDocumentIdentifierParams: - { - if (textDocumentIdentifierParams.TextDocument?.Uri == null) break; - var attributes = GetTextDocumentAttributes(textDocumentIdentifierParams.TextDocument.Uri); + { + if (textDocumentIdentifierParams.TextDocument?.Uri == null) break; + var attributes = GetTextDocumentAttributes(textDocumentIdentifierParams.TextDocument.Uri); - _logger.LogTrace("Found attributes {Count}, {Attributes}", attributes.Count, attributes.Select(x => $"{x.LanguageId}:{x.Scheme}:{x.Uri}")); + _logger.LogTrace("Found attributes {Count}, {Attributes}", attributes.Count, attributes.Select(x => $"{x.LanguageId}:{x.Scheme}:{x.Uri}")); - return GetHandler(descriptors, attributes); - } + return GetHandler(descriptors, attributes); + } case DidOpenTextDocumentParams openTextDocumentParams: - { - if (openTextDocumentParams.TextDocument?.Uri == null) break; - var attributes = new TextDocumentAttributes(openTextDocumentParams.TextDocument.Uri, openTextDocumentParams.TextDocument.LanguageId); + { + if (openTextDocumentParams.TextDocument?.Uri == null) break; + var attributes = new TextDocumentAttributes(openTextDocumentParams.TextDocument.Uri, openTextDocumentParams.TextDocument.LanguageId); - _logger.LogTrace("Created attribute {Attribute}", $"{attributes.LanguageId}:{attributes.Scheme}:{attributes.Uri}"); + _logger.LogTrace("Created attribute {Attribute}", $"{attributes.LanguageId}:{attributes.Scheme}:{attributes.Uri}"); - return GetHandler(descriptors, attributes); - } + return GetHandler(descriptors, attributes); + } case DidChangeTextDocumentParams didChangeDocumentParams: - { - if (didChangeDocumentParams.TextDocument?.Uri == null) break; - // TODO: Do something with document version here? - var attributes = GetTextDocumentAttributes(didChangeDocumentParams.TextDocument.Uri); + { + if (didChangeDocumentParams.TextDocument?.Uri == null) break; + // TODO: Do something with document version here? + var attributes = GetTextDocumentAttributes(didChangeDocumentParams.TextDocument.Uri); - _logger.LogTrace("Found attributes {Count}, {Attributes}", attributes.Count, attributes.Select(x => $"{x.LanguageId}:{x.Scheme}:{x.Uri}")); + _logger.LogTrace("Found attributes {Count}, {Attributes}", attributes.Count, attributes.Select(x => $"{x.LanguageId}:{x.Scheme}:{x.Uri}")); - return GetHandler(descriptors, attributes); - } + return GetHandler(descriptors, attributes); + } } return Enumerable.Empty(); } - private List GetTextDocumentAttributes(DocumentUri uri) - { - return _textDocumentIdentifiers - .Select(x => x.GetTextDocumentAttributes(uri)) - .Where(x => x != null) - .ToList(); - } + private List GetTextDocumentAttributes(DocumentUri uri) => + _textDocumentIdentifiers + .Select(x => x.GetTextDocumentAttributes(uri)) + .Where(x => x != null) + .ToList(); - private IEnumerable GetHandler(IEnumerable descriptors, IEnumerable attributes) - { - return attributes.SelectMany(z => GetHandler(descriptors, z)).Distinct(); - } + private IEnumerable GetHandler(IEnumerable descriptors, IEnumerable attributes) => + attributes.SelectMany(z => GetHandler(descriptors, z)).Distinct(); private IEnumerable GetHandler(IEnumerable descriptors, TextDocumentAttributes attributes) { @@ -83,7 +80,10 @@ private IEnumerable GetHandler(IEnumerable Handle(TRequest request, CancellationToken cancella _logger.LogTrace( "Updating Resolve items with wrapped data for {Method}:{Handler}", _descriptor.Method, - _descriptor.ImplementationType.FullName); + _descriptor.ImplementationType.FullName + ); foreach (var item in canBeResolvedItems) { item.Data ??= new JObject(); diff --git a/src/Shared/HandlerCollectionExtensions.cs b/src/Shared/HandlerCollectionExtensions.cs index 05db1752a..7b9bc6492 100644 --- a/src/Shared/HandlerCollectionExtensions.cs +++ b/src/Shared/HandlerCollectionExtensions.cs @@ -7,36 +7,18 @@ namespace OmniSharp.Extensions.LanguageServer.Shared { - static class HandlerCollectionExtensions + internal static class HandlerCollectionExtensions { - public static LspHandlerDescriptorDisposable Add(this IHandlerCollection collection, IEnumerable handlers) - { - return collection.Add(handlers.ToArray()); - } + public static LspHandlerDescriptorDisposable Add(this IHandlerCollection collection, IEnumerable handlers) => collection.Add(handlers.ToArray()); - public static LspHandlerDescriptorDisposable Add(this IHandlerCollection collection, IEnumerable handlerTypes) - { - return collection.Add(handlerTypes.ToArray()); - } + public static LspHandlerDescriptorDisposable Add(this IHandlerCollection collection, IEnumerable handlerTypes) => collection.Add(handlerTypes.ToArray()); - public static LspHandlerDescriptorDisposable Add(this ILanguageServer collection, IEnumerable handlers) - { - return collection.Add(handlers.ToArray()); - } + public static LspHandlerDescriptorDisposable Add(this ILanguageServer collection, IEnumerable handlers) => collection.Add(handlers.ToArray()); - public static LspHandlerDescriptorDisposable Add(this ILanguageServer collection, IEnumerable handlerTypes) - { - return collection.Add(handlerTypes.ToArray()); - } + public static LspHandlerDescriptorDisposable Add(this ILanguageServer collection, IEnumerable handlerTypes) => collection.Add(handlerTypes.ToArray()); - public static LspHandlerDescriptorDisposable Add(this ILanguageClient collection, IEnumerable handlers) - { - return collection.Add(handlers.ToArray()); - } + public static LspHandlerDescriptorDisposable Add(this ILanguageClient collection, IEnumerable handlers) => collection.Add(handlers.ToArray()); - public static LspHandlerDescriptorDisposable Add(this ILanguageClient collection, IEnumerable handlerTypes) - { - return collection.Add(handlerTypes.ToArray()); - } + public static LspHandlerDescriptorDisposable Add(this ILanguageClient collection, IEnumerable handlerTypes) => collection.Add(handlerTypes.ToArray()); } } diff --git a/src/Shared/InterimLanguageProtocolRegistry.cs b/src/Shared/InterimLanguageProtocolRegistry.cs index 619be372a..f2db35ddb 100644 --- a/src/Shared/InterimLanguageProtocolRegistry.cs +++ b/src/Shared/InterimLanguageProtocolRegistry.cs @@ -5,25 +5,22 @@ namespace OmniSharp.Extensions.LanguageServer.Shared { - class InterimLanguageProtocolRegistry : InterimJsonRpcServerRegistry where T : IJsonRpcHandlerRegistry + internal class InterimLanguageProtocolRegistry : InterimJsonRpcServerRegistry where T : IJsonRpcHandlerRegistry { private readonly IServiceProvider _serviceProvider; private readonly TextDocumentIdentifiers _textDocumentIdentifiers; - public InterimLanguageProtocolRegistry(IServiceProvider serviceProvider, CompositeHandlersManager handlersManager, TextDocumentIdentifiers textDocumentIdentifiers) : base(handlersManager) + public InterimLanguageProtocolRegistry(IServiceProvider serviceProvider, CompositeHandlersManager handlersManager, TextDocumentIdentifiers textDocumentIdentifiers) : base( + handlersManager + ) { _serviceProvider = serviceProvider; _textDocumentIdentifiers = textDocumentIdentifiers; } - public IDisposable AddTextDocumentIdentifier(params ITextDocumentIdentifier[] identifiers) - { - return _textDocumentIdentifiers.Add(identifiers); - } + public IDisposable AddTextDocumentIdentifier(params ITextDocumentIdentifier[] identifiers) => _textDocumentIdentifiers.Add(identifiers); - public IDisposable AddTextDocumentIdentifier() where TTextDocumentIdentifier : ITextDocumentIdentifier - { - return _textDocumentIdentifiers.Add(ActivatorUtilities.CreateInstance(_serviceProvider)); - } + public IDisposable AddTextDocumentIdentifier() where TTextDocumentIdentifier : ITextDocumentIdentifier => + _textDocumentIdentifiers.Add(ActivatorUtilities.CreateInstance(_serviceProvider)); } } diff --git a/src/Shared/LanguageProtocolServiceCollectionExtensions.cs b/src/Shared/LanguageProtocolServiceCollectionExtensions.cs index 2cd3c8a47..c3d1b301f 100644 --- a/src/Shared/LanguageProtocolServiceCollectionExtensions.cs +++ b/src/Shared/LanguageProtocolServiceCollectionExtensions.cs @@ -1,14 +1,11 @@ using System; -using System.Collections.Generic; using System.Linq; using DryIoc; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; -using OmniSharp.Extensions.LanguageServer.Protocol.Shared; namespace OmniSharp.Extensions.LanguageServer.Shared { @@ -16,9 +13,9 @@ internal static class LanguageProtocolServiceCollectionExtensions { internal static IContainer AddLanguageProtocolInternals(this IContainer container, LanguageProtocolRpcOptionsBase options) where T : IJsonRpcHandlerRegistry { - options.RequestProcessIdentifier ??= (options.SupportsContentModified + options.RequestProcessIdentifier ??= options.SupportsContentModified ? new RequestProcessIdentifier(RequestProcessType.Parallel) - : new RequestProcessIdentifier(RequestProcessType.Serial)); + : new RequestProcessIdentifier(); if (options.Serializer == null) { @@ -31,19 +28,19 @@ internal static IContainer AddLanguageProtocolInternals(this IContainer conta container.RegisterInstance(options.RequestProcessIdentifier); container.RegisterMany(nonPublicServiceTypes: true, reuse: Reuse.Singleton); - container.RegisterMany(reuse: Reuse.Singleton); - container.Register(reuse: Reuse.Singleton); - container.RegisterInitializer((identifiers, context) => { - identifiers.Add(context.GetServices().ToArray()); - }); - container.RegisterMany(reuse: Reuse.Singleton); + container.RegisterMany(Reuse.Singleton); + container.Register(Reuse.Singleton); + container.RegisterInitializer((identifiers, context) => { identifiers.Add(context.GetServices().ToArray()); }); + container.RegisterMany(Reuse.Singleton); container.RegisterMany(nonPublicServiceTypes: true, reuse: Reuse.Singleton); - container.RegisterInitializer((manager, context) => { - var descriptions = context.Resolve(); - descriptions.Populate(context, manager); - }); - container.RegisterMany(reuse: Reuse.Singleton); - container.RegisterMany(reuse: Reuse.Singleton); + container.RegisterInitializer( + (manager, context) => { + var descriptions = context.Resolve(); + descriptions.Populate(context, manager); + } + ); + container.RegisterMany(Reuse.Singleton); + container.RegisterMany(Reuse.Singleton); return container; } diff --git a/src/Shared/LspHandlerDescriptorDisposable.cs b/src/Shared/LspHandlerDescriptorDisposable.cs index f284b835a..fc058c510 100644 --- a/src/Shared/LspHandlerDescriptorDisposable.cs +++ b/src/Shared/LspHandlerDescriptorDisposable.cs @@ -4,23 +4,22 @@ namespace OmniSharp.Extensions.LanguageServer.Shared { - class LspHandlerDescriptorDisposable : IDisposable + internal class LspHandlerDescriptorDisposable : IDisposable { - private readonly IEnumerable _instances; private readonly IDisposable _disposable; public LspHandlerDescriptorDisposable(IEnumerable instances, IDisposable disposable) { - _instances = instances; + Descriptors = instances; _disposable = disposable; } - public IEnumerable Descriptors => _instances; + public IEnumerable Descriptors { get; } public void Dispose() { _disposable.Dispose(); - foreach (var instance in _instances) + foreach (var instance in Descriptors) if (instance is IDisposable disposable) disposable.Dispose(); } diff --git a/src/Shared/LspHandlerDescriptorHelpers.cs b/src/Shared/LspHandlerDescriptorHelpers.cs index 17166b641..201eaaa53 100644 --- a/src/Shared/LspHandlerDescriptorHelpers.cs +++ b/src/Shared/LspHandlerDescriptorHelpers.cs @@ -8,7 +8,7 @@ namespace OmniSharp.Extensions.LanguageServer.Shared { - static class LspHandlerDescriptorHelpers + internal static class LspHandlerDescriptorHelpers { public static IJsonRpcHandler InitializeHandler(ILspHandlerDescriptor descriptor, ISupportedCapabilities supportedCapabilities, IJsonRpcHandler handler) { @@ -16,27 +16,23 @@ public static IJsonRpcHandler InitializeHandler(ILspHandlerDescriptor descriptor return handler; } - public static IEnumerable GetSupportedCapabilities(object capabilities) - { - return capabilities - .GetType() - .GetTypeInfo() - .DeclaredProperties - .Where(x => x.CanRead) - .Select(x => x.GetValue(capabilities)) - .OfType(); - } + public static IEnumerable GetSupportedCapabilities(object capabilities) => + capabilities + .GetType() + .GetTypeInfo() + .DeclaredProperties + .Where(x => x.CanRead) + .Select(x => x.GetValue(capabilities)) + .OfType(); - public static IEnumerable GetStaticRegistrationOptions(object capabilities) - { - return capabilities - .GetType() - .GetTypeInfo() - .DeclaredProperties - .Where(x => x.CanRead) - .Select(x => x.GetValue(capabilities)) - .Select(z => z is ISupports supports ? supports.IsSupported ? supports.Value : z : z) - .OfType(); - } + public static IEnumerable GetStaticRegistrationOptions(object capabilities) => + capabilities + .GetType() + .GetTypeInfo() + .DeclaredProperties + .Where(x => x.CanRead) + .Select(x => x.GetValue(capabilities)) + .Select(z => z is ISupports supports ? supports.IsSupported ? supports.Value : z : z) + .OfType(); } } diff --git a/src/Shared/LspRequestRouter.cs b/src/Shared/LspRequestRouter.cs index 58a409c2a..28347f113 100644 --- a/src/Shared/LspRequestRouter.cs +++ b/src/Shared/LspRequestRouter.cs @@ -24,27 +24,19 @@ public LspRequestRouter( ILogger logger, IEnumerable handlerMatchers, ISerializer serializer, - IServiceScopeFactory serviceScopeFactory) : + IServiceScopeFactory serviceScopeFactory + ) : base(serializer, serviceScopeFactory, logger) { _collection = collection; _handlerMatchers = new HashSet(handlerMatchers); } - public override IRequestDescriptor GetDescriptors(Notification notification) - { - return FindDescriptor(notification); - } + public override IRequestDescriptor GetDescriptors(Notification notification) => FindDescriptor(notification); - public override IRequestDescriptor GetDescriptors(Request request) - { - return FindDescriptor(request); - } + public override IRequestDescriptor GetDescriptors(Request request) => FindDescriptor(request); - private IRequestDescriptor FindDescriptor(IMethodWithParams instance) - { - return FindDescriptor(instance.Method, instance.Params); - } + private IRequestDescriptor FindDescriptor(IMethodWithParams instance) => FindDescriptor(instance.Method, instance.Params); private IRequestDescriptor FindDescriptor(string method, JToken @params) { @@ -52,18 +44,20 @@ private IRequestDescriptor FindDescriptor(string method, var descriptor = _collection.FirstOrDefault(x => x.Method == method); if (descriptor is null) { - _logger.LogDebug("Unable to find {Method}, methods found include {Methods}", method, - string.Join(", ", _collection.Select(x => x.Method + ":" + x.Handler?.GetType()?.FullName))); + _logger.LogDebug( + "Unable to find {Method}, methods found include {Methods}", method, + string.Join(", ", _collection.Select(x => x.Method + ":" + x.Handler?.GetType()?.FullName)) + ); return new RequestDescriptor(); } - if (@params == null || descriptor.Params == null) return new RequestDescriptor(new[] { descriptor }); + if (@params == null || descriptor.Params == null) return new RequestDescriptor(descriptor); object paramsValue = null; if (descriptor.IsDelegatingHandler) { var o = @params?.ToObject(descriptor.Params.GetGenericArguments()[0], _serializer.JsonSerializer); - paramsValue = Activator.CreateInstance(descriptor.Params, new object[] { o }); + paramsValue = Activator.CreateInstance(descriptor.Params, o); } else { @@ -87,14 +81,20 @@ private IRequestDescriptor FindDescriptor(string method, Task IRequestRouter.RouteNotification(IRequestDescriptor descriptors, Notification notification, CancellationToken token) => RouteNotification( - descriptors is IRequestDescriptor d ? d : throw new Exception("This should really never happen, seriously, only hand this correct descriptors"), + descriptors is IRequestDescriptor d + ? d + : throw new Exception("This should really never happen, seriously, only hand this correct descriptors"), notification, - token); + token + ); Task IRequestRouter.RouteRequest(IRequestDescriptor descriptors, Request request, CancellationToken token) => RouteRequest( - descriptors is IRequestDescriptor d ? d : throw new Exception("This should really never happen, seriously, only hand this correct descriptors"), + descriptors is IRequestDescriptor d + ? d + : throw new Exception("This should really never happen, seriously, only hand this correct descriptors"), request, - token); + token + ); } } diff --git a/src/Shared/RequestProcessIdentifier.cs b/src/Shared/RequestProcessIdentifier.cs index b6bc40ff4..5319dab35 100644 --- a/src/Shared/RequestProcessIdentifier.cs +++ b/src/Shared/RequestProcessIdentifier.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Concurrent; using System.Linq; -using System.Reflection; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.LanguageServer.Shared @@ -13,10 +12,7 @@ public class RequestProcessIdentifier : IRequestProcessIdentifier private readonly RequestProcessType _defaultRequestProcessType; - public RequestProcessIdentifier(RequestProcessType defaultRequestProcessType = RequestProcessType.Serial) - { - _defaultRequestProcessType = defaultRequestProcessType; - } + public RequestProcessIdentifier(RequestProcessType defaultRequestProcessType = RequestProcessType.Serial) => _defaultRequestProcessType = defaultRequestProcessType; public RequestProcessType Identify(IHandlerDescriptor descriptor) { @@ -36,10 +32,10 @@ public RequestProcessType Identify(IHandlerDescriptor descriptor) else { var processAttribute = descriptor.ImplementationType - .GetCustomAttributes(true) - .Concat(descriptor.HandlerType.GetCustomAttributes(true)) - .OfType() - .FirstOrDefault(); + .GetCustomAttributes(true) + .Concat(descriptor.HandlerType.GetCustomAttributes(true)) + .OfType() + .FirstOrDefault(); if (processAttribute != null) { type = processAttribute.Type; diff --git a/src/Shared/SharedHandlerCollection.cs b/src/Shared/SharedHandlerCollection.cs index 13e8d7f54..0f3adc81b 100644 --- a/src/Shared/SharedHandlerCollection.cs +++ b/src/Shared/SharedHandlerCollection.cs @@ -9,19 +9,17 @@ using Microsoft.Extensions.DependencyInjection; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol; -using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; namespace OmniSharp.Extensions.LanguageServer.Shared { - class SharedHandlerCollection : IHandlerCollection + internal class SharedHandlerCollection : IHandlerCollection { private static readonly MethodInfo GetRegistrationMethod = typeof(SharedHandlerCollection) - .GetTypeInfo() - .GetMethod(nameof(GetRegistration), BindingFlags.NonPublic | BindingFlags.Static); + .GetTypeInfo() + .GetMethod(nameof(GetRegistration), BindingFlags.NonPublic | BindingFlags.Static); private readonly ISupportedCapabilities _supportedCapabilities; private readonly TextDocumentIdentifiers _textDocumentIdentifiers; @@ -35,15 +33,9 @@ public SharedHandlerCollection(ISupportedCapabilities supportedCapabilities, Tex _serviceProvider = serviceProvider; } - public IEnumerator GetEnumerator() - { - return _descriptors.GetEnumerator(); - } + public IEnumerator GetEnumerator() => _descriptors.GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); IEnumerable IHandlersManager.Descriptors => _descriptors; @@ -70,11 +62,12 @@ IDisposable IHandlersManager.AddLink(string sourceMethod, string destinationMeth destinationMethod, source.HandlerType, source.Handler, - source.RequestProcessType.HasValue ? new JsonRpcHandlerOptions() {RequestProcessType = source.RequestProcessType.Value} : null, + source.RequestProcessType.HasValue ? new JsonRpcHandlerOptions { RequestProcessType = source.RequestProcessType.Value } : null, source.TypeDescriptor, source.HandlerType, source.RegistrationType, - source.CapabilityType); + source.CapabilityType + ); Interlocked.Exchange(ref _descriptors, _descriptors.Add(descriptor)); var cd = new CompositeDisposable(); if (descriptor.Handler is ITextDocumentIdentifier textDocumentIdentifier) @@ -82,7 +75,7 @@ IDisposable IHandlersManager.AddLink(string sourceMethod, string destinationMeth cd.Add(_textDocumentIdentifiers.Add(textDocumentIdentifier)); } - return new LspHandlerDescriptorDisposable(new[] {descriptor}, cd); + return new LspHandlerDescriptorDisposable(new[] { descriptor }, cd); } @@ -164,21 +157,17 @@ public LspHandlerDescriptorDisposable Add(string method, Type handlerType, JsonR return new LspHandlerDescriptorDisposable(descriptors, cd); } - class EqualityComparer : IEqualityComparer<(string method, Type implementedInterface)> + private class EqualityComparer : IEqualityComparer<(string method, Type implementedInterface)> { - public bool Equals((string method, Type implementedInterface) x, (string method, Type implementedInterface) y) - { - return x.method?.Equals(y.method) == true; - } + public bool Equals((string method, Type implementedInterface) x, (string method, Type implementedInterface) y) => x.method?.Equals(y.method) == true; - public int GetHashCode((string method, Type implementedInterface) obj) - { - return obj.method?.GetHashCode() ?? 0; - } + public int GetHashCode((string method, Type implementedInterface) obj) => obj.method?.GetHashCode() ?? 0; } - private (HashSet descriptors, CompositeDisposable compositeDisposable) AddHandler(string method, IJsonRpcHandler handler, - JsonRpcHandlerOptions options) + private (HashSet descriptors, CompositeDisposable compositeDisposable) AddHandler( + string method, IJsonRpcHandler handler, + JsonRpcHandlerOptions options + ) { var descriptors = new HashSet(); var cd = new CompositeDisposable(); @@ -190,7 +179,7 @@ public int GetHashCode((string method, Type implementedInterface) obj) cd.Add(_textDocumentIdentifiers.Add(textDocumentIdentifier)); } - return (descriptors, cd); + return ( descriptors, cd ); } private (HashSet descriptors, CompositeDisposable compositeDisposable) AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptions options) @@ -198,10 +187,10 @@ public int GetHashCode((string method, Type implementedInterface) obj) var descriptors = new HashSet(); var cd = new CompositeDisposable(); foreach (var (method, implementedInterface) in handler.GetType().GetTypeInfo() - .ImplementedInterfaces - .Select(x => (method: HandlerTypeDescriptorHelper.GetMethodName(x), implementedInterface: x)) - .Distinct(new EqualityComparer()) - .Where(x => !string.IsNullOrWhiteSpace(x.method)) + .ImplementedInterfaces + .Select(x => ( method: HandlerTypeDescriptorHelper.GetMethodName(x), implementedInterface: x )) + .Distinct(new EqualityComparer()) + .Where(x => !string.IsNullOrWhiteSpace(x.method)) ) { var descriptor = GetDescriptor(method, implementedInterface, handler, options); @@ -213,17 +202,16 @@ public int GetHashCode((string method, Type implementedInterface) obj) } } - return (descriptors, cd); + return ( descriptors, cd ); } - private LspHandlerDescriptor GetDescriptor(string method, Type handlerType, IServiceProvider serviceProvider, JsonRpcHandlerOptions options) - { - return GetDescriptor( + private LspHandlerDescriptor GetDescriptor(string method, Type handlerType, IServiceProvider serviceProvider, JsonRpcHandlerOptions options) => + GetDescriptor( method, handlerType, ActivatorUtilities.CreateInstance(serviceProvider, handlerType) as IJsonRpcHandler, - options); - } + options + ); private LspHandlerDescriptor GetDescriptor(string method, Type handlerType, IJsonRpcHandler handler, JsonRpcHandlerOptions options) { @@ -237,9 +225,11 @@ private LspHandlerDescriptor GetDescriptor(string method, Type handlerType, IJso return GetDescriptor(method, handlerType, handler, options, typeDescriptor, @interface, registrationType, capabilityType); } - private LspHandlerDescriptor GetDescriptor(string method, Type handlerType, IJsonRpcHandler handler, JsonRpcHandlerOptions options, + private LspHandlerDescriptor GetDescriptor( + string method, Type handlerType, IJsonRpcHandler handler, JsonRpcHandlerOptions options, ILspHandlerTypeDescriptor typeDescriptor, - Type @interface, Type registrationType, Type capabilityType) + Type @interface, Type registrationType, Type capabilityType + ) { Type @params = null; object registrationOptions = null; @@ -251,8 +241,8 @@ private LspHandlerDescriptor GetDescriptor(string method, Type handlerType, IJso if (registrationType != null) { registrationOptions = GetRegistrationMethod - .MakeGenericMethod(registrationType) - .Invoke(null, new object[] {handler}); + .MakeGenericMethod(registrationType) + .Invoke(null, new object[] { handler }); } var key = "default"; @@ -288,9 +278,9 @@ private LspHandlerDescriptor GetDescriptor(string method, Type handlerType, IJso options?.RequestProcessType ?? typeDescriptor?.RequestProcessType ?? handlerType.GetCustomAttributes(true) - .Concat(@interface.GetCustomAttributes(true)) - .OfType() - .FirstOrDefault()?.Type; + .Concat(@interface.GetCustomAttributes(true)) + .OfType() + .FirstOrDefault()?.Type; var descriptor = new LspHandlerDescriptor( method, @@ -300,7 +290,7 @@ private LspHandlerDescriptor GetDescriptor(string method, Type handlerType, IJso @params, registrationType, registrationOptions, - (registrationType == null ? (Func) (() => false) : (() => _supportedCapabilities.AllowsDynamicRegistration(capabilityType))), + registrationType == null ? (Func) ( () => false ) : () => _supportedCapabilities.AllowsDynamicRegistration(capabilityType), capabilityType, requestProcessType, () => { @@ -313,25 +303,19 @@ private LspHandlerDescriptor GetDescriptor(string method, Type handlerType, IJso Interlocked.Exchange(ref _descriptors, descriptors.ToImmutable()); }, - typeDescriptor); + typeDescriptor + ); return descriptor; } - public bool ContainsHandler(Type type) - { - return ContainsHandler(type.GetTypeInfo()); - } + public bool ContainsHandler(Type type) => ContainsHandler(type.GetTypeInfo()); - public bool ContainsHandler(TypeInfo typeInfo) - { - return _descriptors.Any(z => z.HandlerType.GetTypeInfo().IsAssignableFrom(typeInfo) || z.ImplementationType.GetTypeInfo().IsAssignableFrom(typeInfo)); - } + public bool ContainsHandler(TypeInfo typeInfo) => + _descriptors.Any(z => z.HandlerType.GetTypeInfo().IsAssignableFrom(typeInfo) || z.ImplementationType.GetTypeInfo().IsAssignableFrom(typeInfo)); private static object GetRegistration(IRegistration registration) - where T : class, new() - { - return registration.GetRegistrationOptions() ?? new T(); - } + where T : class, new() => + registration.GetRegistrationOptions() ?? new T(); } } diff --git a/src/Shared/SupportedCapabilities.cs b/src/Shared/SupportedCapabilities.cs index 1712f4f43..9bbd4c92c 100644 --- a/src/Shared/SupportedCapabilities.cs +++ b/src/Shared/SupportedCapabilities.cs @@ -8,16 +8,13 @@ namespace OmniSharp.Extensions.LanguageServer.Shared { - class SupportedCapabilities : ISupportedCapabilities + internal class SupportedCapabilities : ISupportedCapabilities { private static readonly MethodInfo SetCapabilityInnerMethod = typeof(SupportedCapabilities) - .GetTypeInfo() - .GetMethod(nameof(SetCapabilityInner), BindingFlags.NonPublic | BindingFlags.Static); + .GetTypeInfo() + .GetMethod(nameof(SetCapabilityInner), BindingFlags.NonPublic | BindingFlags.Static); private readonly IDictionary _supports = new Dictionary(); - public SupportedCapabilities() - { - } public void Add(IEnumerable supports) { @@ -36,25 +33,23 @@ public bool AllowsDynamicRegistration(Type capabilityType) if (capability is IDynamicCapability dc) return dc.DynamicRegistration; } + return false; } public void SetCapability(ILspHandlerDescriptor descriptor, IJsonRpcHandler handler) { if (!descriptor.HasCapability) return; - if (descriptor.CapabilityType == null ||!typeof(ICapability<>).MakeGenericType(descriptor.CapabilityType).IsInstanceOfType(handler)) return; + if (descriptor.CapabilityType == null || !typeof(ICapability<>).MakeGenericType(descriptor.CapabilityType).IsInstanceOfType(handler)) return; if (_supports.TryGetValue(descriptor.CapabilityType, out var capability)) { SetCapabilityInnerMethod - .MakeGenericMethod(descriptor.CapabilityType) - .Invoke(null, new[] { handler, capability }); + .MakeGenericMethod(descriptor.CapabilityType) + .Invoke(null, new[] { handler, capability }); } } - private static void SetCapabilityInner(ICapability capability, T instance) - { - capability.SetCapability(instance); - } + private static void SetCapabilityInner(ICapability capability, T instance) => capability.SetCapability(instance); } } diff --git a/src/Testing/ClientCapabilityExtensions.cs b/src/Testing/ClientCapabilityExtensions.cs index a2c1e5749..aecd2274e 100644 --- a/src/Testing/ClientCapabilityExtensions.cs +++ b/src/Testing/ClientCapabilityExtensions.cs @@ -8,18 +8,20 @@ namespace OmniSharp.Extensions.LanguageProtocol.Testing { public static class ClientCapabilityExtensions { - public static LanguageClientOptions EnableAllCapabilities( this LanguageClientOptions options) + public static LanguageClientOptions EnableAllCapabilities(this LanguageClientOptions options) { var capabilities = typeof(ICapability).Assembly.GetExportedTypes() - .Where(z => typeof(ICapability).IsAssignableFrom(z)) - .Where(z => z.IsClass && !z.IsAbstract); + .Where(z => typeof(ICapability).IsAssignableFrom(z)) + .Where(z => z.IsClass && !z.IsAbstract); foreach (var item in capabilities) { options.WithCapability(Activator.CreateInstance(item, Array.Empty()) as ICapability); } + return options; } - public static LanguageClientOptions DisableAllCapabilities( this LanguageClientOptions options) + + public static LanguageClientOptions DisableAllCapabilities(this LanguageClientOptions options) { options.Services.RemoveAll(typeof(ICapability)); return options; diff --git a/src/Testing/ConfigurationHelpers.cs b/src/Testing/ConfigurationHelpers.cs index fe5f6a11f..7cd83f525 100644 --- a/src/Testing/ConfigurationHelpers.cs +++ b/src/Testing/ConfigurationHelpers.cs @@ -6,13 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -using OmniSharp.Extensions.LanguageServer.Client; -using OmniSharp.Extensions.LanguageServer.Protocol.Client; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; -using OmniSharp.Extensions.LanguageServer.Server; namespace OmniSharp.Extensions.LanguageProtocol.Testing { @@ -28,28 +22,32 @@ public static IConfiguration ToConfiguration(this IEnumerable(observer => - { - var reloadToken = configuration.GetReloadToken(); - return reloadToken.RegisterChangeCallback(_ => - { - observer.OnNext(Unit.Default); - observer.OnCompleted(); - }, Unit.Default); - }).ToTask(cancellationToken); + return Observable.Create( + observer => { + var reloadToken = configuration.GetReloadToken(); + return reloadToken.RegisterChangeCallback( + _ => { + observer.OnNext(Unit.Default); + observer.OnCompleted(); + }, Unit.Default + ); + } + ).ToTask(cancellationToken); } public static Task WaitForChange(this IOptionsMonitor options, CancellationToken cancellationToken) { if (options == null) throw new ArgumentNullException(nameof(options)); - return Observable.Create(observer => - { - return options.OnChange(_ => - { - observer.OnNext(Unit.Default); - observer.OnCompleted(); - }); - }).ToTask(cancellationToken); + return Observable.Create( + observer => { + return options.OnChange( + _ => { + observer.OnNext(Unit.Default); + observer.OnCompleted(); + } + ); + } + ).ToTask(cancellationToken); } } } diff --git a/src/Testing/LanguageProtocolTestBase.cs b/src/Testing/LanguageProtocolTestBase.cs index a970da119..02c44dd5b 100644 --- a/src/Testing/LanguageProtocolTestBase.cs +++ b/src/Testing/LanguageProtocolTestBase.cs @@ -5,7 +5,6 @@ using System.Threading.Tasks; using MediatR; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageServer.Client; @@ -29,78 +28,81 @@ public LanguageProtocolTestBase(JsonRpcTestOptions testOptions) : base(testOptio { } - protected virtual void ConfigureClientInputOutput(PipeReader serverOutput, PipeWriter clientInput, LanguageClientOptions options) - { + protected virtual void ConfigureClientInputOutput(PipeReader serverOutput, PipeWriter clientInput, LanguageClientOptions options) => options.WithInput(serverOutput).WithOutput(clientInput); - } - protected virtual void ConfigureServerInputOutput(PipeReader clientOutput, PipeWriter serverInput, LanguageServerOptions options) - { + protected virtual void ConfigureServerInputOutput(PipeReader clientOutput, PipeWriter serverInput, LanguageServerOptions options) => options.WithInput(clientOutput).WithOutput(serverInput); - } protected internal virtual (ILanguageClient client, ILanguageServer server) Create( Action clientOptionsAction, - Action serverOptionsAction) + Action serverOptionsAction + ) { var clientPipe = new Pipe(TestOptions.DefaultPipeOptions); var serverPipe = new Pipe(TestOptions.DefaultPipeOptions); - _client = LanguageClient.PreInit(options => { - options - .WithLoggerFactory(TestOptions.ClientLoggerFactory) - .ConfigureLogging(x => x.SetMinimumLevel(LogLevel.Trace)) - .Services - .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) - .AddSingleton(ClientEvents as IRequestSettler); - ConfigureClientInputOutput(serverPipe.Reader, clientPipe.Writer, options); - clientOptionsAction(options); - }); + _client = LanguageClient.PreInit( + options => { + options + .WithLoggerFactory(TestOptions.ClientLoggerFactory) + .ConfigureLogging(x => x.SetMinimumLevel(LogLevel.Trace)) + .Services + .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) + .AddSingleton(ClientEvents as IRequestSettler); + ConfigureClientInputOutput(serverPipe.Reader, clientPipe.Writer, options); + clientOptionsAction(options); + } + ); - _server = RealLanguageServer.PreInit(options => { - options - .WithLoggerFactory(TestOptions.ClientLoggerFactory) - .ConfigureLogging(x => x.SetMinimumLevel(LogLevel.Trace)) - .Services - .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) - .AddSingleton(ServerEvents as IRequestSettler); - ConfigureServerInputOutput(clientPipe.Reader, serverPipe.Writer, options); - serverOptionsAction(options); - }); + _server = RealLanguageServer.PreInit( + options => { + options + .WithLoggerFactory(TestOptions.ClientLoggerFactory) + .ConfigureLogging(x => x.SetMinimumLevel(LogLevel.Trace)) + .Services + .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) + .AddSingleton(ServerEvents as IRequestSettler); + ConfigureServerInputOutput(clientPipe.Reader, serverPipe.Writer, options); + serverOptionsAction(options); + } + ); Disposable.Add(_client); Disposable.Add(_server); - return (_client, _server); + return ( _client, _server ); } protected internal virtual async Task<(ILanguageClient client, ILanguageServer server)> Initialize( Action clientOptionsAction, - Action serverOptionsAction) + Action serverOptionsAction + ) { - (_client, _server) = Create(clientOptionsAction, serverOptionsAction); + ( _client, _server ) = Create(clientOptionsAction, serverOptionsAction); - return await ObservableEx.ForkJoin( - Observable.FromAsync(_client.Initialize), + return await Observable.FromAsync(_client.Initialize).ForkJoin( Observable.FromAsync(_server.Initialize), - (a, b) => (_client, _server) + (a, b) => ( _client, _server ) ).ToTask(CancellationToken); } protected virtual async Task<(ILanguageClient client, ILanguageServer server, TestConfigurationProvider configurationProvider)> InitializeWithConfiguration( Action clientOptionsAction, Action serverOptionsAction - ) { - var (client, server) = Create(options => { - clientOptionsAction?.Invoke(options); - options.WithCapability(new DidChangeConfigurationCapability()); - options.Services.AddSingleton(); - }, serverOptionsAction); + ) + { + var (client, server) = Create( + options => { + clientOptionsAction?.Invoke(options); + options.WithCapability(new DidChangeConfigurationCapability()); + options.Services.AddSingleton(); + }, serverOptionsAction + ); - return await ObservableEx.ForkJoin( - Observable.FromAsync(client.Initialize), + return await Observable.FromAsync(client.Initialize).ForkJoin( Observable.FromAsync(server.Initialize), - (a, b) => (client, server, client.GetRequiredService()) + (a, b) => ( client, server, client.GetRequiredService() ) ).ToTask(CancellationToken); } } diff --git a/src/Testing/LanguageServerTestBase.cs b/src/Testing/LanguageServerTestBase.cs index 58c752969..eb786c08c 100644 --- a/src/Testing/LanguageServerTestBase.cs +++ b/src/Testing/LanguageServerTestBase.cs @@ -1,8 +1,5 @@ using System; using System.IO; -using System.IO.Pipelines; -using System.Reactive.Linq; -using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using MediatR; using Microsoft.Extensions.DependencyInjection; @@ -11,8 +8,6 @@ using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using OmniSharp.Extensions.LanguageServer.Server; namespace OmniSharp.Extensions.LanguageProtocol.Testing { @@ -31,18 +26,20 @@ public LanguageServerTestBase(JsonRpcTestOptions jsonRpcTestOptions) : base(json protected virtual ILanguageClient CreateClient(Action clientOptionsAction = null) { - _client = LanguageClient.PreInit(options => { - var (reader, writer) = SetupServer(); - options - .WithInput(reader) - .WithOutput(writer) - .WithLoggerFactory(TestOptions.ClientLoggerFactory) - .ConfigureLogging(x => x.SetMinimumLevel(LogLevel.Trace)) - .Services - .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) - .AddSingleton(Events as IRequestSettler); - clientOptionsAction?.Invoke(options); - }); + _client = LanguageClient.PreInit( + options => { + var (reader, writer) = SetupServer(); + options + .WithInput(reader) + .WithOutput(writer) + .WithLoggerFactory(TestOptions.ClientLoggerFactory) + .ConfigureLogging(x => x.SetMinimumLevel(LogLevel.Trace)) + .Services + .AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>)) + .AddSingleton(Events as IRequestSettler); + clientOptionsAction?.Invoke(options); + } + ); Disposable.Add(_client); @@ -59,16 +56,19 @@ protected virtual async Task InitializeClient(Action InitializeClientWithConfiguration( Action clientOptionsAction = null - ) { - var client = CreateClient(options => { - clientOptionsAction?.Invoke(options); - options.WithCapability(new DidChangeConfigurationCapability()); - options.AddHandler(); - }); + ) + { + var client = CreateClient( + options => { + clientOptionsAction?.Invoke(options); + options.WithCapability(new DidChangeConfigurationCapability()); + options.AddHandler(); + } + ); await client.Initialize(CancellationToken); - return (client, client.GetRequiredService()); + return ( client, client.GetRequiredService() ); } } } diff --git a/src/Testing/TestConfigurationProvider.cs b/src/Testing/TestConfigurationProvider.cs index 739c930da..f40697b61 100644 --- a/src/Testing/TestConfigurationProvider.cs +++ b/src/Testing/TestConfigurationProvider.cs @@ -10,7 +10,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; namespace OmniSharp.Extensions.LanguageProtocol.Testing @@ -22,10 +21,7 @@ public class TestConfigurationProvider : IConfigurationHandler private readonly ConcurrentDictionary<(string section, DocumentUri scope), IConfiguration> _scopedConfigurations = new ConcurrentDictionary<(string section, DocumentUri scope), IConfiguration>(); - public TestConfigurationProvider(IWorkspaceLanguageClient workspaceLanguageClient) - { - _workspaceLanguageClient = workspaceLanguageClient; - } + public TestConfigurationProvider(IWorkspaceLanguageClient workspaceLanguageClient) => _workspaceLanguageClient = workspaceLanguageClient; public void Update(string section, IDictionary configuration) { @@ -48,18 +44,15 @@ public void Update(string section, DocumentUri documentUri, IDictionary configuration); + _scopedConfigurations.AddOrUpdate(( section, documentUri ), configuration, (a, _) => configuration); TriggerChange(); } - public void Reset(string section) - { - Reset(section, null); - } + public void Reset(string section) => Reset(section, null); public void Reset(string section, DocumentUri documentUri) { - _scopedConfigurations.TryRemove((section, documentUri), out _); + _scopedConfigurations.TryRemove(( section, documentUri ), out _); _workspaceLanguageClient.DidChangeConfiguration(new DidChangeConfigurationParams()); TriggerChange(); } @@ -67,22 +60,20 @@ public void Reset(string section, DocumentUri documentUri) private IConfiguration Get(ConfigurationItem configurationItem) { if (_scopedConfigurations.TryGetValue( - (configurationItem.Section, configurationItem.ScopeUri), - out var configuration) + ( configurationItem.Section, configurationItem.ScopeUri ), + out var configuration + ) ) { return new ConfigurationBuilder() - .AddConfiguration(configuration, false) - .Build(); + .AddConfiguration(configuration, false) + .Build(); } return new ConfigurationBuilder().Build(); } - private void TriggerChange() - { - _workspaceLanguageClient.DidChangeConfiguration(new DidChangeConfigurationParams()); - } + private void TriggerChange() => _workspaceLanguageClient.DidChangeConfiguration(new DidChangeConfigurationParams()); Task> IRequestHandler>.Handle(ConfigurationParams request, CancellationToken cancellationToken) { @@ -106,13 +97,13 @@ private JObject Parse(IEnumerable> values) var result = new JObject(); foreach (var item in values) { - var keys = item.Key.Split(new[] {":"}, StringSplitOptions.RemoveEmptyEntries); + var keys = item.Key.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries); var prop = keys.Last(); JToken root = result; // This produces a simple look ahead var zippedKeys = keys - .Zip(keys.Skip(1), (prev, current) => (prev, current)); + .Zip(keys.Skip(1), (prev, current) => ( prev, current )); foreach (var (key, next) in zippedKeys) { diff --git a/test/Client.Tests/ClientTests.cs b/test/Client.Tests/ClientTests.cs index 4777e53b6..133ed03e6 100644 --- a/test/Client.Tests/ClientTests.cs +++ b/test/Client.Tests/ClientTests.cs @@ -1,29 +1,28 @@ +using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Xunit; -using Xunit.Abstractions; -using System.Collections.Generic; -using System; using MediatR; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Server; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; +using Xunit; +using Xunit.Abstractions; using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; namespace OmniSharp.Extensions.LanguageServer.Client.Tests { /// - /// Tests for . + /// Tests for . /// public class ClientTests : PipeServerTestBase { /// - /// Create a new test suite. + /// Create a new test suite. /// /// - /// Output for the current test. + /// Output for the current test. /// public ClientTests(ITestOutputHelper testOutput) : base(testOutput) @@ -31,12 +30,12 @@ public ClientTests(ITestOutputHelper testOutput) } /// - /// Get an absolute document path for use in tests. + /// Get an absolute document path for use in tests. /// - string AbsoluteDocumentPath => IsWindows ? @"c:\Foo.txt" : "/Foo.txt"; + private string AbsoluteDocumentPath => IsWindows ? @"c:\Foo.txt" : "/Foo.txt"; /// - /// Ensure that the language client can successfully request Hover information. + /// Ensure that the language client can successfully request Hover information. /// [Fact(DisplayName = "Language client can successfully request hover info")] public async Task Hover_Success() @@ -47,36 +46,45 @@ public async Task Hover_Success() var (client, server) = await Initialize( client => { - client.WithCapability(new HoverCapability() { - ContentFormat = new Container(MarkupKind.Markdown, MarkupKind.PlainText), - }); + client.WithCapability( + new HoverCapability { + ContentFormat = new Container(MarkupKind.Markdown, MarkupKind.PlainText), + } + ); }, server => { - server.OnHover((request, token) => { - Assert.NotNull(request.TextDocument); + server.OnHover( + (request, token) => { + Assert.NotNull(request.TextDocument); - Assert.Equal(AbsoluteDocumentPath, - DocumentUri.GetFileSystemPath(request.TextDocument.Uri) - ); + Assert.Equal( + AbsoluteDocumentPath, + DocumentUri.GetFileSystemPath(request.TextDocument.Uri) + ); - Assert.Equal(line, request.Position.Line); - Assert.Equal(column, request.Position.Character); + Assert.Equal(line, request.Position.Line); + Assert.Equal(column, request.Position.Character); - return Task.FromResult(new Hover { - Contents = expectedHoverContent, - Range = new Range { - Start = request.Position, - End = request.Position - } - }); - }, new HoverRegistrationOptions()); + return Task.FromResult( + new Hover { + Contents = expectedHoverContent, + Range = new Range { + Start = request.Position, + End = request.Position + } + } + ); + }, new HoverRegistrationOptions() + ); } ); - var hover = await client.TextDocument.RequestHover(new HoverParams() { - TextDocument = AbsoluteDocumentPath, - Position = (line, column) - }); + var hover = await client.TextDocument.RequestHover( + new HoverParams { + TextDocument = AbsoluteDocumentPath, + Position = ( line, column ) + } + ); Assert.NotNull(hover.Range); Assert.NotNull(hover.Range.Start); @@ -90,8 +98,9 @@ public async Task Hover_Success() Assert.NotNull(hover.Contents); Assert.True(expectedHoverContent.HasMarkedStrings); - Assert.Equal(expectedHoverContent.MarkedStrings - .Select(markedString => markedString.Value), + Assert.Equal( + expectedHoverContent.MarkedStrings + .Select(markedString => markedString.Value), hover.Contents.MarkedStrings.Select( markedString => markedString.Value ) @@ -99,7 +108,7 @@ public async Task Hover_Success() } /// - /// Ensure that the language client can successfully request Completions. + /// Ensure that the language client can successfully request Completions. /// [Fact(DisplayName = "Language client can successfully request completions")] public async Task Completions_Success() @@ -108,12 +117,12 @@ public async Task Completions_Success() const int column = 5; var expectedDocumentPath = AbsoluteDocumentPath; var expectedDocumentUri = DocumentUri.FromFileSystemPath(expectedDocumentPath); - var expectedCompletionItems = new CompletionItem[] { + var expectedCompletionItems = new[] { new CompletionItem { Kind = CompletionItemKind.Class, Label = "Class1", TextEdit = new TextEdit { - Range = ((line, column), (line, column)), + Range = ( ( line, column ), ( line, column ) ), NewText = "Class1", } } @@ -121,69 +130,88 @@ public async Task Completions_Success() var (client, server) = await Initialize( client => { - client.WithCapability(new CompletionCapability() { - CompletionItem = new CompletionItemCapability() { - DeprecatedSupport = true, - DocumentationFormat = new Container(MarkupKind.Markdown, MarkupKind.PlainText), - PreselectSupport = true, - SnippetSupport = true, - TagSupport = new CompletionItemTagSupportCapability() { - ValueSet = new[] {CompletionItemTag.Deprecated} - }, - CommitCharactersSupport = true + client.WithCapability( + new CompletionCapability { + CompletionItem = new CompletionItemCapability { + DeprecatedSupport = true, + DocumentationFormat = new Container(MarkupKind.Markdown, MarkupKind.PlainText), + PreselectSupport = true, + SnippetSupport = true, + TagSupport = new CompletionItemTagSupportCapability { + ValueSet = new[] { CompletionItemTag.Deprecated } + }, + CommitCharactersSupport = true + } } - }); + ); }, server => { - server.OnCompletion((request, cancellationToken) => { - Assert.NotNull(request.TextDocument); + server.OnCompletion( + (request, cancellationToken) => { + Assert.NotNull(request.TextDocument); - Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); + Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); - Assert.Equal(line, request.Position.Line); - Assert.Equal(column, request.Position.Character); + Assert.Equal(line, request.Position.Line); + Assert.Equal(column, request.Position.Character); - return Task.FromResult(new CompletionList( - expectedCompletionItems, - isIncomplete: true - )); - }, new CompletionRegistrationOptions()); - }); + return Task.FromResult( + new CompletionList( + expectedCompletionItems, + true + ) + ); + }, new CompletionRegistrationOptions() + ); + } + ); - var actualCompletions = await client.TextDocument.RequestCompletion(new CompletionParams() { - TextDocument = AbsoluteDocumentPath, - Position = (line, column), - }, CancellationToken); + var actualCompletions = await client.TextDocument.RequestCompletion( + new CompletionParams { + TextDocument = AbsoluteDocumentPath, + Position = ( line, column ), + }, CancellationToken + ); Assert.True(actualCompletions.IsIncomplete, "completions.IsIncomplete"); Assert.NotNull(actualCompletions.Items); var actualCompletionItems = actualCompletions.Items.ToArray(); - Assert.Collection(actualCompletionItems, actualCompletionItem => { - var expectedCompletionItem = expectedCompletionItems[0]; - - Assert.Equal(expectedCompletionItem.Kind, actualCompletionItem.Kind); - Assert.Equal(expectedCompletionItem.Label, actualCompletionItem.Label); - - Assert.NotNull(actualCompletionItem.TextEdit); - Assert.Equal(expectedCompletionItem.TextEdit.NewText, actualCompletionItem.TextEdit.NewText); - - Assert.NotNull(actualCompletionItem.TextEdit.Range); - Assert.NotNull(actualCompletionItem.TextEdit.Range.Start); - Assert.NotNull(actualCompletionItem.TextEdit.Range.End); - Assert.Equal(expectedCompletionItem.TextEdit.Range.Start.Line, - actualCompletionItem.TextEdit.Range.Start.Line); - Assert.Equal(expectedCompletionItem.TextEdit.Range.Start.Character, - actualCompletionItem.TextEdit.Range.Start.Character); - Assert.Equal(expectedCompletionItem.TextEdit.Range.End.Line, - actualCompletionItem.TextEdit.Range.End.Line); - Assert.Equal(expectedCompletionItem.TextEdit.Range.End.Character, - actualCompletionItem.TextEdit.Range.End.Character); - }); + Assert.Collection( + actualCompletionItems, actualCompletionItem => { + var expectedCompletionItem = expectedCompletionItems[0]; + + Assert.Equal(expectedCompletionItem.Kind, actualCompletionItem.Kind); + Assert.Equal(expectedCompletionItem.Label, actualCompletionItem.Label); + + Assert.NotNull(actualCompletionItem.TextEdit); + Assert.Equal(expectedCompletionItem.TextEdit.NewText, actualCompletionItem.TextEdit.NewText); + + Assert.NotNull(actualCompletionItem.TextEdit.Range); + Assert.NotNull(actualCompletionItem.TextEdit.Range.Start); + Assert.NotNull(actualCompletionItem.TextEdit.Range.End); + Assert.Equal( + expectedCompletionItem.TextEdit.Range.Start.Line, + actualCompletionItem.TextEdit.Range.Start.Line + ); + Assert.Equal( + expectedCompletionItem.TextEdit.Range.Start.Character, + actualCompletionItem.TextEdit.Range.Start.Character + ); + Assert.Equal( + expectedCompletionItem.TextEdit.Range.End.Line, + actualCompletionItem.TextEdit.Range.End.Line + ); + Assert.Equal( + expectedCompletionItem.TextEdit.Range.End.Character, + actualCompletionItem.TextEdit.Range.End.Character + ); + } + ); } /// - /// Ensure that the language client can successfully request SignatureHelp. + /// Ensure that the language client can successfully request SignatureHelp. /// [Fact(DisplayName = "Language client can successfully request signature help")] public async Task SignatureHelp_Success() @@ -213,15 +241,16 @@ public async Task SignatureHelp_Success() var (client, server) = await Initialize( client => { client.WithCapability( - new SignatureHelpCapability() { + new SignatureHelpCapability { ContextSupport = true, - SignatureInformation = new SignatureInformationCapability() { + SignatureInformation = new SignatureInformationCapability { DocumentationFormat = new Container(MarkupKind.Markdown), - ParameterInformation = new SignatureParameterInformationCapability() { + ParameterInformation = new SignatureParameterInformationCapability { LabelOffsetSupport = true } } - }); + } + ); }, server => { server.OnSignatureHelp( @@ -234,40 +263,48 @@ public async Task SignatureHelp_Success() Assert.Equal(column, request.Position.Character); return Task.FromResult(expectedSignatureHelp); - }, new SignatureHelpRegistrationOptions()); - }); + }, new SignatureHelpRegistrationOptions() + ); + } + ); - var actualSignatureHelp = await client.TextDocument.RequestSignatureHelp(new SignatureHelpParams() { - TextDocument = AbsoluteDocumentPath, - Position = (line, column), - }, CancellationToken); + var actualSignatureHelp = await client.TextDocument.RequestSignatureHelp( + new SignatureHelpParams { + TextDocument = AbsoluteDocumentPath, + Position = ( line, column ), + }, CancellationToken + ); Assert.Equal(expectedSignatureHelp.ActiveParameter, actualSignatureHelp.ActiveParameter); Assert.Equal(expectedSignatureHelp.ActiveSignature, actualSignatureHelp.ActiveSignature); var actualSignatures = actualSignatureHelp.Signatures.ToArray(); - Assert.Collection(actualSignatures, actualSignature => { - var expectedSignature = expectedSignatureHelp.Signatures.ToArray()[0]; + Assert.Collection( + actualSignatures, actualSignature => { + var expectedSignature = expectedSignatureHelp.Signatures.ToArray()[0]; - Assert.True(actualSignature.Documentation.HasString); - Assert.Equal(expectedSignature.Documentation.String, actualSignature.Documentation.String); + Assert.True(actualSignature.Documentation.HasString); + Assert.Equal(expectedSignature.Documentation.String, actualSignature.Documentation.String); - Assert.Equal(expectedSignature.Label, actualSignature.Label); + Assert.Equal(expectedSignature.Label, actualSignature.Label); - var expectedParameters = expectedSignature.Parameters.ToArray(); - var actualParameters = actualSignature.Parameters.ToArray(); + var expectedParameters = expectedSignature.Parameters.ToArray(); + var actualParameters = actualSignature.Parameters.ToArray(); - Assert.Collection(actualParameters, actualParameter => { - var expectedParameter = expectedParameters[0]; - Assert.True(actualParameter.Documentation.HasString); - Assert.Equal(expectedParameter.Documentation.String, actualParameter.Documentation.String); - Assert.Equal(expectedParameter.Label.Label, actualParameter.Label.Label); - }); - }); + Assert.Collection( + actualParameters, actualParameter => { + var expectedParameter = expectedParameters[0]; + Assert.True(actualParameter.Documentation.HasString); + Assert.Equal(expectedParameter.Documentation.String, actualParameter.Documentation.String); + Assert.Equal(expectedParameter.Label.Label, actualParameter.Label.Label); + } + ); + } + ); } /// - /// Ensure that the language client can successfully request Definition. + /// Ensure that the language client can successfully request Definition. /// [Fact(DisplayName = "Language client can successfully request definition")] public async Task Definition_Success() @@ -278,58 +315,72 @@ public async Task Definition_Success() var expectedDocumentUri = DocumentUri.FromFileSystemPath(expectedDocumentPath); var expectedDefinitions = new LocationOrLocationLinks( - new LocationOrLocationLink(new Location { - Uri = expectedDocumentUri, - Range = ((line, column), (line, column)), - })); + new LocationOrLocationLink( + new Location { + Uri = expectedDocumentUri, + Range = ( ( line, column ), ( line, column ) ), + } + ) + ); var (client, server) = await Initialize( client => { client.WithCapability( - new DefinitionCapability() { + new DefinitionCapability { LinkSupport = true } ); }, server => { - server.OnDefinition((request, cancellationToken) => { - Assert.NotNull(request.TextDocument); + server.OnDefinition( + (request, cancellationToken) => { + Assert.NotNull(request.TextDocument); - Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); + Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); - Assert.Equal(line, request.Position.Line); - Assert.Equal(column, request.Position.Character); + Assert.Equal(line, request.Position.Line); + Assert.Equal(column, request.Position.Character); - return Task.FromResult(expectedDefinitions); - }, new DefinitionRegistrationOptions()); - }); + return Task.FromResult(expectedDefinitions); + }, new DefinitionRegistrationOptions() + ); + } + ); - var definitions = await client.TextDocument.RequestDefinition(new DefinitionParams() { - TextDocument = AbsoluteDocumentPath, - Position = (line, column), - }, CancellationToken); + var definitions = await client.TextDocument.RequestDefinition( + new DefinitionParams { + TextDocument = AbsoluteDocumentPath, + Position = ( line, column ), + }, CancellationToken + ); var actualDefinitions = definitions.ToArray(); - Assert.Collection(actualDefinitions, actualDefinition => { - var expectedDefinition = expectedDefinitions.Single(); - - Assert.NotNull(actualDefinition.Location); - Assert.Equal(expectedDefinition.Location.Uri, actualDefinition.Location.Uri); - - Assert.NotNull(actualDefinition.Location.Range); - Assert.NotNull(actualDefinition.Location.Range.Start); - Assert.NotNull(actualDefinition.Location.Range.End); - Assert.Equal(expectedDefinition.Location.Range.Start.Line, actualDefinition.Location.Range.Start.Line); - Assert.Equal(expectedDefinition.Location.Range.Start.Character, - actualDefinition.Location.Range.Start.Character); - Assert.Equal(expectedDefinition.Location.Range.End.Line, actualDefinition.Location.Range.End.Line); - Assert.Equal(expectedDefinition.Location.Range.End.Character, - actualDefinition.Location.Range.End.Character); - }); + Assert.Collection( + actualDefinitions, actualDefinition => { + var expectedDefinition = expectedDefinitions.Single(); + + Assert.NotNull(actualDefinition.Location); + Assert.Equal(expectedDefinition.Location.Uri, actualDefinition.Location.Uri); + + Assert.NotNull(actualDefinition.Location.Range); + Assert.NotNull(actualDefinition.Location.Range.Start); + Assert.NotNull(actualDefinition.Location.Range.End); + Assert.Equal(expectedDefinition.Location.Range.Start.Line, actualDefinition.Location.Range.Start.Line); + Assert.Equal( + expectedDefinition.Location.Range.Start.Character, + actualDefinition.Location.Range.Start.Character + ); + Assert.Equal(expectedDefinition.Location.Range.End.Line, actualDefinition.Location.Range.End.Line); + Assert.Equal( + expectedDefinition.Location.Range.End.Character, + actualDefinition.Location.Range.End.Character + ); + } + ); } /// - /// Ensure that the language client can successfully request DocumentHighlight. + /// Ensure that the language client can successfully request DocumentHighlight. /// [Fact(DisplayName = "Language client can successfully request document highlights")] public async Task DocumentHighlights_Success() @@ -342,51 +393,59 @@ public async Task DocumentHighlights_Success() var expectedHighlights = new DocumentHighlightContainer( new DocumentHighlight { Kind = DocumentHighlightKind.Write, - Range = ((line, column), (line, column)), - }); + Range = ( ( line, column ), ( line, column ) ), + } + ); var (client, server) = await Initialize( client => { client.WithCapability( - new DocumentHighlightCapability() { } + new DocumentHighlightCapability() ); }, server => { - server.OnDocumentHighlight((request, cancellationToken) => { - Assert.NotNull(request.TextDocument); + server.OnDocumentHighlight( + (request, cancellationToken) => { + Assert.NotNull(request.TextDocument); - Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); + Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); - Assert.Equal(line, request.Position.Line); - Assert.Equal(column, request.Position.Character); + Assert.Equal(line, request.Position.Line); + Assert.Equal(column, request.Position.Character); - return Task.FromResult(expectedHighlights); - }, new DocumentHighlightRegistrationOptions()); - }); + return Task.FromResult(expectedHighlights); + }, new DocumentHighlightRegistrationOptions() + ); + } + ); - var definitions = await client.TextDocument.RequestDocumentHighlight(new DocumentHighlightParams() { - TextDocument = AbsoluteDocumentPath, - Position = (line, column), - }, CancellationToken); + var definitions = await client.TextDocument.RequestDocumentHighlight( + new DocumentHighlightParams { + TextDocument = AbsoluteDocumentPath, + Position = ( line, column ), + }, CancellationToken + ); var actualDefinitions = definitions.ToArray(); - Assert.Collection(actualDefinitions, actualHighlight => { - var expectedHighlight = expectedHighlights.Single(); - - Assert.Equal(DocumentHighlightKind.Write, expectedHighlight.Kind); - - Assert.NotNull(actualHighlight.Range); - Assert.NotNull(actualHighlight.Range.Start); - Assert.NotNull(actualHighlight.Range.End); - Assert.Equal(expectedHighlight.Range.Start.Line, actualHighlight.Range.Start.Line); - Assert.Equal(expectedHighlight.Range.Start.Character, actualHighlight.Range.Start.Character); - Assert.Equal(expectedHighlight.Range.End.Line, actualHighlight.Range.End.Line); - Assert.Equal(expectedHighlight.Range.End.Character, actualHighlight.Range.End.Character); - }); + Assert.Collection( + actualDefinitions, actualHighlight => { + var expectedHighlight = expectedHighlights.Single(); + + Assert.Equal(DocumentHighlightKind.Write, expectedHighlight.Kind); + + Assert.NotNull(actualHighlight.Range); + Assert.NotNull(actualHighlight.Range.Start); + Assert.NotNull(actualHighlight.Range.End); + Assert.Equal(expectedHighlight.Range.Start.Line, actualHighlight.Range.Start.Line); + Assert.Equal(expectedHighlight.Range.Start.Character, actualHighlight.Range.Start.Character); + Assert.Equal(expectedHighlight.Range.End.Line, actualHighlight.Range.End.Line); + Assert.Equal(expectedHighlight.Range.End.Character, actualHighlight.Range.End.Character); + } + ); } /// - /// Ensure that the language client can successfully request DocumentHighlight. + /// Ensure that the language client can successfully request DocumentHighlight. /// [Fact(DisplayName = "Language client can successfully request document symbols")] public async Task DocumentSymbols_DocumentSymbol_Success() @@ -403,57 +462,75 @@ public async Task DocumentSymbols_DocumentSymbol_Success() Range = new Range(new Position(line, character), new Position(line, character)) }; var expectedSymbols = new SymbolInformationOrDocumentSymbolContainer( - new SymbolInformationOrDocumentSymbol(documentSymbol)); + new SymbolInformationOrDocumentSymbol(documentSymbol) + ); var (client, server) = await Initialize( client => { - client.WithCapability(new DocumentSymbolCapability() { - DynamicRegistration = true, - SymbolKind = new SymbolKindCapability() { - ValueSet = new Container(Enum.GetValues(typeof(SymbolKind)).Cast() - .ToArray()) - }, - TagSupport = new TagSupportCapability() { - ValueSet = new[] {SymbolTag.Deprecated} - }, - HierarchicalDocumentSymbolSupport = true - }); + client.WithCapability( + new DocumentSymbolCapability { + DynamicRegistration = true, + SymbolKind = new SymbolKindCapability { + ValueSet = new Container( + Enum.GetValues(typeof(SymbolKind)).Cast() + .ToArray() + ) + }, + TagSupport = new TagSupportCapability { + ValueSet = new[] { SymbolTag.Deprecated } + }, + HierarchicalDocumentSymbolSupport = true + } + ); }, server => { - server.OnDocumentSymbol((request, cancellationToken) => { - Assert.NotNull(request.TextDocument); + server.OnDocumentSymbol( + (request, cancellationToken) => { + Assert.NotNull(request.TextDocument); - Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); + Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); - return Task.FromResult(expectedSymbols); - }, new DocumentSymbolRegistrationOptions()); - }); + return Task.FromResult(expectedSymbols); + }, new DocumentSymbolRegistrationOptions() + ); + } + ); - var symbols = await client.TextDocument.RequestDocumentSymbol(new DocumentSymbolParams { - TextDocument = expectedDocumentUri - }, CancellationToken); + var symbols = await client.TextDocument.RequestDocumentSymbol( + new DocumentSymbolParams { + TextDocument = expectedDocumentUri + }, CancellationToken + ); var actualSymbols = symbols.ToArray(); - Assert.Collection(actualSymbols, actualSymbol => { - var expectedSymbol = expectedSymbols.Single(); - - Assert.True(expectedSymbol.IsDocumentSymbol); - - Assert.NotNull(actualSymbol.DocumentSymbol); - Assert.Equal(expectedSymbol.DocumentSymbol.Detail, actualSymbol.DocumentSymbol.Detail); - Assert.Equal(expectedSymbol.DocumentSymbol.Kind, actualSymbol.DocumentSymbol.Kind); - Assert.Equal(expectedSymbol.DocumentSymbol.Range.Start.Line, - actualSymbol.DocumentSymbol.Range.Start.Line); - Assert.Equal(expectedSymbol.DocumentSymbol.Range.Start.Character, - actualSymbol.DocumentSymbol.Range.Start.Character); - Assert.Equal(expectedSymbol.DocumentSymbol.Range.End.Line, actualSymbol.DocumentSymbol.Range.End.Line); - Assert.Equal(expectedSymbol.DocumentSymbol.Range.End.Character, - actualSymbol.DocumentSymbol.Range.End.Character); - }); + Assert.Collection( + actualSymbols, actualSymbol => { + var expectedSymbol = expectedSymbols.Single(); + + Assert.True(expectedSymbol.IsDocumentSymbol); + + Assert.NotNull(actualSymbol.DocumentSymbol); + Assert.Equal(expectedSymbol.DocumentSymbol.Detail, actualSymbol.DocumentSymbol.Detail); + Assert.Equal(expectedSymbol.DocumentSymbol.Kind, actualSymbol.DocumentSymbol.Kind); + Assert.Equal( + expectedSymbol.DocumentSymbol.Range.Start.Line, + actualSymbol.DocumentSymbol.Range.Start.Line + ); + Assert.Equal( + expectedSymbol.DocumentSymbol.Range.Start.Character, + actualSymbol.DocumentSymbol.Range.Start.Character + ); + Assert.Equal(expectedSymbol.DocumentSymbol.Range.End.Line, actualSymbol.DocumentSymbol.Range.End.Line); + Assert.Equal( + expectedSymbol.DocumentSymbol.Range.End.Character, + actualSymbol.DocumentSymbol.Range.End.Character + ); + } + ); } /// - /// Ensure that the language client can successfully request FoldingRanges. + /// Ensure that the language client can successfully request FoldingRanges. /// [Fact(DisplayName = "Language client can successfully request document folding ranges")] public async Task FoldingRanges_Success() @@ -468,42 +545,52 @@ public async Task FoldingRanges_Success() StartCharacter = 1, EndLine = 7, EndCharacter = 2, - }); + } + ); var (client, server) = await Initialize( client => { - client.WithCapability(new FoldingRangeCapability() { - RangeLimit = 100, - LineFoldingOnly = true - }); + client.WithCapability( + new FoldingRangeCapability { + RangeLimit = 100, + LineFoldingOnly = true + } + ); }, server => { - server.OnFoldingRange((request, cancellationToken) => { - Assert.NotNull(request.TextDocument); - Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); - return Task.FromResult(expectedFoldingRanges); - }, new FoldingRangeRegistrationOptions()); - }); + server.OnFoldingRange( + (request, cancellationToken) => { + Assert.NotNull(request.TextDocument); + Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); + return Task.FromResult(expectedFoldingRanges); + }, new FoldingRangeRegistrationOptions() + ); + } + ); - var foldingRanges = await client.TextDocument.RequestFoldingRange(new FoldingRangeRequestParam() { - TextDocument = AbsoluteDocumentPath - }, CancellationToken); + var foldingRanges = await client.TextDocument.RequestFoldingRange( + new FoldingRangeRequestParam { + TextDocument = AbsoluteDocumentPath + }, CancellationToken + ); var actualFoldingRanges = foldingRanges.ToArray(); - Assert.Collection(actualFoldingRanges, actualFoldingRange => { - var expectedFoldingRange = expectedFoldingRanges.Single(); + Assert.Collection( + actualFoldingRanges, actualFoldingRange => { + var expectedFoldingRange = expectedFoldingRanges.Single(); - Assert.Equal(FoldingRangeKind.Region, expectedFoldingRange.Kind); + Assert.Equal(FoldingRangeKind.Region, expectedFoldingRange.Kind); - Assert.Equal(expectedFoldingRange.StartLine, actualFoldingRange.StartLine); - Assert.Equal(expectedFoldingRange.StartCharacter, actualFoldingRange.StartCharacter); - Assert.Equal(expectedFoldingRange.EndLine, actualFoldingRange.EndLine); - Assert.Equal(expectedFoldingRange.EndCharacter, actualFoldingRange.EndCharacter); - }); + Assert.Equal(expectedFoldingRange.StartLine, actualFoldingRange.StartLine); + Assert.Equal(expectedFoldingRange.StartCharacter, actualFoldingRange.StartCharacter); + Assert.Equal(expectedFoldingRange.EndLine, actualFoldingRange.EndLine); + Assert.Equal(expectedFoldingRange.EndCharacter, actualFoldingRange.EndCharacter); + } + ); } /// - /// Ensure that the language client can successfully receive Diagnostics from the server. + /// Ensure that the language client can successfully receive Diagnostics from the server. /// [Fact(DisplayName = "Language client can successfully receive diagnostics")] public async Task Diagnostics_Success() @@ -536,21 +623,25 @@ public async Task Diagnostics_Success() var (client, server) = await Initialize( client => { - client.OnPublishDiagnostics((request) => { - actualDocumentUri = request.Uri; - actualDiagnostics = request.Diagnostics.ToList(); + client.OnPublishDiagnostics( + request => { + actualDocumentUri = request.Uri; + actualDiagnostics = request.Diagnostics.ToList(); - receivedDiagnosticsNotification.SetResult(null); - return Unit.Task; - }); + receivedDiagnosticsNotification.SetResult(null); + return Unit.Task; + } + ); }, - server => { - }); + server => { } + ); - server.TextDocument.PublishDiagnostics(new PublishDiagnosticsParams { - Uri = DocumentUri.FromFileSystemPath(documentPath), - Diagnostics = expectedDiagnostics - }); + server.TextDocument.PublishDiagnostics( + new PublishDiagnosticsParams { + Uri = DocumentUri.FromFileSystemPath(documentPath), + Diagnostics = expectedDiagnostics + } + ); CancellationToken.Register(() => receivedDiagnosticsNotification.SetCanceled()); diff --git a/test/Client.Tests/Logging/TestOutputLogScope.cs b/test/Client.Tests/Logging/TestOutputLogScope.cs index 026837306..e3150359a 100644 --- a/test/Client.Tests/Logging/TestOutputLogScope.cs +++ b/test/Client.Tests/Logging/TestOutputLogScope.cs @@ -4,17 +4,17 @@ namespace OmniSharp.Extensions.LanguageServer.Client.Tests.Logging { /// - /// Log scope for . + /// Log scope for . /// internal class TestOutputLogScope { /// - /// Storage for the current . + /// Storage for the current . /// - static readonly AsyncLocal _currentScope = new AsyncLocal(); + private static readonly AsyncLocal _currentScope = new AsyncLocal(); /// - /// The current (if any). + /// The current (if any). /// public static TestOutputLogScope Current { @@ -23,23 +23,23 @@ public static TestOutputLogScope Current } /// - /// The scope name. + /// The scope name. /// - readonly string _name; + private readonly string _name; /// - /// State associated with the scope. + /// State associated with the scope. /// - readonly object _state; + private readonly object _state; /// - /// Create a new . + /// Create a new . /// /// - /// The scope name. + /// The scope name. /// /// - /// State associated with the scope. + /// State associated with the scope. /// public TestOutputLogScope(string name, object state) { @@ -48,25 +48,25 @@ public TestOutputLogScope(string name, object state) } /// - /// The scope's parent scope (if any). + /// The scope's parent scope (if any). /// public TestOutputLogScope Parent { get; private set; } /// - /// Create a new and make it the current . + /// Create a new and make it the current . /// /// - /// The scope name. + /// The scope name. /// /// - /// State associated with the scope. + /// State associated with the scope. /// /// - /// An representing the scope. + /// An representing the scope. /// public static IDisposable Push(string name, object state) { - TestOutputLogScope parent = Current; + var parent = Current; Current = new TestOutputLogScope(name, state) { Parent = parent }; @@ -75,26 +75,26 @@ public static IDisposable Push(string name, object state) } /// - /// Get a string representation of the scope. + /// Get a string representation of the scope. /// /// - /// The scope's string representation. + /// The scope's string representation. /// public override string ToString() => _state?.ToString(); /// - /// Wrapper for disposal of log scope. + /// Wrapper for disposal of log scope. /// - class ScopeDisposal + private class ScopeDisposal : IDisposable { /// - /// Has the scope been disposed? + /// Has the scope been disposed? /// - bool _disposed; + private bool _disposed; /// - /// Revert to the previous scope (if any). + /// Revert to the previous scope (if any). /// public void Dispose() { diff --git a/test/Client.Tests/Logging/TestOutputLogger.cs b/test/Client.Tests/Logging/TestOutputLogger.cs index c6e494805..d3e2a727e 100644 --- a/test/Client.Tests/Logging/TestOutputLogger.cs +++ b/test/Client.Tests/Logging/TestOutputLogger.cs @@ -1,41 +1,42 @@ -using Microsoft.Extensions.Logging; using System; +using System.Diagnostics; +using Microsoft.Extensions.Logging; using Xunit.Abstractions; namespace OmniSharp.Extensions.LanguageServer.Client.Tests.Logging { /// - /// A logger that writes to Xunit test output. + /// A logger that writes to Xunit test output. /// public class TestOutputLogger : ILogger { /// - /// The Xunit test output. + /// The Xunit test output. /// - readonly ITestOutputHelper _testOutput; + private readonly ITestOutputHelper _testOutput; /// - /// The logger name. + /// The logger name. /// - readonly string _name; + private readonly string _name; /// - /// The minimum level to log at. + /// The minimum level to log at. /// - readonly LogLevel _minimumLevel; + private readonly LogLevel _minimumLevel; /// - /// Create a new . + /// Create a new . /// /// - /// The Xunit test output. + /// The Xunit test output. /// /// - /// The logger name. + /// The logger name. /// /// - /// The minimum level to log at. + /// The minimum level to log at. /// public TestOutputLogger(ITestOutputHelper testOutput, string name, LogLevel minimumLevel) { @@ -48,70 +49,70 @@ public TestOutputLogger(ITestOutputHelper testOutput, string name, LogLevel mini _testOutput = testOutput; // Trim off namespace, if possible. - string[] nameSegments = name.Split('.'); + var nameSegments = name.Split('.'); _name = nameSegments[nameSegments.Length - 1]; _minimumLevel = minimumLevel; } /// - /// Begin a new log scope. + /// Begin a new log scope. /// /// - /// The type used as state for the scope. + /// The type used as state for the scope. /// /// - /// The scope state. + /// The scope state. /// /// - /// An representing the scope. + /// An representing the scope. /// public IDisposable BeginScope(TState state) => TestOutputLogScope.Push(_name, state); /// - /// Determine whether logging is enabled at the specified level. + /// Determine whether logging is enabled at the specified level. /// /// - /// The target log level. + /// The target log level. /// /// - /// true, if logging is enabled; otherwise, false. + /// true, if logging is enabled; otherwise, false. /// public bool IsEnabled(LogLevel logLevel) => logLevel >= _minimumLevel; /// - /// Write a log message to the test output. + /// Write a log message to the test output. /// /// - /// The type used as state for the log entry. + /// The type used as state for the log entry. /// /// - /// The log entry's associated logging level. + /// The log entry's associated logging level. /// /// - /// An identifying the log entry type. + /// An identifying the log entry type. /// /// - /// The log entry state. + /// The log entry state. /// /// - /// The (if any) associated with the log entry. + /// The (if any) associated with the log entry. /// /// - /// A delegate that formats the log message. + /// A delegate that formats the log message. /// public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) { if (logLevel < _minimumLevel) return; - string prefix = !string.IsNullOrWhiteSpace(_name) + var prefix = !string.IsNullOrWhiteSpace(_name) ? $"[{_name}/{logLevel}] " : $"[{logLevel}] "; - string message = prefix + formatter(state, exception); + var message = prefix + formatter(state, exception); if (exception != null) - message += "\n" + exception.ToString(); + message += "\n" + exception; try { @@ -121,7 +122,7 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except { // Test has already terminated. - System.Diagnostics.Debug.WriteLine(message); + Debug.WriteLine(message); } } } diff --git a/test/Client.Tests/Logging/TestOutputLoggingExtensions.cs b/test/Client.Tests/Logging/TestOutputLoggingExtensions.cs index 6fe2a699b..50b822821 100644 --- a/test/Client.Tests/Logging/TestOutputLoggingExtensions.cs +++ b/test/Client.Tests/Logging/TestOutputLoggingExtensions.cs @@ -1,25 +1,25 @@ -using Microsoft.Extensions.Logging; using System; +using Microsoft.Extensions.Logging; using Xunit.Abstractions; namespace OmniSharp.Extensions.LanguageServer.Client.Tests.Logging { /// - /// Extension methods for configuring logging to Xunit test output. + /// Extension methods for configuring logging to Xunit test output. /// public static class TestOutputLoggingExtensions { /// - /// Write log events to Xunit test output. + /// Write log events to Xunit test output. /// /// - /// The logger factory to configure. + /// The logger factory to configure. /// /// - /// The test output to which events will be logged. + /// The test output to which events will be logged. /// /// - /// The minimum level to log at. + /// The minimum level to log at. /// public static void AddTestOutput(this ILoggerFactory loggerFactory, ITestOutputHelper testOutput, LogLevel minimumLevel = LogLevel.Information) { diff --git a/test/Client.Tests/Logging/TestOutputLoggingProvider.cs b/test/Client.Tests/Logging/TestOutputLoggingProvider.cs index f4e41939a..8b1368703 100644 --- a/test/Client.Tests/Logging/TestOutputLoggingProvider.cs +++ b/test/Client.Tests/Logging/TestOutputLoggingProvider.cs @@ -1,39 +1,39 @@ -using Microsoft.Extensions.Logging; using System; -using Xunit.Abstractions; using System.Collections.Concurrent; +using Microsoft.Extensions.Logging; +using Xunit.Abstractions; namespace OmniSharp.Extensions.LanguageServer.Client.Tests.Logging { /// - /// A provider for loggers that send log events to Xunit test output. + /// A provider for loggers that send log events to Xunit test output. /// public sealed class TestOutputLoggingProvider : ILoggerProvider { /// - /// Loggers created by the provider. + /// Loggers created by the provider. /// - static readonly ConcurrentDictionary _loggers = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary _loggers = new ConcurrentDictionary(); /// - /// The test output to which events will be logged. + /// The test output to which events will be logged. /// - readonly ITestOutputHelper _testOutput; + private readonly ITestOutputHelper _testOutput; /// - /// The minimum level to log at. + /// The minimum level to log at. /// - readonly LogLevel _minimumLevel; + private readonly LogLevel _minimumLevel; /// - /// Create a new test output event sink. + /// Create a new test output event sink. /// /// - /// The test output to which events will be logged. + /// The test output to which events will be logged. /// /// - /// The minimum level to log at. + /// The minimum level to log at. /// public TestOutputLoggingProvider(ITestOutputHelper testOutput, LogLevel minimumLevel) { @@ -45,26 +45,27 @@ public TestOutputLoggingProvider(ITestOutputHelper testOutput, LogLevel minimumL } /// - /// Create a new logger. + /// Create a new logger. /// /// - /// The logger name. + /// The logger name. /// /// - /// The logger. + /// The logger. /// public ILogger CreateLogger(string name) { if (name == null) name = string.Empty; - return _loggers.GetOrAdd(name, + return _loggers.GetOrAdd( + name, new TestOutputLogger(_testOutput, name, _minimumLevel) ); } /// - /// Dispose of resources being used by the logger provider and its loggers. + /// Dispose of resources being used by the logger provider and its loggers. /// public void Dispose() { diff --git a/test/Client.Tests/PipeServerTestBase.cs b/test/Client.Tests/PipeServerTestBase.cs index 1cbd16c41..5ac4a6ad9 100644 --- a/test/Client.Tests/PipeServerTestBase.cs +++ b/test/Client.Tests/PipeServerTestBase.cs @@ -14,12 +14,12 @@ namespace OmniSharp.Extensions.LanguageServer.Client.Tests { /// - /// The base class for test suites that use a . + /// The base class for test suites that use a . /// public abstract class PipeServerTestBase : TestBase, IAsyncLifetime { /// - /// The used to connect client and server streams. + /// The used to connect client and server streams. /// private readonly CancellationTokenSource _cancellationTokenSource; @@ -29,10 +29,10 @@ public abstract class PipeServerTestBase : TestBase, IAsyncLifetime private ILanguageServer _server; /// - /// Create a new . + /// Create a new . /// /// - /// Output for the current test. + /// Output for the current test. /// protected PipeServerTestBase(ITestOutputHelper testOutput) : base(testOutput) @@ -45,35 +45,40 @@ protected PipeServerTestBase(ITestOutputHelper testOutput) } /// - /// The workspace root path. + /// The workspace root path. /// protected string WorkspaceRoot => Path.GetDirectoryName(GetType().Assembly.Location); /// - /// Create a connected to the test's . + /// Create a connected to the test's . /// /// - /// The . + /// The . /// protected async Task<(ILanguageClient client, ILanguageServer server)> Initialize( Action clientOptionsAction, - Action serverOptionsAction) + Action serverOptionsAction + ) { var clientPipe = new Pipe(); var serverPipe = new Pipe(); - _client = LanguageClient.PreInit(options => { - options.WithServices(services => services.AddSingleton(LoggerFactory)); - options.WithInput(serverPipe.Reader).WithOutput(clientPipe.Writer); - options.WithRootPath(WorkspaceRoot); - clientOptionsAction(options); - }); + _client = LanguageClient.PreInit( + options => { + options.WithServices(services => services.AddSingleton(LoggerFactory)); + options.WithInput(serverPipe.Reader).WithOutput(clientPipe.Writer); + options.WithRootPath(WorkspaceRoot); + clientOptionsAction(options); + } + ); Disposal.Add(_client); - _server = OmniSharp.Extensions.LanguageServer.Server.LanguageServer.PreInit(options => { - options.WithServices(services => services.AddSingleton(LoggerFactory)); - options.WithInput(clientPipe.Reader).WithOutput(serverPipe.Writer); - serverOptionsAction(options); - }); + _server = Server.LanguageServer.PreInit( + options => { + options.WithServices(services => services.AddSingleton(LoggerFactory)); + options.WithInput(clientPipe.Reader).WithOutput(serverPipe.Writer); + serverOptionsAction(options); + } + ); Disposal.Add(_server); await Task.WhenAll( @@ -81,7 +86,7 @@ await Task.WhenAll( _server.Initialize(CancellationToken) ); - return (_client, _server); + return ( _client, _server ); } public virtual Task InitializeAsync() => Task.CompletedTask; diff --git a/test/Client.Tests/TestBase.cs b/test/Client.Tests/TestBase.cs index ba6629e1f..fc0170dad 100644 --- a/test/Client.Tests/TestBase.cs +++ b/test/Client.Tests/TestBase.cs @@ -1,27 +1,26 @@ -using Microsoft.Extensions.Logging; using System; using System.Reactive.Disposables; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; +using Microsoft.Extensions.Logging; +using OmniSharp.Extensions.LanguageServer.Client.Tests.Logging; using Xunit; using Xunit.Abstractions; namespace OmniSharp.Extensions.LanguageServer.Client.Tests { - using Logging; - /// - /// The base class for test suites. + /// The base class for test suites. /// public abstract class TestBase : IDisposable { /// - /// Create a new test-suite. + /// Create a new test-suite. /// /// - /// Output for the current test. + /// Output for the current test. /// protected TestBase(ITestOutputHelper testOutput) { @@ -45,8 +44,8 @@ protected TestBase(ITestOutputHelper testOutput) // Ugly hack to get access to the current test. CurrentTest = (ITest) TestOutput.GetType() - .GetField("test", BindingFlags.NonPublic | BindingFlags.Instance) - .GetValue(TestOutput); + .GetField("test", BindingFlags.NonPublic | BindingFlags.Instance) + .GetValue(TestOutput); Assert.True(CurrentTest != null, "Cannot retrieve current test from ITestOutputHelper."); @@ -58,15 +57,12 @@ protected TestBase(ITestOutputHelper testOutput) } /// - /// Finaliser for . + /// Finaliser for . /// - ~TestBase() - { - Dispose(false); - } + ~TestBase() => Dispose(false); /// - /// Dispose of resources being used by the test suite. + /// Dispose of resources being used by the test suite. /// public void Dispose() { @@ -75,10 +71,10 @@ public void Dispose() } /// - /// Dispose of resources being used by the test suite. + /// Dispose of resources being used by the test suite. /// /// - /// Explicit disposal? + /// Explicit disposal? /// protected virtual void Dispose(bool disposing) { @@ -97,42 +93,42 @@ protected virtual void Dispose(bool disposing) } /// - /// A representing resources used by the test. + /// A representing resources used by the test. /// protected CompositeDisposable Disposal { get; } = new CompositeDisposable(); /// - /// Output for the current test. + /// Output for the current test. /// protected ITestOutputHelper TestOutput { get; } /// - /// A representing the current test. + /// A representing the current test. /// protected ITest CurrentTest { get; } /// - /// The Serilog logger for the current test. + /// The Serilog logger for the current test. /// protected ILoggerFactory LoggerFactory { get; } /// - /// The Serilog logger for the current test. + /// The Serilog logger for the current test. /// protected ILogger Log { get; } /// - /// The logging level for the current test. + /// The logging level for the current test. /// protected virtual LogLevel LogLevel => LogLevel.Information; /// - /// Is the test running on Windows? + /// Is the test running on Windows? /// protected virtual bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); /// - /// Is the test running on a Unix-like operating system? + /// Is the test running on a Unix-like operating system? /// protected virtual bool IsUnix => RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); } diff --git a/test/Client.Tests/TestRequest.cs b/test/Client.Tests/TestRequest.cs index b6e9cfc20..99b27ca1c 100644 --- a/test/Client.Tests/TestRequest.cs +++ b/test/Client.Tests/TestRequest.cs @@ -1,12 +1,12 @@ namespace OmniSharp.Extensions.LanguageServer.Client.Tests { /// - /// A test request. + /// A test request. /// - class TestRequest + internal class TestRequest { /// - /// A test value for the request. + /// A test value for the request. /// public int Value { get; set; } } diff --git a/test/Client.Tests/TestResponse.cs b/test/Client.Tests/TestResponse.cs index bbbab1d39..a419de6ae 100644 --- a/test/Client.Tests/TestResponse.cs +++ b/test/Client.Tests/TestResponse.cs @@ -1,12 +1,12 @@ namespace OmniSharp.Extensions.LanguageServer.Client.Tests { /// - /// A test response. + /// A test response. /// - class TestResponse + internal class TestResponse { /// - /// A test value for the response. + /// A test value for the response. /// public string Value { get; set; } } diff --git a/test/Dap.Tests/DapOutputHandlerTests.cs b/test/Dap.Tests/DapOutputHandlerTests.cs index 4e69610aa..65338dc62 100644 --- a/test/Dap.Tests/DapOutputHandlerTests.cs +++ b/test/Dap.Tests/DapOutputHandlerTests.cs @@ -9,6 +9,7 @@ using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Client; +using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.JsonRpc.Server.Messages; using Xunit; @@ -29,8 +30,10 @@ public async Task ShouldSerializeResponses() var pipe = new Pipe(new PipeOptions()); using var handler = NewHandler(pipe.Writer); - var value = new OutgoingResponse(1, new object(), - new OmniSharp.Extensions.JsonRpc.Server.Request(1, "command", new JObject())); + var value = new OutgoingResponse( + 1, new object(), + new Request(1, "command", new JObject()) + ); handler.Send(value); await handler.WriteAndFlush(); @@ -49,7 +52,7 @@ public async Task ShouldSerializeNotifications() var pipe = new Pipe(new PipeOptions()); using var handler = NewHandler(pipe.Writer); - var value = new OmniSharp.Extensions.JsonRpc.Client.OutgoingNotification() { + var value = new OutgoingNotification { Method = "method", Params = new object() }; @@ -71,7 +74,7 @@ public async Task ShouldSerializeRequests() var pipe = new Pipe(new PipeOptions()); using var handler = NewHandler(pipe.Writer); - var value = new OmniSharp.Extensions.JsonRpc.Client.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 af5ebea36..0e23d4af2 100644 --- a/test/Dap.Tests/DebugAdapterSpecifictionRecieverTests.cs +++ b/test/Dap.Tests/DebugAdapterSpecifictionRecieverTests.cs @@ -1,9 +1,7 @@ using System.Linq; using FluentAssertions; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.DebugAdapter.Protocol; -using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.JsonRpc.Server.Messages; using Xunit; @@ -29,18 +27,18 @@ public void ShouldRespond_AsExpected(string json, Renor[] request) var response = result[i]; inSerializer.SerializeObject(response) - .Should().Be(outSerializer.SerializeObject(r)); + .Should().Be(outSerializer.SerializeObject(r)); } } - class SpecificationMessages : TheoryData + private class SpecificationMessages : TheoryData { public SpecificationMessages() { Add( @"{""seq"": ""0"", ""type"": ""request"", ""command"": ""attach"", ""arguments"": { ""__restart"": 3 }}", new Renor[] { - new Request(0, "attach", new JObject() {{"__restart", 3}}) + new Request(0, "attach", new JObject { { "__restart", 3 } }) } ); @@ -54,7 +52,7 @@ public SpecificationMessages() Add( @"{""seq"": ""0"", ""type"": ""event"", ""event"": ""breakpoint"", ""body"": { ""reason"": ""new"" }}", new Renor[] { - new Notification("breakpoint", new JObject() {{"reason", "new"}}), + new Notification("breakpoint", new JObject { { "reason", "new" } }), } ); @@ -98,7 +96,8 @@ public SpecificationMessages() @"[1]", new Renor[] { new InvalidRequest(string.Empty, "Not an object") - }); + } + ); } } @@ -111,7 +110,7 @@ public void Should_ValidateInvalidMessages(string json, bool expected) result.Should().Be(expected); } - class InvalidMessages : TheoryData + private class InvalidMessages : TheoryData { public InvalidMessages() { diff --git a/test/Dap.Tests/EventingTests.cs b/test/Dap.Tests/EventingTests.cs index effcbdc55..ca80fc2fc 100644 --- a/test/Dap.Tests/EventingTests.cs +++ b/test/Dap.Tests/EventingTests.cs @@ -5,7 +5,6 @@ using NSubstitute; using OmniSharp.Extensions.DebugAdapter.Client; using OmniSharp.Extensions.DebugAdapter.Protocol.Client; -using OmniSharp.Extensions.DebugAdapter.Protocol.Events; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; using OmniSharp.Extensions.DebugAdapter.Protocol.Server; using OmniSharp.Extensions.DebugAdapter.Server; @@ -15,7 +14,6 @@ using Serilog.Events; using Xunit; using Xunit.Abstractions; -using OnDebugAdapterServerInitializedDelegate = OmniSharp.Extensions.DebugAdapter.Protocol.Server.OnDebugAdapterServerInitializedDelegate; namespace Dap.Tests { @@ -57,13 +55,14 @@ public async Task Initialize_Delegate_Is_Supported() public async Task Initialize_Interface_Is_Supported_On_Handlers() { var onDebugAdapterClientInitialize = - Substitute.For(new Type[] {typeof(IOnDebugAdapterClientInitialize), typeof(RunInTerminalHandler)}, Array.Empty()) as IOnDebugAdapterClientInitialize; + Substitute.For(new[] { typeof(IOnDebugAdapterClientInitialize), typeof(RunInTerminalHandler) }, Array.Empty()) as IOnDebugAdapterClientInitialize; var onDebugAdapterServerInitialize = - Substitute.For(new Type[] {typeof(IOnDebugAdapterServerInitialize), typeof(CompletionsHandler)}, Array.Empty()) as + Substitute.For(new[] { typeof(IOnDebugAdapterServerInitialize), typeof(CompletionsHandler) }, Array.Empty()) as IOnDebugAdapterServerInitialize; var (client, server) = await Initialize( options => options.AddHandler(onDebugAdapterClientInitialize as IJsonRpcHandler), - options => options.AddHandler(onDebugAdapterServerInitialize as IJsonRpcHandler)); + options => options.AddHandler(onDebugAdapterServerInitialize as IJsonRpcHandler) + ); await onDebugAdapterClientInitialize.Received(1).OnInitialize(client, client.ClientSettings, Arg.Any()); await onDebugAdapterServerInitialize.Received(1).OnInitialize(server, server.ClientSettings, Arg.Any()); @@ -101,13 +100,14 @@ public async Task Initialized_Delegate_Is_Supported() public async Task Initialized_Interface_Is_Supported_On_Handlers() { var onDebugAdapterClientInitialized = - Substitute.For(new Type[] {typeof(IOnDebugAdapterClientInitialized), typeof(RunInTerminalHandler)}, Array.Empty()) as IOnDebugAdapterClientInitialized; + Substitute.For(new[] { typeof(IOnDebugAdapterClientInitialized), typeof(RunInTerminalHandler) }, Array.Empty()) as IOnDebugAdapterClientInitialized; var onDebugAdapterServerInitialized = - Substitute.For(new Type[] {typeof(IOnDebugAdapterServerInitialized), typeof(CompletionsHandler)}, Array.Empty()) as + Substitute.For(new[] { typeof(IOnDebugAdapterServerInitialized), typeof(CompletionsHandler) }, Array.Empty()) as IOnDebugAdapterServerInitialized; var (client, server) = await Initialize( options => options.AddHandler(onDebugAdapterClientInitialized as IJsonRpcHandler), - options => options.AddHandler(onDebugAdapterServerInitialized as IJsonRpcHandler)); + options => options.AddHandler(onDebugAdapterServerInitialized as IJsonRpcHandler) + ); await onDebugAdapterClientInitialized.Received(1).OnInitialized(client, client.ClientSettings, client.ServerSettings, Arg.Any()); await onDebugAdapterServerInitialized.Received(1).OnInitialized(server, server.ClientSettings, server.ServerSettings, Arg.Any()); @@ -145,13 +145,14 @@ public async Task Started_Delegate_Is_Supported() public async Task Started_Interface_Is_Supported_On_Handlers() { var onDebugAdapterClientStarted = - Substitute.For(new Type[] {typeof(IOnDebugAdapterClientStarted), typeof(RunInTerminalHandler)}, Array.Empty()) as IOnDebugAdapterClientStarted; + Substitute.For(new[] { typeof(IOnDebugAdapterClientStarted), typeof(RunInTerminalHandler) }, Array.Empty()) as IOnDebugAdapterClientStarted; var onDebugAdapterServerStarted = - Substitute.For(new Type[] {typeof(IOnDebugAdapterServerStarted), typeof(CompletionsHandler)}, Array.Empty()) as + Substitute.For(new[] { typeof(IOnDebugAdapterServerStarted), typeof(CompletionsHandler) }, Array.Empty()) as IOnDebugAdapterServerStarted; var (client, server) = await Initialize( options => options.AddHandler(onDebugAdapterClientStarted as IJsonRpcHandler), - options => options.AddHandler(onDebugAdapterServerStarted as IJsonRpcHandler)); + options => options.AddHandler(onDebugAdapterServerStarted as IJsonRpcHandler) + ); await onDebugAdapterClientStarted.Received(1).OnStarted(client, Arg.Any()); await onDebugAdapterServerStarted.Received(1).OnStarted(server, Arg.Any()); diff --git a/test/Dap.Tests/FoundationTests.cs b/test/Dap.Tests/FoundationTests.cs index 33ee7eff5..a283f6557 100644 --- a/test/Dap.Tests/FoundationTests.cs +++ b/test/Dap.Tests/FoundationTests.cs @@ -25,17 +25,11 @@ public class FoundationTests { private readonly ILogger _logger; - public FoundationTests(ITestOutputHelper outputHelper) - { - this._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 { @@ -43,7 +37,12 @@ public ActionDelegateData() { { var baseOptions = new DebugAdapterServerOptions().WithPipe(new Pipe()); - void BaseDelegate(DebugAdapterServerOptions o) => o.WithPipe(new Pipe()); + + void BaseDelegate(DebugAdapterServerOptions o) + { + o.WithPipe(new Pipe()); + } + var serviceProvider = new ServiceCollection().BuildServiceProvider(); Add(new ActionDelegate("create (server): options", () => DebugAdapterServer.Create(baseOptions))); Add(new ActionDelegate("create (server): options, serviceProvider", () => DebugAdapterServer.Create(baseOptions, serviceProvider))); @@ -52,16 +51,29 @@ public ActionDelegateData() Add(new ActionDelegate("from (server): options", () => DebugAdapterServer.From(baseOptions))); Add(new ActionDelegate("from (server): options, cancellationToken", () => DebugAdapterServer.From(baseOptions, CancellationToken.None))); - Add(new ActionDelegate("from (server): options, serviceProvider, cancellationToken", () => DebugAdapterServer.From(baseOptions, serviceProvider, CancellationToken.None))); + Add( + new ActionDelegate( + "from (server): options, serviceProvider, cancellationToken", () => DebugAdapterServer.From(baseOptions, serviceProvider, CancellationToken.None) + ) + ); Add(new ActionDelegate("from (server): options, serviceProvider", () => DebugAdapterServer.From(baseOptions, serviceProvider))); Add(new ActionDelegate("from (server): action", () => DebugAdapterServer.From(BaseDelegate))); Add(new ActionDelegate("from (server): action, cancellationToken", () => DebugAdapterServer.From(BaseDelegate, CancellationToken.None))); - Add(new ActionDelegate("from (server): action, serviceProvider, cancellationToken", () => DebugAdapterServer.From(BaseDelegate, serviceProvider, CancellationToken.None))); + Add( + new ActionDelegate( + "from (server): action, serviceProvider, cancellationToken", () => DebugAdapterServer.From(BaseDelegate, serviceProvider, CancellationToken.None) + ) + ); Add(new ActionDelegate("from (server): action, serviceProvider", () => DebugAdapterServer.From(BaseDelegate, serviceProvider))); } { var baseOptions = new DebugAdapterClientOptions().WithPipe(new Pipe()); - void BaseDelegate(DebugAdapterClientOptions o) => o.WithPipe(new Pipe()); + + void BaseDelegate(DebugAdapterClientOptions o) + { + o.WithPipe(new Pipe()); + } + var serviceProvider = new ServiceCollection().BuildServiceProvider(); Add(new ActionDelegate("create (client): options", () => DebugAdapterClient.Create(baseOptions))); Add(new ActionDelegate("create (client): options, serviceProvider", () => DebugAdapterClient.Create(baseOptions, serviceProvider))); @@ -70,11 +82,19 @@ public ActionDelegateData() Add(new ActionDelegate("from (client): options", () => DebugAdapterClient.From(baseOptions))); Add(new ActionDelegate("from (client): options, cancellationToken", () => DebugAdapterClient.From(baseOptions, CancellationToken.None))); - Add(new ActionDelegate("from (client): options, serviceProvider, cancellationToken", () => DebugAdapterClient.From(baseOptions, serviceProvider, CancellationToken.None))); + Add( + new ActionDelegate( + "from (client): options, serviceProvider, cancellationToken", () => DebugAdapterClient.From(baseOptions, serviceProvider, CancellationToken.None) + ) + ); Add(new ActionDelegate("from (client): options, serviceProvider", () => DebugAdapterClient.From(baseOptions, serviceProvider))); Add(new ActionDelegate("from (client): action", () => DebugAdapterClient.From(BaseDelegate))); Add(new ActionDelegate("from (client): action, cancellationToken", () => DebugAdapterClient.From(BaseDelegate, CancellationToken.None))); - Add(new ActionDelegate("from (client): action, serviceProvider, cancellationToken", () => DebugAdapterClient.From(BaseDelegate, serviceProvider, CancellationToken.None))); + Add( + new ActionDelegate( + "from (client): action, serviceProvider, cancellationToken", () => DebugAdapterClient.From(BaseDelegate, serviceProvider, CancellationToken.None) + ) + ); Add(new ActionDelegate("from (client): action, serviceProvider", () => DebugAdapterClient.From(BaseDelegate, serviceProvider))); } } @@ -88,7 +108,7 @@ public class ActionDelegate public ActionDelegate(string name, Action method) { _name = name; - this.Method = method; + Method = method; } public override string ToString() => _name; @@ -96,19 +116,15 @@ public ActionDelegate(string name, Action method) [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"); - } + .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"); - } + .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))] @@ -145,90 +161,100 @@ public void HandlersShouldAbstractClass(IHandlerTypeDescriptor 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"); } } [Theory(DisplayName = "Handler extension method classes with appropriately named methods")] [ClassData(typeof(TypeHandlerExtensionData))] - public void HandlersShouldExtensionMethodClassWithMethods(IHandlerTypeDescriptor descriptor, string onMethodName, string sendMethodName, - Type extensionClass, string extensionClassName) + public void HandlersShouldExtensionMethodClassWithMethods( + IHandlerTypeDescriptor descriptor, string onMethodName, string sendMethodName, + Type extensionClass, string extensionClassName + ) { // This test requires a refactor, the delegating handlers have been removed and replaced by shared implementations // TODO: // * Check for IPartialItem(s)<> extension methods // * Also update events to have a nicer fire and forget abstract class - _logger.LogInformation("Handler: {Type} {Extension} {ExtensionName} {OnMethod} {SendMethod}", descriptor.HandlerType, - extensionClass, extensionClassName, onMethodName, sendMethodName); + _logger.LogInformation( + "Handler: {Type} {Extension} {ExtensionName} {OnMethod} {SendMethod}", descriptor.HandlerType, + extensionClass, extensionClassName, onMethodName, sendMethodName + ); 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() - .BeTrue($"{descriptor.HandlerType.FullName} is missing event extension methods named {onMethodName}"); + .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() - .BeTrue($"{descriptor.HandlerType.FullName} is missing execute extension methods named {sendMethodName}"); + .BeTrue($"{descriptor.HandlerType.FullName} is missing execute extension methods named {sendMethodName}"); var registries = extensionClass.GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(z => z.Name == onMethodName || z.Name == sendMethodName) - .Select(z => z.GetParameters()[0].ParameterType) - .Distinct() - .ToHashSet(); - - registries.Should().HaveCount(descriptor.Direction == Direction.Bidirectional ? 4 : 2, - $"{descriptor.HandlerType.FullName} there should be methods for both handing the event and sending the event"); + .Where(z => z.Name == onMethodName || z.Name == sendMethodName) + .Select(z => z.GetParameters()[0].ParameterType) + .Distinct() + .ToHashSet(); + + registries.Should().HaveCount( + descriptor.Direction == Direction.Bidirectional ? 4 : 2, + $"{descriptor.HandlerType.FullName} there should be methods for both handing the event and sending the event" + ); } [Theory(DisplayName = "Handler all expected extensions methods based on method direction")] [ClassData(typeof(TypeHandlerExtensionData))] - public void HandlersShouldHaveExpectedExtensionMethodsBasedOnDirection(IHandlerTypeDescriptor descriptor, string onMethodName, string sendMethodName, - Type extensionClass, string extensionClassName) + public void HandlersShouldHaveExpectedExtensionMethodsBasedOnDirection( + IHandlerTypeDescriptor descriptor, string onMethodName, string sendMethodName, + Type extensionClass, string extensionClassName + ) { - _logger.LogInformation("Handler: {Type} {Extension} {ExtensionName} {OnMethod} {SendMethod}", descriptor.HandlerType, - extensionClass, extensionClassName, onMethodName, sendMethodName); + _logger.LogInformation( + "Handler: {Type} {Extension} {ExtensionName} {OnMethod} {SendMethod}", descriptor.HandlerType, + extensionClass, extensionClassName, onMethodName, sendMethodName + ); var onMethodRegistries = extensionClass.GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(z => z.Name == onMethodName) - .Select(z => z.GetParameters()[0].ParameterType) - .Distinct() - .ToHashSet(); + .Where(z => z.Name == onMethodName) + .Select(z => z.GetParameters()[0].ParameterType) + .Distinct() + .ToHashSet(); var sendMethodRegistries = extensionClass.GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(z => z.Name == sendMethodName) - .Select(z => z.GetParameters()[0].ParameterType) - .Distinct() - .ToHashSet(); + .Where(z => z.Name == sendMethodName) + .Select(z => z.GetParameters()[0].ParameterType) + .Distinct() + .ToHashSet(); 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.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"))}, + 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"))}, + { ( "Server", info => info.ParameterType.Name.EndsWith("Client") ), ( "Client", info => info.ParameterType.Name.EndsWith("Server") ) }, _ => throw new NotImplementedException(descriptor.HandlerType.FullName) }; foreach (var item in expectedEventRegistries) { extensionClass.GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(z => z.Name == onMethodName) - .Where(z => item.matcher(z.GetParameters()[0])) - .Should().HaveCountGreaterOrEqualTo(1, $"{descriptor.HandlerType.FullName} is missing a registry implementation for {item.type}"); + .Where(z => z.Name == onMethodName) + .Where(z => item.matcher(z.GetParameters()[0])) + .Should().HaveCountGreaterOrEqualTo(1, $"{descriptor.HandlerType.FullName} is missing a registry implementation for {item.type}"); } foreach (var item in expectedRequestHandlers) { extensionClass.GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(z => z.Name == sendMethodName) - .Where(z => item.matcher(z.GetParameters()[0])) - .Should().HaveCountGreaterOrEqualTo(1, $"{descriptor.HandlerType.FullName} is missing a request implementation for {item.type}"); + .Where(z => z.Name == sendMethodName) + .Where(z => item.matcher(z.GetParameters()[0])) + .Should().HaveCountGreaterOrEqualTo(1, $"{descriptor.HandlerType.FullName} is missing a request implementation for {item.type}"); } { @@ -236,7 +262,7 @@ public void HandlersShouldHaveExpectedExtensionMethodsBasedOnDirection(IHandlerT Func ForParameter(int index, Func m) { - return (info) => m(info.GetParameters()[index]); + return info => m(info.GetParameters()[index]); } var containsCancellationToken = ForParameter(1, info => info.ParameterType.GetGenericArguments().Reverse().Take(2).Any(x => x == typeof(CancellationToken))); @@ -281,15 +307,17 @@ Func ForParameter(int index, Func m) } } - class MethodMatcher + private class MethodMatcher { private readonly IEnumerable _registries; private readonly IHandlerTypeDescriptor _descriptor; private readonly Type _extensionClass; private readonly string _methodName; - public MethodMatcher(IEnumerable registries, - IHandlerTypeDescriptor descriptor, Type extensionClass, string methodName) + public MethodMatcher( + IEnumerable registries, + IHandlerTypeDescriptor descriptor, Type extensionClass, string methodName + ) { _registries = registries; _descriptor = descriptor; @@ -302,41 +330,55 @@ public void Match(string description, params Func[] matchers) foreach (var registry in _registries) { var methods = _extensionClass.GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(z => z.Name == _methodName) - .Where(z => matchers.All(matcher => matcher(z))) - .ToHashSet(); - methods.Count.Should().BeGreaterThan(0, - $"{_descriptor.HandlerType.FullName} missing extension with parameter type {description} method for {registry.FullName}"); + .Where(z => z.Name == _methodName) + .Where(z => matchers.All(matcher => matcher(z))) + .ToHashSet(); + methods.Count.Should().BeGreaterThan( + 0, + $"{_descriptor.HandlerType.FullName} missing extension with parameter type {description} method for {registry.FullName}" + ); foreach (var method in methods) { if (method.Name == GetOnMethodName(_descriptor)) { - var registrySub = Substitute.For(new Type[] {method.GetParameters()[0].ParameterType}, - Array.Empty()); + var registrySub = Substitute.For( + new[] { method.GetParameters()[0].ParameterType }, + Array.Empty() + ); - method.Invoke(null, + method.Invoke( + null, new[] { - registrySub, Substitute.For(new Type[] {method.GetParameters()[1].ParameterType}, Array.Empty()), - }.Concat(method.GetParameters().Skip(2).Select(z => - !z.ParameterType.IsGenericType - ? Activator.CreateInstance(z.ParameterType) - : Substitute.For(new Type[] {z.ParameterType}, Array.Empty())) - ) - .ToArray()); + registrySub, Substitute.For(new[] { method.GetParameters()[1].ParameterType }, Array.Empty()), + }.Concat( + method.GetParameters().Skip(2).Select( + z => + !z.ParameterType.IsGenericType + ? Activator.CreateInstance(z.ParameterType) + : Substitute.For(new[] { z.ParameterType }, Array.Empty()) + ) + ) + .ToArray() + ); registrySub.Received().ReceivedCalls() - .Any(z => z.GetMethodInfo().Name == nameof(IJsonRpcHandlerRegistry.AddHandler) && z.GetArguments().Length == 3 && - z.GetArguments()[0].Equals(_descriptor.Method)).Should() - .BeTrue($"{_descriptor.HandlerType.Name} {description} should have the correct method."); + .Any( + z => z.GetMethodInfo().Name == nameof(IJsonRpcHandlerRegistry.AddHandler) && z.GetArguments().Length == 3 && + z.GetArguments()[0].Equals(_descriptor.Method) + ).Should() + .BeTrue($"{_descriptor.HandlerType.Name} {description} should have the correct method."); } if (_descriptor.IsRequest && method.Name == GetSendMethodName(_descriptor)) { - method.GetParameters().Last().ParameterType.Should().Be(typeof(CancellationToken), - $"{_descriptor.HandlerType.Name} {description} send method must have optional cancellation token"); + method.GetParameters().Last().ParameterType.Should().Be( + typeof(CancellationToken), + $"{_descriptor.HandlerType.Name} {description} send method must have optional cancellation token" + ); method.GetParameters().Last().IsOptional.Should().BeTrue( - $"{_descriptor.HandlerType.Name} {description} send method must have optional cancellation token"); + $"{_descriptor.HandlerType.Name} {description} send method must have optional cancellation token" + ); } } } @@ -348,9 +390,13 @@ public class ParamsShouldHaveMethodAttributeData : TheoryData public ParamsShouldHaveMethodAttributeData() { foreach (var type in typeof(IDataBreakpointInfoHandler).Assembly.ExportedTypes - .Where(z => z.IsClass && !z.IsAbstract && z.GetInterfaces().Any(z => - z.IsGenericType && - typeof(IRequest<>).IsAssignableFrom(z.GetGenericTypeDefinition())))) + .Where( + z => z.IsClass && !z.IsAbstract && z.GetInterfaces().Any( + z => + z.IsGenericType && + typeof(IRequest<>).IsAssignableFrom(z.GetGenericTypeDefinition()) + ) + )) { Add(type); } @@ -362,7 +408,7 @@ public class HandlersShouldHaveMethodAttributeData : TheoryData public HandlersShouldHaveMethodAttributeData() { foreach (var type in typeof(IDataBreakpointInfoHandler).Assembly.ExportedTypes - .Where(z => z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z))) + .Where(z => z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z))) { if (type.IsGenericTypeDefinition && !MethodAttribute.AllFrom(type).Any()) continue; Add(type); @@ -375,7 +421,7 @@ public class HandlersShouldAbstractClassData : TheoryData public HandlersShouldAbstractClassData() { foreach (var type in typeof(IDataBreakpointInfoHandler).Assembly.ExportedTypes - .Where(z => z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z))) + .Where(z => z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z))) { if (type.IsGenericTypeDefinition && !MethodAttribute.AllFrom(type).Any()) continue; Add(type); @@ -403,8 +449,8 @@ public static Type GetHandlerInterface(Type type) { if (IsValidInterface(type)) return type; return type?.GetTypeInfo() - .ImplementedInterfaces - .First(IsValidInterface); + .ImplementedInterfaces + .First(IsValidInterface); } @@ -413,7 +459,8 @@ public class TypeHandlerData : TheoryData public TypeHandlerData() { foreach (var type in typeof(CompletionsArguments).Assembly.ExportedTypes.Where( - z => z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z))) + z => z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z) + )) { if (type.IsGenericTypeDefinition && !MethodAttribute.AllFrom(type).Any()) continue; if (type == typeof(IProgressStartHandler) || type == typeof(IProgressUpdateHandler) || type == typeof(IProgressEndHandler)) continue; @@ -428,7 +475,7 @@ public class TypeHandlerExtensionData : TheoryData z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z))) + .Where(z => z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z))) { if (type.IsGenericTypeDefinition && !MethodAttribute.AllFrom(type).Any()) continue; if (type == typeof(IProgressStartHandler) || type == typeof(IProgressUpdateHandler) || type == typeof(IProgressEndHandler)) continue; @@ -445,31 +492,23 @@ public TypeHandlerExtensionData() } } - private static string GetExtensionClassName(IHandlerTypeDescriptor descriptor) - { - return SpecialCasedHandlerName(descriptor) + "Extensions"; - ; - } + private static string GetExtensionClassName(IHandlerTypeDescriptor descriptor) => SpecialCasedHandlerName(descriptor) + "Extensions"; - private static string SpecialCasedHandlerName(IHandlerTypeDescriptor descriptor) - { - return new Regex(@"(\w+(?:\`\d)?)$") - .Replace(descriptor.HandlerType.Name ?? string.Empty, - descriptor.HandlerType.Name.Substring(1, descriptor.HandlerType.Name.IndexOf("Handler", StringComparison.Ordinal) - 1)) - ; - } + private static string SpecialCasedHandlerName(IHandlerTypeDescriptor descriptor) => + new Regex(@"(\w+(?:\`\d)?)$") + .Replace( + descriptor.HandlerType.Name ?? string.Empty, + descriptor.HandlerType.Name.Substring(1, descriptor.HandlerType.Name.IndexOf("Handler", StringComparison.Ordinal) - 1) + ); private static Type GetExtensionClass(IHandlerTypeDescriptor descriptor) { var name = GetExtensionClassName(descriptor); return descriptor.HandlerType.Assembly.GetExportedTypes() - .FirstOrDefault(z => z.IsClass && z.IsAbstract && (z.Name == name || z.Name == name + "Base")); + .FirstOrDefault(z => z.IsClass && z.IsAbstract && ( z.Name == name || z.Name == name + "Base" )); } - private static string GetOnMethodName(IHandlerTypeDescriptor descriptor) - { - return "On" + SpecialCasedHandlerName(descriptor); - } + private static string GetOnMethodName(IHandlerTypeDescriptor descriptor) => "On" + SpecialCasedHandlerName(descriptor); private static string GetSendMethodName(IHandlerTypeDescriptor descriptor) { diff --git a/test/Dap.Tests/Integration/ConnectionAndDisconnectionTests.cs b/test/Dap.Tests/Integration/ConnectionAndDisconnectionTests.cs index 7ec756049..eda469436 100644 --- a/test/Dap.Tests/Integration/ConnectionAndDisconnectionTests.cs +++ b/test/Dap.Tests/Integration/ConnectionAndDisconnectionTests.cs @@ -14,9 +14,10 @@ namespace Dap.Tests.Integration { public class ConnectionAndDisconnectionTests : DebugAdapterProtocolTestBase { - public ConnectionAndDisconnectionTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions() - .ConfigureForXUnit(outputHelper) - .WithTestTimeout(TimeSpan.FromSeconds(20)) + public ConnectionAndDisconnectionTests(ITestOutputHelper outputHelper) : base( + new JsonRpcTestOptions() + .ConfigureForXUnit(outputHelper) + .WithTestTimeout(TimeSpan.FromSeconds(20)) ) { } @@ -83,24 +84,28 @@ public async Task Client_Should_Support_Links() private void ConfigureClient(DebugAdapterClientOptions options) { - options.OnRequest("keepalive", (ct) => Task.FromResult(true)); + options.OnRequest("keepalive", ct => Task.FromResult(true)); options.WithLink("keepalive", "ka"); options.WithLink("throw", "t"); - options.OnRequest("throw", async ct => { - throw new NotSupportedException(); - return Task.CompletedTask; - }); + options.OnRequest( + "throw", async ct => { + throw new NotSupportedException(); + return Task.CompletedTask; + } + ); } private void ConfigureServer(DebugAdapterServerOptions options) { - options.OnRequest("keepalive", (ct) => Task.FromResult(true)); + options.OnRequest("keepalive", ct => Task.FromResult(true)); options.WithLink("keepalive", "ka"); options.WithLink("throw", "t"); - options.OnRequest("throw", async ct => { - throw new NotSupportedException(); - return Task.CompletedTask; - }); + options.OnRequest( + "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 d3c373256..77ffafade 100644 --- a/test/Dap.Tests/Integration/CustomRequestsTests.cs +++ b/test/Dap.Tests/Integration/CustomRequestsTests.cs @@ -7,7 +7,6 @@ using NSubstitute; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; using OmniSharp.Extensions.DebugAdapter.Testing; -using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Testing; using Xunit; using Xunit.Abstractions; @@ -16,7 +15,9 @@ namespace Dap.Tests.Integration { public class CustomRequestsTests : DebugAdapterProtocolTestBase { - public CustomRequestsTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper)) { } + public CustomRequestsTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper)) + { + } [Fact] public async Task Should_Support_Custom_Attach_Request_Using_Base_Class() @@ -24,11 +25,13 @@ public async Task Should_Support_Custom_Attach_Request_Using_Base_Class() var fake = Substitute.For>(); var (client, server) = await Initialize(options => { }, options => { options.AddHandler(fake); }); - await client.RequestAttach(new CustomAttachRequestArguments() { - ComputerName = "computer", - RunspaceId = "1234", - ProcessId = "4321" - }); + await client.RequestAttach( + new CustomAttachRequestArguments { + ComputerName = "computer", + RunspaceId = "1234", + ProcessId = "4321" + } + ); var call = fake.ReceivedCalls().Single(); var args = call.GetArguments(); @@ -44,11 +47,13 @@ public async Task Should_Support_Custom_Attach_Request_Receiving_Regular_Request var fake = Substitute.For(); var (client, server) = await Initialize(options => { }, options => { options.AddHandler(fake); }); - await client.RequestAttach(new CustomAttachRequestArguments() { - ComputerName = "computer", - RunspaceId = "1234", - ProcessId = "4321" - }); + await client.RequestAttach( + new CustomAttachRequestArguments { + ComputerName = "computer", + RunspaceId = "1234", + ProcessId = "4321" + } + ); var call = fake.ReceivedCalls().Single(); var args = call.GetArguments(); @@ -64,13 +69,15 @@ public async Task Should_Support_Custom_Attach_Request_Using_Extension_Data_Usin var fake = Substitute.For>(); var (client, server) = await Initialize(options => { }, options => { options.AddHandler(fake); }); - await client.RequestAttach(new AttachRequestArguments() { - ExtensionData = new Dictionary() { - ["ComputerName"] = "computer", - ["RunspaceId"] = "1234", - ["ProcessId"] = "4321" + await client.RequestAttach( + new AttachRequestArguments { + ExtensionData = new Dictionary { + ["ComputerName"] = "computer", + ["RunspaceId"] = "1234", + ["ProcessId"] = "4321" + } } - }); + ); var call = fake.ReceivedCalls().Single(); var args = call.GetArguments(); @@ -86,9 +93,11 @@ public async Task Should_Support_Custom_Launch_Request_Using_Base_Class() var fake = Substitute.For>(); var (client, server) = await Initialize(options => { }, options => { options.AddHandler(fake); }); - await client.RequestLaunch(new CustomLaunchRequestArguments() { - Script = "build.ps1" - }); + await client.RequestLaunch( + new CustomLaunchRequestArguments { + Script = "build.ps1" + } + ); var call = fake.ReceivedCalls().Single(); var args = call.GetArguments(); @@ -102,9 +111,11 @@ public async Task Should_Support_Custom_Launch_Request_Receiving_Regular_Request var fake = Substitute.For(); var (client, server) = await Initialize(options => { }, options => { options.AddHandler(fake); }); - await client.RequestLaunch(new CustomLaunchRequestArguments() { - Script = "build.ps1" - }); + await client.RequestLaunch( + new CustomLaunchRequestArguments { + Script = "build.ps1" + } + ); var call = fake.ReceivedCalls().Single(); var args = call.GetArguments(); @@ -118,11 +129,13 @@ public async Task Should_Support_Custom_Launch_Request_Using_Extension_Data_Base var fake = Substitute.For>(); var (client, server) = await Initialize(options => { }, options => { options.AddHandler(fake); }); - await client.RequestLaunch(new CustomLaunchRequestArguments() { - ExtensionData = new Dictionary() { - ["Script"] = "build.ps1" + await client.RequestLaunch( + new CustomLaunchRequestArguments { + ExtensionData = new Dictionary { + ["Script"] = "build.ps1" + } } - }); + ); var call = fake.ReceivedCalls().Single(); var args = call.GetArguments(); @@ -136,11 +149,13 @@ public async Task Should_Support_Custom_Attach_Request_Using_Delegate() var fake = Substitute.For>>(); var (client, server) = await Initialize(options => { }, options => { options.OnAttach(fake); }); - await client.RequestAttach(new CustomAttachRequestArguments() { - ComputerName = "computer", - RunspaceId = "1234", - ProcessId = "4321" - }); + await client.RequestAttach( + new CustomAttachRequestArguments { + ComputerName = "computer", + RunspaceId = "1234", + ProcessId = "4321" + } + ); var call = fake.ReceivedCalls().Single(); var args = call.GetArguments(); @@ -156,11 +171,13 @@ public async Task Should_Support_Custom_Attach_Request_Receiving_Regular_Request var fake = Substitute.For>>(); var (client, server) = await Initialize(options => { }, options => { options.OnAttach(fake); }); - await client.RequestAttach(new CustomAttachRequestArguments() { - ComputerName = "computer", - RunspaceId = "1234", - ProcessId = "4321" - }); + await client.RequestAttach( + new CustomAttachRequestArguments { + ComputerName = "computer", + RunspaceId = "1234", + ProcessId = "4321" + } + ); var call = fake.ReceivedCalls().Single(); var args = call.GetArguments(); @@ -176,13 +193,15 @@ public async Task Should_Support_Custom_Attach_Request_Using_Extension_Data_Usin var fake = Substitute.For>>(); var (client, server) = await Initialize(options => { }, options => { options.OnAttach(fake); }); - await client.RequestAttach(new AttachRequestArguments() { - ExtensionData = new Dictionary() { - ["ComputerName"] = "computer", - ["RunspaceId"] = "1234", - ["ProcessId"] = "4321" + await client.RequestAttach( + new AttachRequestArguments { + ExtensionData = new Dictionary { + ["ComputerName"] = "computer", + ["RunspaceId"] = "1234", + ["ProcessId"] = "4321" + } } - }); + ); var call = fake.ReceivedCalls().Single(); var args = call.GetArguments(); @@ -198,9 +217,11 @@ public async Task Should_Support_Custom_Launch_Request_Using_Delegate() var fake = Substitute.For>>(); var (client, server) = await Initialize(options => { }, options => { options.OnLaunch(fake); }); - await client.RequestLaunch(new CustomLaunchRequestArguments() { - Script = "build.ps1" - }); + await client.RequestLaunch( + new CustomLaunchRequestArguments { + Script = "build.ps1" + } + ); var call = fake.ReceivedCalls().Single(); var args = call.GetArguments(); @@ -214,9 +235,11 @@ public async Task Should_Support_Custom_Launch_Request_Receiving_Regular_Request var fake = Substitute.For>>(); var (client, server) = await Initialize(options => { }, options => { options.OnLaunch(fake); }); - await client.RequestLaunch(new CustomLaunchRequestArguments() { - Script = "build.ps1" - }); + await client.RequestLaunch( + new CustomLaunchRequestArguments { + Script = "build.ps1" + } + ); var call = fake.ReceivedCalls().Single(); var args = call.GetArguments(); @@ -230,11 +253,13 @@ public async Task Should_Support_Custom_Launch_Request_Using_Extension_Data_Usin var fake = Substitute.For>>(); var (client, server) = await Initialize(options => { }, options => { options.OnLaunch(fake); }); - await client.RequestLaunch(new CustomLaunchRequestArguments() { - ExtensionData = new Dictionary() { - ["Script"] = "build.ps1" + await client.RequestLaunch( + new CustomLaunchRequestArguments { + ExtensionData = new Dictionary { + ["Script"] = "build.ps1" + } } - }); + ); var call = fake.ReceivedCalls().Single(); var args = call.GetArguments(); diff --git a/test/Dap.Tests/Integration/GenericDapServerTests.cs b/test/Dap.Tests/Integration/GenericDapServerTests.cs index b8f0104c0..c56c62729 100644 --- a/test/Dap.Tests/Integration/GenericDapServerTests.cs +++ b/test/Dap.Tests/Integration/GenericDapServerTests.cs @@ -1,4 +1,3 @@ -using System; using System.Threading; using System.Threading.Tasks; using FluentAssertions; @@ -36,9 +35,9 @@ public async Task Supports_Multiple_Handlers_On_A_Single_Class() handler.Count.Should().Be(6); } - class Handler : IStepBackHandler, IStepInTargetsHandler, IStepInHandler, IStepOutHandler, INextHandler, IReverseContinueHandler + private class Handler : IStepBackHandler, IStepInTargetsHandler, IStepInHandler, IStepOutHandler, INextHandler, IReverseContinueHandler { - public int Count { get; set; } = 0; + public int Count { get; set; } public Task Handle(StepBackArguments request, CancellationToken cancellationToken) { diff --git a/test/Dap.Tests/Integration/ProgressTests.cs b/test/Dap.Tests/Integration/ProgressTests.cs index 1a71e5902..8cff79965 100644 --- a/test/Dap.Tests/Integration/ProgressTests.cs +++ b/test/Dap.Tests/Integration/ProgressTests.cs @@ -7,7 +7,6 @@ using NSubstitute; using OmniSharp.Extensions.DebugAdapter.Client; using OmniSharp.Extensions.DebugAdapter.Protocol.Events; -using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Server; using OmniSharp.Extensions.DebugAdapter.Testing; using OmniSharp.Extensions.JsonRpc.Testing; @@ -18,15 +17,16 @@ namespace Dap.Tests.Integration { public class ProgressTests : DebugAdapterProtocolTestBase { - public ProgressTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions() - .ConfigureForXUnit(outputHelper) - .WithSettleTimeSpan(TimeSpan.FromSeconds(1)) - .WithSettleTimeout(TimeSpan.FromSeconds(2)) + public ProgressTests(ITestOutputHelper outputHelper) : base( + new JsonRpcTestOptions() + .ConfigureForXUnit(outputHelper) + .WithSettleTimeSpan(TimeSpan.FromSeconds(1)) + .WithSettleTimeout(TimeSpan.FromSeconds(2)) ) { } - class Data + private class Data { public string Value { get; set; } = "Value"; } @@ -39,44 +39,56 @@ public async Task Should_Support_Progress_From_Sever_To_Client() var data = new List(); client.ProgressManager.Progress.Take(1).Switch().Subscribe(x => data.Add(x)); - using var workDoneObserver = server.ProgressManager.Create(new ProgressStartEvent() { - Cancellable = true, - Message = "Begin", - Percentage = 0, - Title = "Work is pending" - }, onComplete: () => new ProgressEndEvent() { - Message = "End" - }); - - workDoneObserver.OnNext(new ProgressUpdateEvent() { - Percentage = 10, - Message = "Report 1" - }); - - workDoneObserver.OnNext(new ProgressUpdateEvent() { - Percentage = 20, - Message = "Report 2" - }); - - workDoneObserver.OnNext(new ProgressUpdateEvent() { - Percentage = 30, - Message = "Report 3" - }); - - workDoneObserver.OnNext(new ProgressUpdateEvent() { - Percentage = 40, - Message = "Report 4" - }); + using var workDoneObserver = server.ProgressManager.Create( + new ProgressStartEvent { + Cancellable = true, + Message = "Begin", + Percentage = 0, + Title = "Work is pending" + }, onComplete: () => new ProgressEndEvent { + Message = "End" + } + ); + + workDoneObserver.OnNext( + new ProgressUpdateEvent { + Percentage = 10, + Message = "Report 1" + } + ); + + workDoneObserver.OnNext( + new ProgressUpdateEvent { + Percentage = 20, + Message = "Report 2" + } + ); + + workDoneObserver.OnNext( + new ProgressUpdateEvent { + Percentage = 30, + Message = "Report 3" + } + ); + + workDoneObserver.OnNext( + new ProgressUpdateEvent { + Percentage = 40, + Message = "Report 4" + } + ); workDoneObserver.OnCompleted(); await SettleNext(); - var results = data.Select(z => z switch { - ProgressStartEvent begin => begin.Message, - ProgressUpdateEvent begin => begin.Message, - ProgressEndEvent begin => begin.Message, - }); + var results = data.Select( + z => z switch { + ProgressStartEvent begin => begin.Message, + ProgressUpdateEvent begin => begin.Message, + ProgressEndEvent begin => begin.Message, + } + ); results.Should().ContainInOrder("Begin", "Report 1", "Report 2", "Report 3", "Report 4", "End"); } @@ -89,55 +101,66 @@ public async Task Should_Support_Cancelling_Progress_From_Server_To_Client_Reque var data = new List(); var sub = client.ProgressManager.Progress.Take(1).Switch().Subscribe(x => data.Add(x)); - using var workDoneObserver = server.ProgressManager.Create(new ProgressStartEvent() { - Cancellable = true, - Message = "Begin", - Percentage = 0, - Title = "Work is pending" - }, onComplete: () => new ProgressEndEvent() { - Message = "End" - }); - - workDoneObserver.OnNext(new ProgressUpdateEvent() { - Percentage = 10, - Message = "Report 1" - }); - - workDoneObserver.OnNext(new ProgressUpdateEvent() { - Percentage = 20, - Message = "Report 2" - }); + using var workDoneObserver = server.ProgressManager.Create( + new ProgressStartEvent { + Cancellable = true, + Message = "Begin", + Percentage = 0, + Title = "Work is pending" + }, onComplete: () => new ProgressEndEvent { + Message = "End" + } + ); + + workDoneObserver.OnNext( + new ProgressUpdateEvent { + Percentage = 10, + Message = "Report 1" + } + ); + + workDoneObserver.OnNext( + new ProgressUpdateEvent { + Percentage = 20, + Message = "Report 2" + } + ); await SettleNext(); sub.Dispose(); - workDoneObserver.OnNext(new ProgressUpdateEvent() { - Percentage = 30, - Message = "Report 3" - }); + workDoneObserver.OnNext( + new ProgressUpdateEvent { + Percentage = 30, + Message = "Report 3" + } + ); - workDoneObserver.OnNext(new ProgressUpdateEvent() { - Percentage = 40, - Message = "Report 4" - }); + workDoneObserver.OnNext( + new ProgressUpdateEvent { + Percentage = 40, + Message = "Report 4" + } + ); workDoneObserver.OnCompleted(); await SettleNext(); - var results = data.Select(z => z switch { - ProgressStartEvent begin => begin.Message, - ProgressUpdateEvent begin => begin.Message, - ProgressEndEvent begin => begin.Message, - }); + var results = data.Select( + z => z switch { + ProgressStartEvent begin => begin.Message, + ProgressUpdateEvent begin => begin.Message, + ProgressEndEvent begin => begin.Message, + } + ); results.Should().ContainInOrder("Begin", "Report 1", "Report 2"); } private void ConfigureClient(DebugAdapterClientOptions options) { - } private void ConfigureServer(DebugAdapterServerOptions options) diff --git a/test/Dap.Tests/Integration/RequestCancellationTests.cs b/test/Dap.Tests/Integration/RequestCancellationTests.cs index c9ef1c2fc..f70d3671d 100644 --- a/test/Dap.Tests/Integration/RequestCancellationTests.cs +++ b/test/Dap.Tests/Integration/RequestCancellationTests.cs @@ -1,14 +1,9 @@ using System; -using System.Collections.Concurrent; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using FluentAssertions; -using Microsoft.CodeAnalysis; -using Microsoft.Extensions.Logging; using NSubstitute; using OmniSharp.Extensions.DebugAdapter.Client; -using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; using OmniSharp.Extensions.DebugAdapter.Server; using OmniSharp.Extensions.DebugAdapter.Testing; @@ -19,7 +14,6 @@ namespace Dap.Tests.Integration { - public class RequestCancellationTests : DebugAdapterProtocolTestBase { public RequestCancellationTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper)) @@ -42,10 +36,12 @@ public async Task Should_Cancel_Pending_Requests() [Fact] public async Task Should_Cancel_Requests_After_Timeout() { - var (client, server) = await Initialize(ConfigureClient, x => { - ConfigureServer(x); - x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(1000)); - }); + var (client, server) = await Initialize( + ConfigureClient, x => { + ConfigureServer(x); + x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(1000)); + } + ); Func> action = () => client.RequestCompletions(new CompletionsArguments()); action.Should().Throw(); @@ -55,12 +51,12 @@ private void ConfigureClient(DebugAdapterClientOptions options) { } - private void ConfigureServer(DebugAdapterServerOptions options) - { - options.OnCompletions(async (x, ct) => { - await Task.Delay(50000, ct); - return new CompletionsResponse(); - }); - } + private void ConfigureServer(DebugAdapterServerOptions options) => + options.OnCompletions( + async (x, ct) => { + await Task.Delay(50000, ct); + return new CompletionsResponse(); + } + ); } } diff --git a/test/Dap.Tests/JsonRpcIntegrationTests.cs b/test/Dap.Tests/JsonRpcIntegrationTests.cs index 94df979eb..a6ed3ba32 100644 --- a/test/Dap.Tests/JsonRpcIntegrationTests.cs +++ b/test/Dap.Tests/JsonRpcIntegrationTests.cs @@ -245,3 +245,6 @@ // } // } // } + + + diff --git a/test/Dap.Tests/LanguageClientServiceCollectionSupportTests.cs b/test/Dap.Tests/LanguageClientServiceCollectionSupportTests.cs index 04398a3b0..b0251046b 100644 --- a/test/Dap.Tests/LanguageClientServiceCollectionSupportTests.cs +++ b/test/Dap.Tests/LanguageClientServiceCollectionSupportTests.cs @@ -18,10 +18,7 @@ public class DebugAdapterClientServiceCollectionSupportTests { private readonly ITestOutputHelper _testOutputHelper; - public DebugAdapterClientServiceCollectionSupportTests(ITestOutputHelper testOutputHelper) - { - _testOutputHelper = testOutputHelper; - } + public DebugAdapterClientServiceCollectionSupportTests(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper; [Fact] public void Inner_Services_Should_Override_Outer_Services() @@ -29,17 +26,19 @@ public void Inner_Services_Should_Override_Outer_Services() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddDebugAdapterClient(options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .WithServices(s => s.AddSingleton(new OutsideService("override"))) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddSingleton(new OutsideService("servername")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddDebugAdapterClient( + options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .WithServices(s => s.AddSingleton(new OutsideService("override"))) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddSingleton(new OutsideService("servername")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); using var server = services.GetRequiredService(); server.GetRequiredService().Value.Should().Be("override"); @@ -51,18 +50,21 @@ public void Handlers_Can_Be_Added_From_The_Service_Collection() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddDebugAdapterClient(options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .WithServices(services => - services.AddJsonRpcHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}) - ); - }) - .AddSingleton(new OutsideService("servername")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddDebugAdapterClient( + options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .WithServices( + services => + services.AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + ); + } + ) + .AddSingleton(new OutsideService("servername")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); using var server = services.GetRequiredService(); server.HandlersManager.Descriptors.Should().Contain(z => z.Handler.GetType() == typeof(Handler)); @@ -74,23 +76,27 @@ public void Should_Bootstrap_Multiple_Servers_Through_Service_Collection() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddDebugAdapterClient("serial", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddDebugAdapterClient("parallel", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Parallel}); - }) - .AddSingleton(new OutsideService("outside")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddDebugAdapterClient( + "serial", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddDebugAdapterClient( + "parallel", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel }); + } + ) + .AddSingleton(new OutsideService("outside")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); var resolver = services.GetRequiredService(); var serialServer = resolver.Get("serial").Should().NotBeNull().And.Subject; @@ -108,63 +114,55 @@ public void Should_Throw_When_Multiple_Servers_Are_Added_And_Attempt_To_Resolve_ cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddDebugAdapterClient("serial", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddDebugAdapterClient("parallel", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Parallel}); - }) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddDebugAdapterClient( + "serial", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddDebugAdapterClient( + "parallel", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel }); + } + ) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); Action a = () => services.GetRequiredService(); a.Should().Throw(); } [Method("outside")] - class Request : IRequest + private class Request : IRequest { } - class Response + private class Response { public string Value { get; } - public Response(string value) - { - Value = value; - } + public Response(string value) => Value = value; } - class Handler : IJsonRpcRequestHandler + private class Handler : IJsonRpcRequestHandler { private readonly OutsideService _outsideService; - public Handler(OutsideService outsideService) - { - _outsideService = outsideService; - } + public Handler(OutsideService outsideService) => _outsideService = outsideService; - public Task Handle(Request request, CancellationToken cancellationToken) - { - return Task.FromResult(new Response(_outsideService.Value)); - } + public Task Handle(Request request, CancellationToken cancellationToken) => Task.FromResult(new Response(_outsideService.Value)); } - class OutsideService + private class OutsideService { - public OutsideService(string value) - { - Value = value; - } + public OutsideService(string value) => Value = value; public string Value { get; } } diff --git a/test/Dap.Tests/LanguageServerServiceCollectionSupportTests.cs b/test/Dap.Tests/LanguageServerServiceCollectionSupportTests.cs index a67cc0932..b660fb76d 100644 --- a/test/Dap.Tests/LanguageServerServiceCollectionSupportTests.cs +++ b/test/Dap.Tests/LanguageServerServiceCollectionSupportTests.cs @@ -18,10 +18,7 @@ public class DebugAdapterServerServiceCollectionSupportTests { private readonly ITestOutputHelper _testOutputHelper; - public DebugAdapterServerServiceCollectionSupportTests(ITestOutputHelper testOutputHelper) - { - _testOutputHelper = testOutputHelper; - } + public DebugAdapterServerServiceCollectionSupportTests(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper; [Fact] public void Inner_Services_Should_Override_Outer_Services() @@ -29,17 +26,19 @@ public void Inner_Services_Should_Override_Outer_Services() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddDebugAdapterServer(options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .WithServices(s => s.AddSingleton(new OutsideService("override"))) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddSingleton(new OutsideService("servername")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddDebugAdapterServer( + options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .WithServices(s => s.AddSingleton(new OutsideService("override"))) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddSingleton(new OutsideService("servername")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); using var server = services.GetRequiredService(); server.GetRequiredService().Value.Should().Be("override"); @@ -51,18 +50,21 @@ public void Handlers_Can_Be_Added_From_The_Service_Collection() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddDebugAdapterServer(options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .WithServices(services => - services.AddJsonRpcHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}) - ); - }) - .AddSingleton(new OutsideService("servername")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddDebugAdapterServer( + options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .WithServices( + services => + services.AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + ); + } + ) + .AddSingleton(new OutsideService("servername")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); using var server = services.GetRequiredService(); server.HandlersManager.Descriptors.Should().Contain(z => z.Handler.GetType() == typeof(Handler)); @@ -74,23 +76,27 @@ public void Should_Bootstrap_Multiple_Servers_Through_Service_Collection() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddDebugAdapterServer("serial", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddDebugAdapterServer("parallel", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Parallel}); - }) - .AddSingleton(new OutsideService("outside")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddDebugAdapterServer( + "serial", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddDebugAdapterServer( + "parallel", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel }); + } + ) + .AddSingleton(new OutsideService("outside")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); var resolver = services.GetRequiredService(); var serialServer = resolver.Get("serial").Should().NotBeNull().And.Subject; @@ -108,63 +114,55 @@ public void Should_Throw_When_Multiple_Servers_Are_Added_And_Attempt_To_Resolve_ cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddDebugAdapterServer("serial", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddDebugAdapterServer("parallel", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Parallel}); - }) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddDebugAdapterServer( + "serial", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddDebugAdapterServer( + "parallel", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel }); + } + ) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); Action a = () => services.GetRequiredService(); a.Should().Throw(); } [Method("outside")] - class Request : IRequest + private class Request : IRequest { } - class Response + private class Response { public string Value { get; } - public Response(string value) - { - Value = value; - } + public Response(string value) => Value = value; } - class Handler : IJsonRpcRequestHandler + private class Handler : IJsonRpcRequestHandler { private readonly OutsideService _outsideService; - public Handler(OutsideService outsideService) - { - _outsideService = outsideService; - } + public Handler(OutsideService outsideService) => _outsideService = outsideService; - public Task Handle(Request request, CancellationToken cancellationToken) - { - return Task.FromResult(new Response(_outsideService.Value)); - } + public Task Handle(Request request, CancellationToken cancellationToken) => Task.FromResult(new Response(_outsideService.Value)); } - class OutsideService + private class OutsideService { - public OutsideService(string value) - { - Value = value; - } + public OutsideService(string value) => Value = value; public string Value { get; } } diff --git a/test/Generation.Tests/GenerationHelpers.cs b/test/Generation.Tests/GenerationHelpers.cs index bfdf265cf..358b60cad 100644 --- a/test/Generation.Tests/GenerationHelpers.cs +++ b/test/Generation.Tests/GenerationHelpers.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Immutable; -using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; @@ -13,8 +12,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Text; -using Microsoft.Extensions.DependencyInjection; -using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.DebugAdapter.Protocol.Client; using OmniSharp.Extensions.JsonRpc.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Server; @@ -28,8 +25,7 @@ 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", @@ -41,8 +37,7 @@ static GenerationHelpers() }; var coreMetaReferences = coreAssemblyNames.Select(x => MetadataReference.CreateFromFile(Path.Combine(coreAssemblyPath, x))); - var otherAssemblies = new[] - { + var otherAssemblies = new[] { typeof(CSharpCompilation).Assembly, typeof(CodeGenerationAttributeAttribute).Assembly, typeof(GenerateHandlerMethodsAttribute).Assembly, @@ -51,8 +46,8 @@ static GenerationHelpers() typeof(ILanguageServerRegistry).Assembly, }; MetadataReferences = coreMetaReferences - .Concat(otherAssemblies.Distinct().Select(x => MetadataReference.CreateFromFile(x.Location))) - .ToImmutableArray(); + .Concat(otherAssemblies.Distinct().Select(x => MetadataReference.CreateFromFile(x.Location))) + .ToImmutableArray(); } internal const string CrLf = "\r\n"; @@ -84,10 +79,7 @@ public static async Task Generate(string source) return generatedText; } - public static string NormalizeToLf(string input) - { - return input.Replace(CrLf, Lf); - } + public static string NormalizeToLf(string input) => input.Replace(CrLf, Lf); public static async Task GenerateAsync(string source) { @@ -98,7 +90,7 @@ public static async Task GenerateAsync(string source) 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"); @@ -113,26 +105,29 @@ public static async Task GenerateAsync(string source) public static Project CreateProject(params string[] sources) { - var projectId = ProjectId.CreateNewId(debugName: TestProjectName); + var projectId = ProjectId.CreateNewId(TestProjectName); var solution = new AdhocWorkspace() - .CurrentSolution - .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp) - .WithProjectCompilationOptions( - projectId, - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) - .WithProjectParseOptions( - projectId, - new CSharpParseOptions(preprocessorSymbols: new[] { "SOMETHING_ACTIVE" })) - .AddMetadataReferences(projectId, MetadataReferences); + .CurrentSolution + .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp) + .WithProjectCompilationOptions( + projectId, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + ) + .WithProjectParseOptions( + projectId, + new CSharpParseOptions(preprocessorSymbols: new[] { "SOMETHING_ACTIVE" }) + ) + .AddMetadataReferences(projectId, MetadataReferences); - int count = 0; + var count = 0; foreach (var source in sources) { var newFileName = DefaultFilePathPrefix + count + "." + CSharpDefaultFileExt; - var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); + var documentId = DocumentId.CreateNewId(projectId, newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source)); count++; } + var project = solution.GetProject(projectId); if (project is null) { diff --git a/test/Generation.Tests/JsonRpcGenerationTests.cs b/test/Generation.Tests/JsonRpcGenerationTests.cs index cac3678ee..fe118e8ee 100644 --- a/test/Generation.Tests/JsonRpcGenerationTests.cs +++ b/test/Generation.Tests/JsonRpcGenerationTests.cs @@ -1,7 +1,4 @@ using System.Threading.Tasks; -using Snapper; -using Snapper.Attributes; -using Snapper.Core; using Xunit; using static Generation.Tests.GenerationHelpers; @@ -656,6 +653,7 @@ public static partial class AttachExtensions }"; await AssertGeneratedAsExpected(source, expected); } + [Fact] public async Task Supports_Allow_Generic_Types() { diff --git a/test/JsonRpc.Tests/AggregateSettlerTests.cs b/test/JsonRpc.Tests/AggregateSettlerTests.cs index cdf7cb721..dc32e69d4 100644 --- a/test/JsonRpc.Tests/AggregateSettlerTests.cs +++ b/test/JsonRpc.Tests/AggregateSettlerTests.cs @@ -202,7 +202,7 @@ public void Should_Complete_After_Final_Request_Timeout(SettlerType settlerTypeA ); } - class AggregateRequestSettlerScheduler + private class AggregateRequestSettlerScheduler { private readonly TestScheduler _testScheduler; private readonly IRequestSettler _clientRequestSettler; @@ -215,71 +215,64 @@ public AggregateRequestSettlerScheduler(TestScheduler testScheduler, IRequestSet _serverRequestSettler = serverRequestSettler; } - public IDisposable ScheduleAbsoluteStart(SettlerType settlerType, long dueTime) - { - return settlerType switch { + public IDisposable ScheduleAbsoluteStart(SettlerType settlerType, long dueTime) => + settlerType switch { SettlerType.Client => _testScheduler.ScheduleAbsolute(dueTime, () => _clientRequestSettler.OnStartRequest()), SettlerType.Server => _testScheduler.ScheduleAbsolute(dueTime, () => _serverRequestSettler.OnStartRequest()), - _ => throw new NotImplementedException() + _ => throw new NotImplementedException() }; - } - public IDisposable ScheduleAbsoluteEnd(SettlerType settlerType, long dueTime) - { - return settlerType switch { + public IDisposable ScheduleAbsoluteEnd(SettlerType settlerType, long dueTime) => + settlerType switch { SettlerType.Client => _testScheduler.ScheduleAbsolute(dueTime, () => _clientRequestSettler.OnEndRequest()), SettlerType.Server => _testScheduler.ScheduleAbsolute(dueTime, () => _serverRequestSettler.OnEndRequest()), - _ => throw new NotImplementedException() + _ => throw new NotImplementedException() }; - } - public IDisposable ScheduleRelativeStart(SettlerType settlerType, long dueTime) - { - return settlerType switch { + public IDisposable ScheduleRelativeStart(SettlerType settlerType, long dueTime) => + settlerType switch { SettlerType.Client => _testScheduler.ScheduleRelative(dueTime, () => _clientRequestSettler.OnStartRequest()), SettlerType.Server => _testScheduler.ScheduleRelative(dueTime, () => _serverRequestSettler.OnStartRequest()), - _ => throw new NotImplementedException() + _ => throw new NotImplementedException() }; - } - public IDisposable ScheduleRelativeEnd(SettlerType settlerType, long dueTime) - { - return settlerType switch { + public IDisposable ScheduleRelativeEnd(SettlerType settlerType, long dueTime) => + settlerType switch { SettlerType.Client => _testScheduler.ScheduleRelative(dueTime, () => _clientRequestSettler.OnEndRequest()), SettlerType.Server => _testScheduler.ScheduleRelative(dueTime, () => _serverRequestSettler.OnEndRequest()), - _ => throw new NotImplementedException() + _ => throw new NotImplementedException() }; - } } private (ISettler settler, AggregateRequestSettlerScheduler matcher, IRequestSettler clientRequestSettler, IRequestSettler serverRequestSettler) CreateSettlers( - TestScheduler scheduler, TimeSpan waitTime, TimeSpan timeout) + TestScheduler scheduler, TimeSpan waitTime, TimeSpan timeout + ) { var container1 = CreateContainer(_loggerFactory); container1.RegisterMany( - reuse: Reuse.Singleton, - made: Parameters.Of - .Name(nameof(waitTime), defaultValue: waitTime) - .Name(nameof(timeout), defaultValue: timeout) - .Type(defaultValue: CancellationToken) - .Type(defaultValue: scheduler) + Reuse.Singleton, + Parameters.Of + .Name(nameof(waitTime), defaultValue: waitTime) + .Name(nameof(timeout), defaultValue: timeout) + .Type(defaultValue: CancellationToken) + .Type(defaultValue: scheduler) ); var container2 = CreateContainer(_loggerFactory); container2.RegisterMany( - reuse: Reuse.Singleton, - made: Parameters.Of - .Name(nameof(waitTime), defaultValue: waitTime) - .Name(nameof(timeout), defaultValue: timeout) - .Type(defaultValue: CancellationToken) - .Type(defaultValue: scheduler) + Reuse.Singleton, + Parameters.Of + .Name(nameof(waitTime), defaultValue: waitTime) + .Name(nameof(timeout), defaultValue: timeout) + .Type(defaultValue: CancellationToken) + .Type(defaultValue: scheduler) ); var settler = new AggregateSettler(container1.Resolve(), container2.Resolve()); var clientSettler = container1.Resolve(); var serverSettler = container2.Resolve(); - return (settler, new AggregateRequestSettlerScheduler(scheduler, clientSettler, serverSettler), container1.Resolve(), - container2.Resolve()); + return ( settler, new AggregateRequestSettlerScheduler(scheduler, clientSettler, serverSettler), container1.Resolve(), + container2.Resolve() ); } public enum SettlerType @@ -291,11 +284,12 @@ public enum SettlerType private static IContainer CreateContainer(ILoggerFactory loggerFactory) { var container = new Container() - .WithDependencyInjectionAdapter(new ServiceCollection().AddLogging()) - .With(rules => rules - .WithResolveIEnumerableAsLazyEnumerable() - .With(FactoryMethod.ConstructorWithResolvableArgumentsIncludingNonPublic) - ); + .WithDependencyInjectionAdapter(new ServiceCollection().AddLogging()) + .With( + rules => rules + .WithResolveIEnumerableAsLazyEnumerable() + .With(FactoryMethod.ConstructorWithResolvableArgumentsIncludingNonPublic) + ); container.RegisterInstance(loggerFactory); return container; diff --git a/test/JsonRpc.Tests/FoundationTests.cs b/test/JsonRpc.Tests/FoundationTests.cs index 53edd74cb..98c66dae4 100644 --- a/test/JsonRpc.Tests/FoundationTests.cs +++ b/test/JsonRpc.Tests/FoundationTests.cs @@ -1,15 +1,10 @@ using System; using System.IO.Pipelines; -using System.Reactive; using System.Threading; -using System.Threading.Tasks; using FluentAssertions; -using MediatR; using Microsoft.Extensions.DependencyInjection; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.JsonRpc.Pipelines; using Xunit; -using Unit = MediatR.Unit; namespace JsonRpc.Tests { @@ -17,17 +12,19 @@ public class FoundationTests { [Theory] [ClassData(typeof(CreateData))] - public void All_Create_From_Methods_Should_Work(ActionDelegate actionDelegate) - { - actionDelegate.Method.Should().NotThrow(); - } + public void All_Create_From_Methods_Should_Work(ActionDelegate actionDelegate) => actionDelegate.Method.Should().NotThrow(); public class CreateData : TheoryData { public CreateData() { var baseOptions = new JsonRpcServerOptions().WithPipe(new Pipe()); - void BaseDelegate(JsonRpcServerOptions o) => o.WithPipe(new Pipe()); + + void BaseDelegate(JsonRpcServerOptions o) + { + o.WithPipe(new Pipe()); + } + var serviceProvider = new ServiceCollection().BuildServiceProvider(); Add(new ActionDelegate("create: options", () => JsonRpcServer.Create(baseOptions))); Add(new ActionDelegate("create: options, serviceProvider", () => JsonRpcServer.Create(baseOptions, serviceProvider))); @@ -47,17 +44,20 @@ public CreateData() [Theory] [ClassData(typeof(MissingInputData))] - public void All_Create_Method_Require_Input(ActionDelegate actionDelegate) - { + public void All_Create_Method_Require_Input(ActionDelegate actionDelegate) => actionDelegate.Method.Should().Throw().Where(z => z.Message.StartsWith("Input is missing!")); - } - class MissingInputData : TheoryData + private class MissingInputData : TheoryData { public MissingInputData() { var baseOptions = new JsonRpcServerOptions().WithOutput(new Pipe().Writer); - void BaseDelegate(JsonRpcServerOptions o) => o.WithOutput(new Pipe().Writer); + + void BaseDelegate(JsonRpcServerOptions o) + { + o.WithOutput(new Pipe().Writer); + } + var serviceProvider = new ServiceCollection().BuildServiceProvider(); Add(new ActionDelegate("create: options", () => JsonRpcServer.Create(baseOptions))); Add(new ActionDelegate("create: options, serviceProvider", () => JsonRpcServer.Create(baseOptions, serviceProvider))); @@ -68,17 +68,20 @@ public MissingInputData() [Theory] [ClassData(typeof(MissingOutputData))] - public void All_Create_Method_Require_Output(ActionDelegate actionDelegate) - { + public void All_Create_Method_Require_Output(ActionDelegate actionDelegate) => actionDelegate.Method.Should().Throw().Where(z => z.Message.StartsWith("Output is missing!")); - } - class MissingOutputData : TheoryData + private class MissingOutputData : TheoryData { public MissingOutputData() { var baseOptions = new JsonRpcServerOptions().WithInput(new Pipe().Reader); - void BaseDelegate(JsonRpcServerOptions o) => o.WithInput(new Pipe().Reader); + + void BaseDelegate(JsonRpcServerOptions o) + { + o.WithInput(new Pipe().Reader); + } + var serviceProvider = new ServiceCollection().BuildServiceProvider(); Add(new ActionDelegate("create: options", () => JsonRpcServer.Create(baseOptions))); Add(new ActionDelegate("create: options, serviceProvider", () => JsonRpcServer.Create(baseOptions, serviceProvider))); @@ -95,7 +98,7 @@ public class ActionDelegate public ActionDelegate(string name, Action method) { _name = name; - this.Method = method; + Method = method; } public override string ToString() => _name; diff --git a/test/JsonRpc.Tests/HandlerResolverTests.cs b/test/JsonRpc.Tests/HandlerResolverTests.cs index a8695e34d..388ef54f0 100644 --- a/test/JsonRpc.Tests/HandlerResolverTests.cs +++ b/test/JsonRpc.Tests/HandlerResolverTests.cs @@ -12,21 +12,37 @@ namespace JsonRpc.Tests { public class HandlerResolverTests { - public class Request : IRequest, IRequest { } - public class Response { } - public class Notification : IRequest { } + public class Request : IRequest, IRequest + { + } + + public class Response + { + } + + public class Notification : IRequest + { + } [Method("request")] - public interface IJsonRpcRequestHandler : IJsonRpcRequestHandler { } + public interface IJsonRpcRequestHandler : IJsonRpcRequestHandler + { + } [Method("requestresponse")] - public interface IJsonRpcRequestResponseHandler : IJsonRpcRequestHandler { } + public interface IJsonRpcRequestResponseHandler : IJsonRpcRequestHandler + { + } [Method("notificationdata")] - public interface IJsonRpcNotificationDataHandler : IJsonRpcNotificationHandler { } + public interface IJsonRpcNotificationDataHandler : IJsonRpcNotificationHandler + { + } [Method("notification")] - public interface IInlineJsonRpcNotificationHandler : IJsonRpcNotificationHandler { } + public interface IInlineJsonRpcNotificationHandler : IJsonRpcNotificationHandler + { + } [Theory] [InlineData(typeof(IJsonRpcRequestHandler), "request")] @@ -36,7 +52,7 @@ public interface IInlineJsonRpcNotificationHandler : IJsonRpcNotificationHandler public void Should_Contain_AllDefinedMethods(Type requestHandler, string key) { var handler = new HandlerCollection(new ServiceCollection().BuildServiceProvider()) { - (IJsonRpcHandler) Substitute.For(new Type[] {requestHandler}, new object[0]) + (IJsonRpcHandler) Substitute.For(new[] { requestHandler }, new object[0]) }; handler.Should().Contain(x => x.Method == key); } @@ -49,7 +65,7 @@ public void Should_Contain_AllDefinedMethods(Type requestHandler, string key) public void Should_Have_CorrectParams(Type requestHandler, string key, Type expected) { var handler = new HandlerCollection(new ServiceCollection().BuildServiceProvider()) { - (IJsonRpcHandler) Substitute.For(new Type[] {requestHandler}, new object[0]) + (IJsonRpcHandler) Substitute.For(new[] { requestHandler }, new object[0]) }; handler.First(x => x.Method == key).Params.Should().IsSameOrEqualTo(expected); } diff --git a/test/JsonRpc.Tests/InputHandlerTests.cs b/test/JsonRpc.Tests/InputHandlerTests.cs index 6706f26ff..05aecba70 100644 --- a/test/JsonRpc.Tests/InputHandlerTests.cs +++ b/test/JsonRpc.Tests/InputHandlerTests.cs @@ -1,16 +1,13 @@ using System; -using System.Buffers; using System.IO; using System.IO.Pipelines; using System.Linq; -using System.Reactive.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NSubstitute; @@ -20,7 +17,6 @@ using OmniSharp.Extensions.JsonRpc.Server; using Xunit; using Xunit.Abstractions; -using Request = OmniSharp.Extensions.JsonRpc.Server.Request; namespace JsonRpc.Tests { @@ -30,10 +26,7 @@ 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, @@ -42,9 +35,9 @@ private InputHandler NewHandler( IRequestProcessIdentifier requestProcessIdentifier, IRequestRouter requestRouter, ILoggerFactory loggerFactory, - IResponseRouter responseRouter) - { - return new InputHandler( + IResponseRouter responseRouter + ) => + new InputHandler( inputStream, outputHandler, receiver, @@ -58,7 +51,6 @@ private InputHandler NewHandler( true, null ); - } [Fact] public async Task Should_Pass_In_Requests() @@ -68,9 +60,11 @@ public async Task Should_Pass_In_Requests() var outputHandler = Substitute.For(); var receiver = Substitute.For(); - using var handler = NewHandler(pipe.Reader, outputHandler, receiver, + using var handler = NewHandler( + pipe.Reader, outputHandler, receiver, Substitute.For(), Substitute.For>(), - _loggerFactory, Substitute.For()); + _loggerFactory, Substitute.For() + ); await pipe.Writer.WriteAsync(Encoding.UTF8.GetBytes("Content-Length: 2\r\n\r\n{}")); var cts = new CancellationTokenSource(); @@ -91,14 +85,16 @@ public async Task Should_Handle_Multiple_Requests_At_Once() var outputHandler = Substitute.For(); var receiver = Substitute.For(); - using var handler = NewHandler(pipe.Reader, outputHandler, receiver, + using var handler = NewHandler( + pipe.Reader, outputHandler, receiver, Substitute.For(), Substitute.For>(), - _loggerFactory, Substitute.For()); + _loggerFactory, Substitute.For() + ); await pipe.Writer.WriteAsync( Encoding.UTF8.GetBytes("Content-Length: 2\r\n\r\n{}") - .Concat(Encoding.UTF8.GetBytes("Content-Length: 2\r\n\r\n{}")) - .Concat(Encoding.UTF8.GetBytes("Content-Length: 2\r\n\r\n{}")) - .ToArray() + .Concat(Encoding.UTF8.GetBytes("Content-Length: 2\r\n\r\n{}")) + .Concat(Encoding.UTF8.GetBytes("Content-Length: 2\r\n\r\n{}")) + .ToArray() ); var cts = new CancellationTokenSource(); @@ -113,13 +109,16 @@ await pipe.Writer.WriteAsync( [Theory] [InlineData( - "Content-Length: 2 \r\nContent-Type: application/json\r\n\r\n{}")] + "Content-Length: 2 \r\nContent-Type: application/json\r\n\r\n{}" + )] [InlineData("Content-Type: application/json\r\nContent-Length: 2\r\n\r\n{}")] [InlineData("Content-Type: application/json\r\nNot-A-Header: really\r\nContent-Length: 2\r\n\r\n{}")] [InlineData( - "Content-Type: application/json\r\nNot-A-Header: really\r\nContent-Length:2 \r\n\r\n{}")] + "Content-Type: application/json\r\nNot-A-Header: really\r\nContent-Length:2 \r\n\r\n{}" + )] [InlineData( - "Content-Type: application/json\r\nNot-A-Header: really\r\nContent-Length: 2\r\n\r\n{}")] + "Content-Type: application/json\r\nNot-A-Header: really\r\nContent-Length: 2\r\n\r\n{}" + )] public async Task Should_Handle_Different_Additional_Headers_and_Whitespace(string data) { var pipe = new Pipe(new PipeOptions()); @@ -127,9 +126,11 @@ public async Task Should_Handle_Different_Additional_Headers_and_Whitespace(stri var outputHandler = Substitute.For(); var receiver = Substitute.For(); - using var handler = NewHandler(pipe.Reader, outputHandler, receiver, + using var handler = NewHandler( + pipe.Reader, outputHandler, receiver, Substitute.For(), Substitute.For>(), - _loggerFactory, Substitute.For()); + _loggerFactory, Substitute.For() + ); await pipe.Writer.WriteAsync(Encoding.UTF8.GetBytes(data)); var cts = new CancellationTokenSource(); @@ -152,9 +153,11 @@ public async Task Should_Handle_Multiple_Requests_Back_To_Back() var outputHandler = Substitute.For(); var receiver = Substitute.For(); - using var handler = NewHandler(pipe.Reader, outputHandler, receiver, + using var handler = NewHandler( + pipe.Reader, outputHandler, receiver, Substitute.For(), Substitute.For>(), - _loggerFactory, Substitute.For()); + _loggerFactory, Substitute.For() + ); var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(5)); @@ -182,9 +185,11 @@ public async Task Should_Handle_Multiple_Requests_In_Pieces() var outputHandler = Substitute.For(); var receiver = Substitute.For(); - using var handler = NewHandler(pipe.Reader, outputHandler, receiver, + using var handler = NewHandler( + pipe.Reader, outputHandler, receiver, Substitute.For(), Substitute.For>(), - _loggerFactory, Substitute.For()); + _loggerFactory, Substitute.For() + ); var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(5)); @@ -212,7 +217,9 @@ public async Task Should_Handle_Multiple_Requests_In_Pieces() } [Theory] - [InlineData("Content-Length: 894\r\n\r\n{\"edit\":{\"documentChanges\":[{\"textDocument\":{\"version\":1,\"uri\":\"file:///abc/123/d.cs\"},\"edits\":[{\"range\":{\"start\":{\"line\":1,\"character\":1},\"end\":{\"line\":2,\"character\":2}},\"newText\":\"new text\"},{\"range\":{\"start\":{\"line\":3,\"character\":3},\"end\":{\"line\":4,\"character\":4}},\"newText\":\"new text2\"}]},{\"textDocument\":{\"version\":1,\"uri\":\"file:///abc/123/b.cs\"},\"edits\":[{\"range\":{\"start\":{\"line\":1,\"character\":1},\"end\":{\"line\":2,\"character\":2}},\"newText\":\"new text2\"},{\"range\":{\"start\":{\"line\":3,\"character\":3},\"end\":{\"line\":4,\"character\":4}},\"newText\":\"new text3\"}]},{\"kind\":\"create\",\"uri\":\"file:///abc/123/b.cs\",\"options\":{\"overwrite\":true,\"ignoreIfExists\":true}},{\"kind\":\"rename\",\"oldUri\":\"file:///abc/123/b.cs\",\"newUri\":\"file:///abc/123/c.cs\",\"options\":{\"overwrite\":true,\"ignoreIfExists\":true}},{\"kind\":\"delete\",\"uri\":\"file:///abc/123/c.cs\",\"options\":{\"recursive\":false,\"ignoreIfNotExists\":true}}]}}")] + [InlineData( + "Content-Length: 894\r\n\r\n{\"edit\":{\"documentChanges\":[{\"textDocument\":{\"version\":1,\"uri\":\"file:///abc/123/d.cs\"},\"edits\":[{\"range\":{\"start\":{\"line\":1,\"character\":1},\"end\":{\"line\":2,\"character\":2}},\"newText\":\"new text\"},{\"range\":{\"start\":{\"line\":3,\"character\":3},\"end\":{\"line\":4,\"character\":4}},\"newText\":\"new text2\"}]},{\"textDocument\":{\"version\":1,\"uri\":\"file:///abc/123/b.cs\"},\"edits\":[{\"range\":{\"start\":{\"line\":1,\"character\":1},\"end\":{\"line\":2,\"character\":2}},\"newText\":\"new text2\"},{\"range\":{\"start\":{\"line\":3,\"character\":3},\"end\":{\"line\":4,\"character\":4}},\"newText\":\"new text3\"}]},{\"kind\":\"create\",\"uri\":\"file:///abc/123/b.cs\",\"options\":{\"overwrite\":true,\"ignoreIfExists\":true}},{\"kind\":\"rename\",\"oldUri\":\"file:///abc/123/b.cs\",\"newUri\":\"file:///abc/123/c.cs\",\"options\":{\"overwrite\":true,\"ignoreIfExists\":true}},{\"kind\":\"delete\",\"uri\":\"file:///abc/123/c.cs\",\"options\":{\"recursive\":false,\"ignoreIfNotExists\":true}}]}}" + )] public async Task Should_Handle_Multiple_Chunked_Requests(string content) { var pipe = new Pipe(new PipeOptions()); @@ -220,9 +227,11 @@ public async Task Should_Handle_Multiple_Chunked_Requests(string content) var outputHandler = Substitute.For(); var receiver = Substitute.For(); - using var handler = NewHandler(pipe.Reader, outputHandler, receiver, + using var handler = NewHandler( + pipe.Reader, outputHandler, receiver, Substitute.For(), Substitute.For>(), - _loggerFactory, Substitute.For()); + _loggerFactory, Substitute.For() + ); var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromMinutes(2)); @@ -245,14 +254,16 @@ 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(); - using var handler = NewHandler(pipe.Reader, outputHandler, receiver, + using var handler = NewHandler( + pipe.Reader, outputHandler, receiver, Substitute.For(), Substitute.For>(), - _loggerFactory, Substitute.For()); + _loggerFactory, Substitute.For() + ); var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromMinutes(5)); @@ -300,16 +311,19 @@ public async Task ShouldPassAdditionalUtf8EncodedRequests(string data) var outputHandler = Substitute.For(); var receiver = Substitute.For(); - using var handler = NewHandler(pipe.Reader, outputHandler, receiver, + using var handler = NewHandler( + pipe.Reader, outputHandler, receiver, Substitute.For(), Substitute.For>(), - _loggerFactory, Substitute.For()); + _loggerFactory, Substitute.For() + ); var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(5)); var processTask = handler.ProcessInputStream(cts.Token); await pipe.Writer.WriteAsync( - Encoding.UTF8.GetBytes($"Content-Length: {Encoding.UTF8.GetBytes(data).Length}\r\n\r\n{data}")); + Encoding.UTF8.GetBytes($"Content-Length: {Encoding.UTF8.GetBytes(data).Length}\r\n\r\n{data}") + ); await Task.Yield(); await pipe.Writer.FlushAsync(); @@ -339,7 +353,8 @@ public async Task Should_Parse_Logs(string name, Func createPipeRead var outputHandler = Substitute.For(); var responseRouter = Substitute.For(); - using var handler = NewHandler(reader, outputHandler, receiver, + using var handler = NewHandler( + reader, outputHandler, receiver, new ParallelRequestProcessIdentifier(), incomingRequestRouter, _loggerFactory, @@ -375,10 +390,9 @@ await incomingRequestRouter.Received(count).RouteNotification( } logger.LogInformation("End"); - } - class JsonRpcLogs : TheoryData, ILookup> + private class JsonRpcLogs : TheoryData, ILookup> { public JsonRpcLogs() { @@ -387,32 +401,34 @@ public JsonRpcLogs() { var data = GetData(assembly, streamName); - var msgTypes = data.Select(z => { - if (z.MsgKind.EndsWith("response")) - { - return (type:"response", kind:z.MsgType); - } - - if (z.MsgKind.EndsWith("request")) - { - return (type:"request", kind:z.MsgType); - } - - if (z.MsgKind.EndsWith("notification") && z.MsgType != JsonRpcNames.CancelRequest) - { - return (type: "notification", kind:z.MsgType); - } - - return (type:null, kind:null); - }) - .Where(z => z.type != null) - .ToLookup(z => z.kind, z => z.type); - - Add(streamName, () => CreateReader(data), msgTypes ); + var msgTypes = data.Select( + z => { + if (z.MsgKind.EndsWith("response")) + { + return ( type: "response", kind: z.MsgType ); + } + + if (z.MsgKind.EndsWith("request")) + { + return ( type: "request", kind: z.MsgType ); + } + + if (z.MsgKind.EndsWith("notification") && z.MsgType != JsonRpcNames.CancelRequest) + { + return ( type: "notification", kind: z.MsgType ); + } + + return ( type: null, kind: null ); + } + ) + .Where(z => z.type != null) + .ToLookup(z => z.kind, z => z.type); + + Add(streamName, () => CreateReader(data), msgTypes); } } - DataItem[] GetData(Assembly assembly, string name) + private DataItem[] GetData(Assembly assembly, string name) { var stream = assembly.GetManifestResourceStream(name); using var streamReader = new StreamReader(stream); @@ -421,60 +437,64 @@ DataItem[] GetData(Assembly assembly, string name) return serializer.Deserialize(jsonReader); } - PipeReader CreateReader(DataItem[] data) + private PipeReader CreateReader(DataItem[] data) { var outputData = data - .Select(z => { - if (z.MsgKind.EndsWith("response")) - { - return new OutgoingResponse(z.MsgId, z.Arg, new Request(z.MsgId, z.MsgType, JValue.CreateNull())); - } - - if (z.MsgKind.EndsWith("request")) - { - return new OmniSharp.Extensions.JsonRpc.Client.OutgoingRequest() { - Id = z.MsgId, - Method = z.MsgType, - Params = z.Arg - }; + .Select( + z => { + if (z.MsgKind.EndsWith("response")) + { + return new OutgoingResponse(z.MsgId, z.Arg, new Request(z.MsgId, z.MsgType, JValue.CreateNull())); + } + + if (z.MsgKind.EndsWith("request")) + { + return new OutgoingRequest { + Id = z.MsgId, + Method = z.MsgType, + Params = z.Arg + }; + } + + if (z.MsgKind.EndsWith("notification")) + { + return new OutgoingNotification { + Method = z.MsgType, + Params = z.Arg + }; + } + + throw new NotSupportedException("unknown message kind " + z.MsgKind); } - - if (z.MsgKind.EndsWith("notification")) - { - return new OmniSharp.Extensions.JsonRpc.Client.OutgoingNotification() { - Method = z.MsgType, - Params = z.Arg - }; - } - - throw new NotSupportedException("unknown message kind " + z.MsgKind); - }); + ); var pipeIn = new Pipe(); var _serializer = new JsonRpcSerializer(); - Task.Run(async () => { - foreach (var item in outputData) - { - - var content = _serializer.SerializeObject(item); - var contentBytes = Encoding.UTF8.GetBytes(content).AsMemory(); + Task.Run( + async () => { + foreach (var item in outputData) + { + var content = _serializer.SerializeObject(item); + var contentBytes = Encoding.UTF8.GetBytes(content).AsMemory(); + + await pipeIn.Writer.WriteAsync( + Encoding.UTF8.GetBytes($"Content-Length: {contentBytes.Length}\r\n\r\n") + ); + await pipeIn.Writer.WriteAsync(contentBytes); + await pipeIn.Writer.FlushAsync(); + } - await pipeIn.Writer.WriteAsync( - Encoding.UTF8.GetBytes($"Content-Length: {contentBytes.Length}\r\n\r\n")); - await pipeIn.Writer.WriteAsync(contentBytes); - await pipeIn.Writer.FlushAsync(); + await pipeIn.Writer.CompleteAsync(); } - - await pipeIn.Writer.CompleteAsync(); - }); + ); return pipeIn.Reader; } - class DataItem + private class DataItem { public string Time { get; set; } public string Msg { get; set; } diff --git a/test/JsonRpc.Tests/IntegrationTests.cs b/test/JsonRpc.Tests/IntegrationTests.cs index 6ad982d2e..6b6d487a0 100644 --- a/test/JsonRpc.Tests/IntegrationTests.cs +++ b/test/JsonRpc.Tests/IntegrationTests.cs @@ -20,12 +20,11 @@ public IntegrationTests(ITestOutputHelper testOutputHelper) : base(new JsonRpcTe { } - class Request : IRequest + private class Request : IRequest { - } - class Data + private class Data { public string Value { get; set; } } @@ -34,8 +33,8 @@ class Data public async Task Should_Send_and_receive_requests() { var (client, server) = await Initialize( - client => { client.OnRequest("myrequest", async () => new Data() {Value = "myresponse"}); }, - server => { server.OnRequest("myrequest", async () => new Data() {Value = string.Join("", "myresponse".Reverse())}); } + client => { client.OnRequest("myrequest", async () => new Data { Value = "myresponse" }); }, + server => { server.OnRequest("myrequest", async () => new Data { Value = string.Join("", "myresponse".Reverse()) }); } ); var serverResponse = await client.SendRequest("myrequest").Returning(CancellationToken); @@ -49,14 +48,14 @@ public async Task Should_Send_and_receive_requests() public async Task Should_throw_when_sending_requests() { var (client, server) = await Initialize( - client => { client.OnRequest("myrequest", async (Request request) => new Data() {Value = "myresponse"}); }, - server => { server.OnRequest("myrequest", async (Request request) => new Data() {Value = string.Join("", "myresponse".Reverse())}); } + client => { client.OnRequest("myrequest", async (Request request) => new Data { Value = "myresponse" }); }, + server => { server.OnRequest("myrequest", async (Request request) => new Data { Value = string.Join("", "myresponse".Reverse()) }); } ); - Func clientRequest = () => client.SendRequest("myrequest", (Request)null).Returning(CancellationToken); + Func clientRequest = () => client.SendRequest("myrequest", (Request) null).Returning(CancellationToken); clientRequest.Should().Throw(); - Func serverRequest = () => server.SendRequest("myrequest", (Request)null).Returning(CancellationToken); + Func serverRequest = () => server.SendRequest("myrequest", (Request) null).Returning(CancellationToken); serverRequest.Should().Throw(); } @@ -64,8 +63,8 @@ public async Task Should_throw_when_sending_requests() public async Task Should_throw_when_receiving_requests() { var (client, server) = await Initialize( - client => { client.OnRequest("myrequest", async (Request request) => (Data)null); }, - server => { server.OnRequest("myrequest", async (Request request) => (Data)null); } + client => { client.OnRequest("myrequest", async (Request request) => (Data) null); }, + server => { server.OnRequest("myrequest", async (Request request) => (Data) null); } ); Func clientRequest = () => client.SendRequest("myrequest", new Request()).Returning(CancellationToken); @@ -82,24 +81,28 @@ public async Task Should_Send_and_receive_notifications() var serverNotification = new AsyncSubject(); var (client, server) = await Initialize( client => { - client.OnNotification("mynotification", (Data data) => { - clientNotification.OnNext(data); - clientNotification.OnCompleted(); - }); + client.OnNotification( + "mynotification", (Data data) => { + clientNotification.OnNext(data); + clientNotification.OnCompleted(); + } + ); }, server => { - server.OnNotification("mynotification", (Data data) => { - serverNotification.OnNext(data); - serverNotification.OnCompleted(); - }); + server.OnNotification( + "mynotification", (Data data) => { + serverNotification.OnNext(data); + serverNotification.OnCompleted(); + } + ); } ); - client.SendNotification("mynotification", new Data() {Value = "myresponse"}); + client.SendNotification("mynotification", new Data { Value = "myresponse" }); var serverResponse = await serverNotification; serverResponse.Value.Should().Be("myresponse"); - server.SendNotification("mynotification", new Data() {Value = string.Join("", "myresponse".Reverse())}); + server.SendNotification("mynotification", new Data { Value = string.Join("", "myresponse".Reverse()) }); var clientResponse = await clientNotification; clientResponse.Value.Should().Be("esnopserym"); } @@ -109,16 +112,20 @@ public async Task Should_Send_and_cancel_requests_immediate() { var (client, server) = await Initialize( client => { - client.OnRequest("myrequest", async (ct) => { - await Task.Delay(TimeSpan.FromMinutes(1), ct); - return new Data() {Value = "myresponse"}; - }); + client.OnRequest( + "myrequest", async ct => { + await Task.Delay(TimeSpan.FromMinutes(1), ct); + return new Data { Value = "myresponse" }; + } + ); }, server => { - server.OnRequest("myrequest", async (ct) => { - await Task.Delay(TimeSpan.FromMinutes(1), ct); - return new Data() {Value = string.Join("", "myresponse".Reverse())}; - }); + server.OnRequest( + "myrequest", async ct => { + await Task.Delay(TimeSpan.FromMinutes(1), ct); + return new Data { Value = string.Join("", "myresponse".Reverse()) }; + } + ); } ); @@ -141,16 +148,20 @@ public async Task Should_Send_and_cancel_requests_from_otherside() { var (client, server) = await Initialize( client => { - client.OnRequest("myrequest", async (ct) => { - await Task.Delay(TimeSpan.FromMinutes(1), ct); - return new Data() {Value = "myresponse"}; - }); + client.OnRequest( + "myrequest", async ct => { + await Task.Delay(TimeSpan.FromMinutes(1), ct); + return new Data { Value = "myresponse" }; + } + ); }, server => { - server.OnRequest("myrequest", async (ct) => { - await Task.Delay(TimeSpan.FromMinutes(1), ct); - return new Data() {Value = string.Join("", "myresponse".Reverse())}; - }); + server.OnRequest( + "myrequest", async ct => { + await Task.Delay(TimeSpan.FromMinutes(1), ct); + return new Data { Value = string.Join("", "myresponse".Reverse()) }; + } + ); } ); @@ -176,29 +187,31 @@ public async Task Should_Cancel_Parallel_Requests_When_Options_Are_Given() client => { client.OnRequest( "parallelrequest", - async (ct) => { + async ct => { await Task.Delay(TimeSpan.FromSeconds(10), ct); - return new Data() {Value = "myresponse"}; + return new Data { Value = "myresponse" }; }, - new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Parallel}); + new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel } + ); client.OnRequest( "serialrequest", - async (ct) => new Data() {Value = "myresponse"}, - new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial} + async ct => new Data { Value = "myresponse" }, + new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial } ); }, server => { server.OnRequest( "parallelrequest", - async (ct) => { + async ct => { await Task.Delay(TimeSpan.FromSeconds(10), ct); - return new Data() {Value = "myresponse"}; + return new Data { Value = "myresponse" }; }, - new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Parallel}); + new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel } + ); server.OnRequest( "serialrequest", - async (ct) => new Data() {Value = "myresponse"}, - new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial} + async ct => new Data { Value = "myresponse" }, + new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial } ); } ); @@ -224,14 +237,14 @@ public async Task Should_Link_Request_A_to_Request_B() var (client, server) = await Initialize( client => { client - .OnRequest("myrequest", async () => new Data() {Value = "myresponse"}) - .WithLink("myrequest", "myrequest2") + .OnRequest("myrequest", async () => new Data { Value = "myresponse" }) + .WithLink("myrequest", "myrequest2") ; }, server => { server - .OnRequest("myrequest", async () => new Data() {Value = string.Join("", "myresponse".Reverse())}) - .WithLink("myrequest", "myrequest2") + .OnRequest("myrequest", async () => new Data { Value = string.Join("", "myresponse".Reverse()) }) + .WithLink("myrequest", "myrequest2") ; } ); diff --git a/test/JsonRpc.Tests/JsonRpcServerTests.cs b/test/JsonRpc.Tests/JsonRpcServerTests.cs index 3170cc9bf..aabae324a 100644 --- a/test/JsonRpc.Tests/JsonRpcServerTests.cs +++ b/test/JsonRpc.Tests/JsonRpcServerTests.cs @@ -1,11 +1,8 @@ using System; -using System.IO; using System.IO.Pipes; -using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Nerdbank.Streams; using NSubstitute; -using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Testing; using Xunit; using Xunit.Abstractions; @@ -23,26 +20,29 @@ public JsonRpcServerTests(ITestOutputHelper testOutputHelper) : base(new JsonRpc [Fact] public async Task Can_Connect_To_Stdio() { - var (client, server) = await Initialize(clientOptions => { - clientOptions - .WithInput(Console.OpenStandardInput().UsePipeReader()) - .WithOutput(Console.OpenStandardError().UsePipeWriter()); - }, serverOptions => { - serverOptions - .WithInput(Console.OpenStandardInput().UsePipeReader()) - .WithOutput(Console.OpenStandardError().UsePipeWriter()); - }); + var (client, server) = await Initialize( + clientOptions => { + clientOptions + .WithInput(Console.OpenStandardInput().UsePipeReader()) + .WithOutput(Console.OpenStandardError().UsePipeWriter()); + }, serverOptions => { + serverOptions + .WithInput(Console.OpenStandardInput().UsePipeReader()) + .WithOutput(Console.OpenStandardError().UsePipeWriter()); + } + ); } [Fact] public async Task Can_Connect_To_A_Named_Pipe() { var serverPipe = new NamedPipeServerStream( - pipeName: _pipeName, - direction: PipeDirection.InOut, - maxNumberOfServerInstances: 1, - transmissionMode: PipeTransmissionMode.Byte, - options: PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous); + _pipeName, + PipeDirection.InOut, + 1, + PipeTransmissionMode.Byte, + PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous + ); var clientPipe = new NamedPipeClientStream( ".", _pipeName, @@ -50,15 +50,17 @@ public async Task Can_Connect_To_A_Named_Pipe() PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous ); - var (client, server) = await Initialize(clientOptions => { - clientOptions - .WithInput(clientPipe) - .WithOutput(clientPipe); - }, serverOptions => { - serverOptions - .WithInput(serverPipe) - .WithOutput(serverPipe); - }); + var (client, server) = await Initialize( + clientOptions => { + clientOptions + .WithInput(clientPipe) + .WithOutput(clientPipe); + }, serverOptions => { + serverOptions + .WithInput(serverPipe) + .WithOutput(serverPipe); + } + ); await Task.WhenAll(clientPipe.ConnectAsync(CancellationToken), serverPipe.WaitForConnectionAsync(CancellationToken)); } @@ -68,11 +70,12 @@ public async Task Can_Reconnect_To_A_Named_Pipe() { { var serverPipe = new NamedPipeServerStream( - pipeName: _pipeName, - direction: PipeDirection.InOut, - maxNumberOfServerInstances: 1, - transmissionMode: PipeTransmissionMode.Byte, - options: PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous); + _pipeName, + PipeDirection.InOut, + 1, + PipeTransmissionMode.Byte, + PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous + ); var clientPipe = new NamedPipeClientStream( ".", _pipeName, @@ -80,15 +83,17 @@ public async Task Can_Reconnect_To_A_Named_Pipe() PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous ); - var (client, server) = await Initialize(clientOptions => { - clientOptions - .WithInput(clientPipe) - .WithOutput(clientPipe); - }, serverOptions => { - serverOptions - .WithInput(serverPipe) - .WithOutput(serverPipe); - }); + var (client, server) = await Initialize( + clientOptions => { + clientOptions + .WithInput(clientPipe) + .WithOutput(clientPipe); + }, serverOptions => { + serverOptions + .WithInput(serverPipe) + .WithOutput(serverPipe); + } + ); await Task.WhenAll(clientPipe.ConnectAsync(CancellationToken), serverPipe.WaitForConnectionAsync(CancellationToken)); @@ -101,11 +106,12 @@ public async Task Can_Reconnect_To_A_Named_Pipe() { var serverPipe = new NamedPipeServerStream( - pipeName: _pipeName, - direction: PipeDirection.InOut, - maxNumberOfServerInstances: 1, - transmissionMode: PipeTransmissionMode.Byte, - options: PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous); + _pipeName, + PipeDirection.InOut, + 1, + PipeTransmissionMode.Byte, + PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous + ); var clientPipe = new NamedPipeClientStream( ".", _pipeName, @@ -113,17 +119,19 @@ public async Task Can_Reconnect_To_A_Named_Pipe() PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous ); - var (client, server) = await Initialize(clientOptions => { - clientOptions - .WithInput(clientPipe) - .WithOutput(clientPipe); - // clientOptions.RegisterForDisposal(clientPipe); - }, serverOptions => { - serverOptions - .WithInput(serverPipe) - .WithOutput(serverPipe); - // serverOptions.RegisterForDisposal(serverPipe); - }); + var (client, server) = await Initialize( + clientOptions => { + clientOptions + .WithInput(clientPipe) + .WithOutput(clientPipe); + // clientOptions.RegisterForDisposal(clientPipe); + }, serverOptions => { + serverOptions + .WithInput(serverPipe) + .WithOutput(serverPipe); + // serverOptions.RegisterForDisposal(serverPipe); + } + ); await Task.WhenAll(clientPipe.ConnectAsync(CancellationToken), serverPipe.WaitForConnectionAsync(CancellationToken)); } diff --git a/test/JsonRpc.Tests/JsonRpcTestContainer.cs b/test/JsonRpc.Tests/JsonRpcTestContainer.cs index 27097d692..be6eb1201 100644 --- a/test/JsonRpc.Tests/JsonRpcTestContainer.cs +++ b/test/JsonRpc.Tests/JsonRpcTestContainer.cs @@ -4,7 +4,6 @@ using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Serialization; using Xunit.Abstractions; -using NSubstitute.Internals; namespace JsonRpc.Tests { @@ -13,8 +12,8 @@ internal static class JsonRpcTestContainer public static IContainer Create(ITestOutputHelper testOutputHelper) { var container = JsonRpcServerContainer.Create(null) - .AddJsonRpcMediatR() - .With(rules => rules.WithDefaultReuse(Reuse.ScopedOrSingleton)); + .AddJsonRpcMediatR() + .With(rules => rules.WithDefaultReuse(Reuse.ScopedOrSingleton)); var services = new ServiceCollection().AddLogging().AddOptions(); container.Populate(services); diff --git a/test/JsonRpc.Tests/MediatorTestsNotificationHandler.cs b/test/JsonRpc.Tests/MediatorTestsNotificationHandler.cs index 0fa91515b..75bb09c61 100644 --- a/test/JsonRpc.Tests/MediatorTestsNotificationHandler.cs +++ b/test/JsonRpc.Tests/MediatorTestsNotificationHandler.cs @@ -1,10 +1,8 @@ -using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.JsonRpc.Serialization; using OmniSharp.Extensions.JsonRpc.Server; using Xunit; using Xunit.Abstractions; @@ -14,13 +12,12 @@ namespace JsonRpc.Tests public class MediatorTestsNotificationHandler : AutoTestBase { [Method("exit")] - public interface IExitHandler : IJsonRpcNotificationHandler { } - - public MediatorTestsNotificationHandler(ITestOutputHelper testOutputHelper) : base(testOutputHelper) + public interface IExitHandler : IJsonRpcNotificationHandler { - Container = JsonRpcTestContainer.Create(testOutputHelper); } + public MediatorTestsNotificationHandler(ITestOutputHelper testOutputHelper) : base(testOutputHelper) => Container = JsonRpcTestContainer.Create(testOutputHelper); + [Fact] public async Task ExecutesHandler() { @@ -36,6 +33,5 @@ public async Task ExecutesHandler() await exitHandler.Received(1).Handle(Arg.Any(), Arg.Any()); } - } } diff --git a/test/JsonRpc.Tests/MediatorTestsNotificationHandlerOfT.cs b/test/JsonRpc.Tests/MediatorTestsNotificationHandlerOfT.cs index f1c269bde..02627472d 100644 --- a/test/JsonRpc.Tests/MediatorTestsNotificationHandlerOfT.cs +++ b/test/JsonRpc.Tests/MediatorTestsNotificationHandlerOfT.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using System.Threading; using System.Threading.Tasks; using MediatR; @@ -8,7 +7,6 @@ using Newtonsoft.Json.Linq; using NSubstitute; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.JsonRpc.Serialization; using OmniSharp.Extensions.JsonRpc.Server; using Xunit; using Xunit.Abstractions; @@ -18,17 +16,16 @@ namespace JsonRpc.Tests public class MediatorTestsNotificationHandlerOfT : AutoTestBase { [Method("$/cancelRequest")] - public interface ICancelRequestHandler : IJsonRpcNotificationHandler { } + public interface ICancelRequestHandler : IJsonRpcNotificationHandler + { + } public class CancelParams : IRequest { public object Id { get; set; } } - public MediatorTestsNotificationHandlerOfT(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - Container = JsonRpcTestContainer.Create(testOutputHelper); - } + public MediatorTestsNotificationHandlerOfT(ITestOutputHelper testOutputHelper) : base(testOutputHelper) => Container = JsonRpcTestContainer.Create(testOutputHelper); [Fact] public async Task ExecutesHandler() @@ -40,13 +37,12 @@ public async Task ExecutesHandler() AutoSubstitute.Provide(collection); var router = AutoSubstitute.Resolve(); - var @params = new CancelParams() { Id = Guid.NewGuid() }; + var @params = new CancelParams { Id = Guid.NewGuid() }; var notification = new Notification("$/cancelRequest", JObject.Parse(JsonConvert.SerializeObject(@params))); await router.RouteNotification(router.GetDescriptors(notification), notification, CancellationToken.None); await cancelRequestHandler.Received(1).Handle(Arg.Any(), Arg.Any()); } - } } diff --git a/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequest.cs b/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequest.cs index fc4cf9229..325863e15 100644 --- a/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequest.cs +++ b/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequest.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using System.Threading; using System.Threading.Tasks; using MediatR; @@ -8,7 +7,6 @@ using Newtonsoft.Json.Linq; using NSubstitute; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.JsonRpc.Serialization; using OmniSharp.Extensions.JsonRpc.Server; using Xunit; using Xunit.Abstractions; @@ -18,17 +16,16 @@ namespace JsonRpc.Tests public class MediatorTestsRequestHandlerOfTRequest : AutoTestBase { [Method("workspace/executeCommand")] - public interface IExecuteCommandHandler : IJsonRpcRequestHandler { } + public interface IExecuteCommandHandler : IJsonRpcRequestHandler + { + } public class ExecuteCommandParams : IRequest { public string Command { get; set; } } - public MediatorTestsRequestHandlerOfTRequest(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - Container = JsonRpcTestContainer.Create(testOutputHelper); - } + public MediatorTestsRequestHandlerOfTRequest(ITestOutputHelper testOutputHelper) : base(testOutputHelper) => Container = JsonRpcTestContainer.Create(testOutputHelper); [Fact] public async Task ExecutesHandler() @@ -41,14 +38,12 @@ public async Task ExecutesHandler() var router = AutoSubstitute.Resolve(); var id = Guid.NewGuid().ToString(); - var @params = new ExecuteCommandParams() { Command = "123" }; + var @params = new ExecuteCommandParams { Command = "123" }; var request = new Request(id, "workspace/executeCommand", JObject.Parse(JsonConvert.SerializeObject(@params))); var response = await router.RouteRequest(router.GetDescriptors(request), request, CancellationToken.None); await executeCommandHandler.Received(1).Handle(Arg.Any(), Arg.Any()); - - } } } diff --git a/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs b/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs index a9dcaf228..11933942a 100644 --- a/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs +++ b/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Threading; using System.Threading.Tasks; using MediatR; @@ -9,7 +8,6 @@ using Newtonsoft.Json.Linq; using NSubstitute; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.JsonRpc.Serialization; using OmniSharp.Extensions.JsonRpc.Server; using Xunit; using Xunit.Abstractions; @@ -19,7 +17,9 @@ namespace JsonRpc.Tests public class MediatorTestsRequestHandlerOfTRequestTResponse : AutoTestBase { [Method("textDocument/codeAction")] - public interface ICodeActionHandler : IJsonRpcRequestHandler> { } + public interface ICodeActionHandler : IJsonRpcRequestHandler> + { + } public class CodeActionParams : IRequest> { @@ -31,14 +31,11 @@ public class CodeActionParams : IRequest> public class Command { public string Title { get; set; } - [JsonProperty("command")] - public string Name { get; set; } + [JsonProperty("command")] public string Name { get; set; } } - public MediatorTestsRequestHandlerOfTRequestTResponse(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { + public MediatorTestsRequestHandlerOfTRequestTResponse(ITestOutputHelper testOutputHelper) : base(testOutputHelper) => Container = JsonRpcTestContainer.Create(testOutputHelper); - } [Fact] public async Task ExecutesHandler() @@ -51,7 +48,7 @@ public async Task ExecutesHandler() var router = AutoSubstitute.Resolve(); var id = Guid.NewGuid().ToString(); - var @params = new CodeActionParams() { TextDocument = "TextDocument", Range = "Range", Context = "Context" }; + var @params = new CodeActionParams { TextDocument = "TextDocument", Range = "Range", Context = "Context" }; var request = new Request(id, "textDocument/codeAction", JObject.Parse(JsonConvert.SerializeObject(@params))); var response = await router.RouteRequest(router.GetDescriptors(request), request, CancellationToken.None); diff --git a/test/JsonRpc.Tests/OutputHandlerTests.cs b/test/JsonRpc.Tests/OutputHandlerTests.cs index ddcaad63c..45517d3e5 100644 --- a/test/JsonRpc.Tests/OutputHandlerTests.cs +++ b/test/JsonRpc.Tests/OutputHandlerTests.cs @@ -9,6 +9,7 @@ using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Client; using OmniSharp.Extensions.JsonRpc.Serialization; +using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.JsonRpc.Server.Messages; using Xunit; @@ -22,6 +23,7 @@ private static OutputHandler NewHandler(PipeWriter writer) rec.ShouldFilterOutput(Arg.Any()).Returns(true); return new OutputHandler(writer, new JsonRpcSerializer(), rec, Scheduler.Immediate, NullLogger.Instance); } + private static OutputHandler NewHandler(PipeWriter writer, Func filter) { var rec = Substitute.For(); @@ -35,7 +37,7 @@ public async Task ShouldSerializeResponses() var pipe = new Pipe(new PipeOptions()); using var handler = NewHandler(pipe.Writer); - var value = new OutgoingResponse(1, 1, new OmniSharp.Extensions.JsonRpc.Server.Request(1, "a", null)); + var value = new OutgoingResponse(1, 1, new Request(1, "a", null)); handler.Send(value); @@ -55,7 +57,7 @@ public async Task ShouldSerializeNotifications() var pipe = new Pipe(new PipeOptions()); using var handler = NewHandler(pipe.Writer); - var value = new OmniSharp.Extensions.JsonRpc.Client.OutgoingNotification() { + var value = new OutgoingNotification { Method = "method", Params = new object() }; @@ -77,7 +79,7 @@ public async Task ShouldSerializeRequests() var pipe = new Pipe(new PipeOptions()); using var handler = NewHandler(pipe.Writer); - var value = new OmniSharp.Extensions.JsonRpc.Client.OutgoingRequest() { + var value = new OutgoingRequest { Method = "method", Id = 1, Params = new object(), diff --git a/test/JsonRpc.Tests/ProcessSchedulerTests.cs b/test/JsonRpc.Tests/ProcessSchedulerTests.cs index e5427bc11..7bdd07811 100644 --- a/test/JsonRpc.Tests/ProcessSchedulerTests.cs +++ b/test/JsonRpc.Tests/ProcessSchedulerTests.cs @@ -1,15 +1,13 @@ using System; using System.Linq; -using System.Threading.Tasks; -using Xunit; -using FluentAssertions; using System.Reactive; -using System.Reactive.Disposables; using System.Reactive.Linq; -using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; using Microsoft.Reactive.Testing; using NSubstitute; using OmniSharp.Extensions.JsonRpc; +using Xunit; using Xunit.Abstractions; using Xunit.Sdk; using static Microsoft.Reactive.Testing.ReactiveTest; @@ -18,14 +16,11 @@ namespace JsonRpc.Tests { public class ProcessSchedulerTests { - public ProcessSchedulerTests(ITestOutputHelper testOutputHelper) - { - _testOutputHelper = testOutputHelper; - } + public ProcessSchedulerTests(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper; private readonly ITestOutputHelper _testOutputHelper; - class AllRequestProcessTypes : TheoryData + private class AllRequestProcessTypes : TheoryData { public AllRequestProcessTypes() { @@ -34,7 +29,8 @@ public AllRequestProcessTypes() } } - [Theory, ClassData(typeof(AllRequestProcessTypes))] + [Theory] + [ClassData(typeof(AllRequestProcessTypes))] public void ShouldScheduleCompletedTask(RequestProcessType type) { var testScheduler = new TestScheduler(); @@ -49,7 +45,7 @@ public void ShouldScheduleCompletedTask(RequestProcessType type) s.Add(type, "bogus", DoStuff(testObservable, testObserver)); - testScheduler.AdvanceTo(Subscribed/2); + testScheduler.AdvanceTo(Subscribed / 2); testObservable.Subscriptions.Count.Should().Be(1); @@ -80,17 +76,17 @@ public void ShouldScheduleSerialInOrder() testObservable.Subscriptions.Count.Should().Be(8); testObserver.Messages - .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() - .ContainInOrder( - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed * 2, Unit.Default), - OnNext(Subscribed * 3, Unit.Default), - OnNext(Subscribed * 4, Unit.Default), - OnNext(Subscribed * 5, Unit.Default), - OnNext(Subscribed * 6, Unit.Default), - OnNext(Subscribed * 7, Unit.Default), - OnNext(Subscribed * 8, Unit.Default) - ); + .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() + .ContainInOrder( + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed * 2, Unit.Default), + OnNext(Subscribed * 3, Unit.Default), + OnNext(Subscribed * 4, Unit.Default), + OnNext(Subscribed * 5, Unit.Default), + OnNext(Subscribed * 6, Unit.Default), + OnNext(Subscribed * 7, Unit.Default), + OnNext(Subscribed * 8, Unit.Default) + ); } [Fact] @@ -112,17 +108,17 @@ public void ShouldScheduleParallelInParallel() testObservable.Subscriptions.Count.Should().Be(8); testObserver.Messages - .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() - .ContainInOrder( - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed, Unit.Default) - ); + .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() + .ContainInOrder( + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed, Unit.Default) + ); } [Fact] @@ -150,17 +146,17 @@ public void ShouldScheduleMixed() testObservable.Subscriptions.Count.Should().Be(8); testObserver.Messages - .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() - .ContainInOrder( - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed * 2, Unit.Default), - OnNext(Subscribed * 3, Unit.Default), - OnNext(Subscribed * 3, Unit.Default), - OnNext(Subscribed * 4, Unit.Default) - ); + .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() + .ContainInOrder( + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed * 2, Unit.Default), + OnNext(Subscribed * 3, Unit.Default), + OnNext(Subscribed * 3, Unit.Default), + OnNext(Subscribed * 4, Unit.Default) + ); } [Fact] @@ -191,14 +187,14 @@ public void ShouldScheduleMixed_WithContentModified() testObservable.Subscriptions.Count.Should().Be(11); testObserver.Messages - .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() - .ContainInOrder( - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed * 2, Unit.Default), - OnNext(Subscribed * 3, Unit.Default), - OnNext(Subscribed * 3, Unit.Default), - OnNext(Subscribed * 3, Unit.Default) - ); + .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() + .ContainInOrder( + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed * 2, Unit.Default), + OnNext(Subscribed * 3, Unit.Default), + OnNext(Subscribed * 3, Unit.Default), + OnNext(Subscribed * 3, Unit.Default) + ); } [Fact] @@ -223,13 +219,13 @@ public void ShouldScheduleSerial() testObservable.Subscriptions.Count.Should().Be(4); testObserver.Messages - .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() - .ContainInOrder( - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed * 2, Unit.Default), - OnNext(Subscribed * 3, Unit.Default), - OnNext(Subscribed * 4, Unit.Default) - ); + .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() + .ContainInOrder( + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed * 2, Unit.Default), + OnNext(Subscribed * 3, Unit.Default), + OnNext(Subscribed * 4, Unit.Default) + ); } [Fact] @@ -258,17 +254,17 @@ public void ShouldScheduleWithConcurrency() testObservable.Subscriptions.Count.Should().Be(8); testObserver.Messages - .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() - .ContainInOrder( - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed * 2, Unit.Default), - OnNext(Subscribed * 3, Unit.Default), - OnNext(Subscribed * 4, Unit.Default), - OnNext(Subscribed * 4, Unit.Default), - OnNext(Subscribed * 5, Unit.Default) - ); + .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() + .ContainInOrder( + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed * 2, Unit.Default), + OnNext(Subscribed * 3, Unit.Default), + OnNext(Subscribed * 4, Unit.Default), + OnNext(Subscribed * 4, Unit.Default), + OnNext(Subscribed * 5, Unit.Default) + ); } [Fact] @@ -299,14 +295,14 @@ public void ShouldScheduleWithConcurrency_WithContentModified() testObservable.Subscriptions.Count.Should().Be(11); testObserver.Messages - .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() - .ContainInOrder( - OnNext(Subscribed, Unit.Default), - OnNext(Subscribed * 2, Unit.Default), - OnNext(Subscribed * 3, Unit.Default), - OnNext(Subscribed * 3, Unit.Default), - OnNext(Subscribed * 3, Unit.Default) - ); + .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should() + .ContainInOrder( + OnNext(Subscribed, Unit.Default), + OnNext(Subscribed * 2, Unit.Default), + OnNext(Subscribed * 3, Unit.Default), + OnNext(Subscribed * 3, Unit.Default), + OnNext(Subscribed * 3, Unit.Default) + ); } [Fact] @@ -333,8 +329,8 @@ public void Should_Handle_Cancelled_Tasks() testObservable.Subscriptions.Count.Should().Be(2); errorObservable.Subscriptions.Should().HaveCount(1); var messages = testObserver.Messages - .Where(z => z.Value.Kind != NotificationKind.OnCompleted) - .ToArray(); + .Where(z => z.Value.Kind != NotificationKind.OnCompleted) + .ToArray(); messages.Should().Contain(x => x.Value.Kind == NotificationKind.OnNext && x.Time == Subscribed); messages.Should().Contain(x => x.Value.Kind == NotificationKind.OnError && x.Time == Subscribed * 2 && x.Value.Exception is OperationCanceledException); @@ -365,17 +361,15 @@ public void Should_Handle_Exceptions_Tasks() testObservable.Subscriptions.Count.Should().Be(2); errorObservable.Subscriptions.Should().HaveCount(1); var messages = testObserver.Messages - .Where(z => z.Value.Kind != NotificationKind.OnCompleted) - .ToArray(); + .Where(z => z.Value.Kind != NotificationKind.OnCompleted) + .ToArray(); messages.Should().Contain(x => x.Value.Kind == NotificationKind.OnNext && x.Time == Subscribed); messages.Should().Contain(x => x.Value.Kind == NotificationKind.OnError && x.Time == Subscribed * 2 && x.Value.Exception is NotSameException); messages.Should().Contain(x => x.Value.Kind == NotificationKind.OnNext && x.Time == Subscribed * 3); } - private static SchedulerDelegate DoStuff(IObservable testObservable, IObserver testObserver) - { - return (contentModifiedToken, scheduler) => testObservable.Amb(contentModifiedToken).Do(testObserver); - } + private static SchedulerDelegate DoStuff(IObservable testObservable, IObserver testObserver) => + (contentModifiedToken, scheduler) => testObservable.Amb(contentModifiedToken).Do(testObserver); } } diff --git a/test/JsonRpc.Tests/RequestRouterTests.cs b/test/JsonRpc.Tests/RequestRouterTests.cs index c30729b1e..b67382d74 100644 --- a/test/JsonRpc.Tests/RequestRouterTests.cs +++ b/test/JsonRpc.Tests/RequestRouterTests.cs @@ -1,13 +1,10 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Reactive.Disposables; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.JsonRpc.Serialization; using OmniSharp.Extensions.JsonRpc.Server; using Xunit; using Xunit.Abstractions; @@ -16,22 +13,19 @@ namespace JsonRpc.Tests { public class RequestRouterTests : AutoTestBase { - public RequestRouterTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - Container = JsonRpcTestContainer.Create(testOutputHelper); - } + public RequestRouterTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) => Container = JsonRpcTestContainer.Create(testOutputHelper); [Fact] public async Task ShouldRoute_CustomRequestResponse() { - var collection = new HandlerCollection(new ServiceCollection().BuildServiceProvider()) { }; + var collection = new HandlerCollection(new ServiceCollection().BuildServiceProvider()); var registry = new TestLanguageServerRegistry(); AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var mediator = AutoSubstitute.Resolve(); var method = Substitute.For>>(); method.Invoke(Arg.Any()).Returns(1000L); - registry.OnRequest("$/my/something/awesome", method); + registry.OnRequest("$/my/something/awesome", method); registry.Populate(collection, ServiceProvider); @@ -44,14 +38,14 @@ public async Task ShouldRoute_CustomRequestResponse() [Fact] public async Task ShouldRoute_CustomRequest() { - var collection = new HandlerCollection(new ServiceCollection().BuildServiceProvider()) { }; + var collection = new HandlerCollection(new ServiceCollection().BuildServiceProvider()); var registry = new TestLanguageServerRegistry(); AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var mediator = AutoSubstitute.Resolve(); var method = Substitute.For>(); method.Invoke(Arg.Any()).Returns(Task.CompletedTask); - registry.OnRequest("$/my/something/awesome", method); + registry.OnRequest("$/my/something/awesome", method); registry.Populate(collection, ServiceProvider); @@ -64,13 +58,13 @@ public async Task ShouldRoute_CustomRequest() [Fact] public async Task ShouldRoute_CustomNotification() { - var collection = new HandlerCollection(new ServiceCollection().BuildServiceProvider()) { }; + var collection = new HandlerCollection(new ServiceCollection().BuildServiceProvider()); var registry = new TestLanguageServerRegistry(); AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var mediator = AutoSubstitute.Resolve(); var method = Substitute.For>(); - registry.OnNotification("$/my/something/awesome", method); + registry.OnNotification("$/my/something/awesome", method); registry.Populate(collection, ServiceProvider); @@ -83,7 +77,7 @@ public async Task ShouldRoute_CustomNotification() [Fact] public async Task ShouldRoute_CustomEmptyNotification() { - var collection = new HandlerCollection(new ServiceCollection().BuildServiceProvider()) { }; + var collection = new HandlerCollection(new ServiceCollection().BuildServiceProvider()); var registry = new TestLanguageServerRegistry(); AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); diff --git a/test/JsonRpc.Tests/ResponseRouterTests.cs b/test/JsonRpc.Tests/ResponseRouterTests.cs index c8e3f7366..18a654e23 100644 --- a/test/JsonRpc.Tests/ResponseRouterTests.cs +++ b/test/JsonRpc.Tests/ResponseRouterTests.cs @@ -21,12 +21,13 @@ public async Task WorksWithResultType() var router = new ResponseRouter(outputHandler, new JsonRpcSerializer()); outputHandler - .When(x => x.Send(Arg.Is(x => x.GetType() == typeof(OutgoingRequest)))) - .Do(call => - { - var (method, tcs) = router.GetRequest((long) call.Arg().Id); - tcs.SetResult(new JObject()); - }); + .When(x => x.Send(Arg.Is(x => x.GetType() == typeof(OutgoingRequest)))) + .Do( + call => { + var (method, tcs) = router.GetRequest((long) call.Arg().Id); + tcs.SetResult(new JObject()); + } + ); var response = await router.SendRequest(new ItemParams(), CancellationToken.None); @@ -44,12 +45,13 @@ public async Task WorksWithUnitType() var router = new ResponseRouter(outputHandler, new JsonRpcSerializer()); outputHandler - .When(x => x.Send(Arg.Is(x => x.GetType() == typeof(OutgoingRequest)))) - .Do(call => - { - var (method, tcs) = router.GetRequest((long) call.Arg().Id); - tcs.SetResult(new JObject()); - }); + .When(x => x.Send(Arg.Is(x => x.GetType() == typeof(OutgoingRequest)))) + .Do( + call => { + var (method, tcs) = router.GetRequest((long) call.Arg().Id); + tcs.SetResult(new JObject()); + } + ); await router.SendRequest(new UnitParams(), CancellationToken.None); diff --git a/test/JsonRpc.Tests/Server/ServerShouldThrowCorrectExceptions.cs b/test/JsonRpc.Tests/Server/ServerShouldThrowCorrectExceptions.cs index b5b971fca..39772f0b9 100644 --- a/test/JsonRpc.Tests/Server/ServerShouldThrowCorrectExceptions.cs +++ b/test/JsonRpc.Tests/Server/ServerShouldThrowCorrectExceptions.cs @@ -15,7 +15,7 @@ public ServerShouldThrowCorrectExceptions(ITestOutputHelper outputHelper) : base { } - class Data + private class Data { public string Value { get; set; } } @@ -24,16 +24,16 @@ class Data public async Task Should_Throw_Method_Not_Supported() { var (client, server) = await Initialize( - clientOptions => { - }, - serverOptions => { - serverOptions.OnRequest("method", async (Data data) => new Data() { Value = data.Value}); - }); + clientOptions => { }, + serverOptions => { serverOptions.OnRequest("method", async (Data data) => new Data { Value = data.Value }); } + ); - Func action = () => client.SendRequest("method2", new Data() { - Value = "Echo" - }).Returning(CancellationToken); + Func action = () => client.SendRequest( + "method2", new Data { + Value = "Echo" + } + ).Returning(CancellationToken); await action.Should().ThrowAsync(); } } -} \ No newline at end of file +} diff --git a/test/JsonRpc.Tests/Server/SpecificationReceiverTests.cs b/test/JsonRpc.Tests/Server/SpecificationReceiverTests.cs index a6f5e2af6..d22e19d6a 100644 --- a/test/JsonRpc.Tests/Server/SpecificationReceiverTests.cs +++ b/test/JsonRpc.Tests/Server/SpecificationReceiverTests.cs @@ -26,110 +26,109 @@ public void ShouldRespond_AsExpected2(string json, Renor[] request) var response = result[i]; JsonConvert.SerializeObject(response) - .Should().Be(JsonConvert.SerializeObject(r)); + .Should().Be(JsonConvert.SerializeObject(r)); } } - class SpecificationMessages : TheoryData + private class SpecificationMessages : TheoryData { public SpecificationMessages() { - Add ( + Add( @"{""jsonrpc"": ""2.0"", ""method"": ""subtract"", ""params"": [42, 23], ""id"": 1}", - new Renor[] - { - new Request(1, "subtract", new JArray(new [] {42, 23})) + new Renor[] { + new Request(1, "subtract", new JArray(new[] { 42, 23 })) } ); - Add ( + Add( @"{""jsonrpc"": ""2.0"", ""method"": ""subtract"", ""params"": {""subtrahend"": 23, ""minuend"": 42}, ""id"": 3}", - new Renor[] - { - new Request(3, "subtract", JObject.FromObject(new {subtrahend = 23, minuend = 42})) - }); + new Renor[] { + new Request(3, "subtract", JObject.FromObject(new { subtrahend = 23, minuend = 42 })) + } + ); - Add ( + Add( @"{""jsonrpc"": ""2.0"", ""method"": ""subtract"", ""params"": {""minuend"": 42, ""subtrahend"": 23 }, ""id"": 4}", - new Renor[] - { - new Request(4, "subtract", JObject.FromObject(new {minuend = 42, subtrahend = 23})) - }); + new Renor[] { + new Request(4, "subtract", JObject.FromObject(new { minuend = 42, subtrahend = 23 })) + } + ); - Add ( + Add( @"{""jsonrpc"": ""2.0"", ""method"": ""subtract"", ""id"": 4}", - new Renor[] - { + new Renor[] { new Request(4, "subtract", null) - }); + } + ); // http://www.jsonrpc.org/specification says: // If present, parameters for the rpc call MUST be provided as a Structured value. // Some clients may serialize params as null, instead of omitting it // We're going to pretend we never got the null in the first place. - Add ( + Add( @"{""jsonrpc"": ""2.0"", ""method"": ""subtract"", ""params"": null, ""id"": 4}", - new Renor[] - { + new Renor[] { new Request(4, "subtract", new JObject()) - }); + } + ); - Add ( + Add( @"{""jsonrpc"": ""2.0"", ""method"": ""update"", ""params"": [1,2,3,4,5]}", - new Renor[] - { - new Notification("update", new JArray(new [] {1,2,3,4,5})) - }); + new Renor[] { + new Notification("update", new JArray(new[] { 1, 2, 3, 4, 5 })) + } + ); - Add ( + Add( @"{""jsonrpc"": ""2.0"", ""method"": ""foobar""}", - new Renor[] - { + new Renor[] { new Notification("foobar", null) - }); + } + ); // http://www.jsonrpc.org/specification says: // If present, parameters for the rpc call MUST be provided as a Structured value. // Some clients may serialize params as null, instead of omitting it // We're going to pretend we never got the null in the first place. - Add ( + Add( @"{""jsonrpc"": ""2.0"", ""method"": ""foobar"", ""params"": null}", - new Renor[] - { + new Renor[] { new Notification("foobar", new JObject()) - }); + } + ); - Add ( + Add( @"{""jsonrpc"":""2.0"",""method"":""initialized"",""params"":{}}", new Renor[] { new Notification("initialized", new JObject()), } ); - Add ( + Add( @"{""jsonrpc"": ""2.0"", ""method"": 1, ""params"": ""bar""}", - new Renor[] - { + new Renor[] { new InvalidRequest("1", "Invalid params") - }); + } + ); - Add ( + Add( @"[1]", - new Renor[] - { + new Renor[] { new InvalidRequest("", "Not an object") - }); + } + ); - Add ( + Add( @"[1,2,3]", - new Renor[] - { + new Renor[] { new InvalidRequest("", "Not an object"), new InvalidRequest("", "Not an object"), new InvalidRequest("", "Not an object") - }); + } + ); - Add ( + Add( @"[ {""jsonrpc"": ""2.0"", ""method"": ""sum"", ""params"": [1,2,4], ""id"": ""1""}, {""jsonrpc"": ""2.0"", ""method"": ""notify_hello"", ""params"": [7]}, @@ -138,17 +137,17 @@ public SpecificationMessages() {""jsonrpc"": ""2.0"", ""method"": ""foo.get"", ""params"": {""name"": ""myself""}, ""id"": ""5""}, {""jsonrpc"": ""2.0"", ""method"": ""get_data"", ""id"": ""9""} ]", - new Renor[] - { - new Request("1", "sum", new JArray(new [] {1,2,4})), - new Notification("notify_hello", new JArray(new [] {7})), - new Request("2", "subtract", new JArray(new [] {42,23})), + new Renor[] { + new Request("1", "sum", new JArray(new[] { 1, 2, 4 })), + new Notification("notify_hello", new JArray(new[] { 7 })), + new Request("2", "subtract", new JArray(new[] { 42, 23 })), new InvalidRequest("", "Unexpected protocol"), - new Request("5", "foo.get", JObject.FromObject(new {name = "myself"})), + new Request("5", "foo.get", JObject.FromObject(new { name = "myself" })), new Request("9", "get_data", null), - }); + } + ); - Add ( + Add( @"[ {""jsonrpc"": ""2.0"", ""error"": {""code"": -32600, ""message"": ""Invalid Request"", ""data"": {}}, ""id"": null}, {""jsonrpc"": ""2.0"", ""error"": {""code"": -32600, ""message"": ""Invalid Request"", ""data"": {}}, ""id"": null}, @@ -158,7 +157,8 @@ public SpecificationMessages() new ServerError(new ServerErrorResult(-32600, "Invalid Request")), new ServerError(new ServerErrorResult(-32600, "Invalid Request")), new ServerError(new ServerErrorResult(-32600, "Invalid Request")), - }); + } + ); } } @@ -171,16 +171,16 @@ public void Should_ValidateInvalidMessages(string json, bool expected) result.Should().Be(expected); } - class InvalidMessages : TheoryData + private class InvalidMessages : TheoryData { public InvalidMessages() { - Add (@"[]", false); - Add (@"""""", false); - Add (@"1", false); - Add (@"true", false); - Add (@"[{}]", true); - Add (@"{}", true); + Add(@"[]", false); + Add(@"""""", false); + Add(@"1", false); + Add(@"true", false); + Add(@"[{}]", true); + Add(@"{}", true); } } } diff --git a/test/JsonRpc.Tests/Server/SpecificatiosIdTests.cs b/test/JsonRpc.Tests/Server/SpecificatiosIdTests.cs index dbef54e5d..0b517d976 100644 --- a/test/JsonRpc.Tests/Server/SpecificatiosIdTests.cs +++ b/test/JsonRpc.Tests/Server/SpecificatiosIdTests.cs @@ -24,22 +24,25 @@ public void ShouldParse_SimpleMessages(string message, Type outputType, object e } } - class SimpleTestMessages : TheoryData + private class SimpleTestMessages : TheoryData { public SimpleTestMessages() { - Add ( + Add( @"{ ""jsonrpc"": ""2.0"", ""method"": ""method1"", ""id"": ""canbestring"" }", typeof(string), - "canbestring" as object); - Add ( + "canbestring" + ); + Add( @"{ ""jsonrpc"": ""2.0"", ""method"": ""method1"", ""id"": 12345 }", typeof(long), - 12345L as object); - Add ( + 12345L + ); + Add( @"{ ""jsonrpc"": ""2.0"", ""method"": ""method1"", ""id"": null }", typeof(object), - (object)null); + null + ); } } } diff --git a/test/JsonRpc.Tests/ServiceCollectionSupportTests.cs b/test/JsonRpc.Tests/ServiceCollectionSupportTests.cs index b704a8a6a..32478c3c6 100644 --- a/test/JsonRpc.Tests/ServiceCollectionSupportTests.cs +++ b/test/JsonRpc.Tests/ServiceCollectionSupportTests.cs @@ -17,10 +17,7 @@ public class ServiceCollectionSupportTests { private readonly ITestOutputHelper _testOutputHelper; - public ServiceCollectionSupportTests(ITestOutputHelper testOutputHelper) - { - _testOutputHelper = testOutputHelper; - } + public ServiceCollectionSupportTests(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper; [Fact] public async Task Should_Bootstrap_Server_Through_Service_Collection() @@ -28,16 +25,18 @@ public async Task Should_Bootstrap_Server_Through_Service_Collection() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddJsonRpcServer(options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddSingleton(new OutsideService("servername")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddJsonRpcServer( + options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddSingleton(new OutsideService("servername")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); var server = services.GetRequiredService(); await server.Initialize(cts.Token); @@ -55,17 +54,19 @@ public async Task Inner_Services_Should_Override_Outer_Services() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddJsonRpcServer(options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .WithServices(s => s.AddSingleton(new OutsideService("override"))) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddSingleton(new OutsideService("servername")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddJsonRpcServer( + options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .WithServices(s => s.AddSingleton(new OutsideService("override"))) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddSingleton(new OutsideService("servername")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); var server = services.GetRequiredService(); await server.Initialize(cts.Token); @@ -82,18 +83,21 @@ public async Task Handlers_Can_Be_Added_From_The_Service_Collection() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddJsonRpcServer(options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .WithServices(services => - services.AddJsonRpcHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}) - ); - }) - .AddSingleton(new OutsideService("servername")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddJsonRpcServer( + options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .WithServices( + services => + services.AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + ); + } + ) + .AddSingleton(new OutsideService("servername")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); var server = services.GetRequiredService(); await server.Initialize(cts.Token); @@ -110,21 +114,24 @@ public async Task Handlers_Can_Access_External_Service_Provider() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddJsonRpcServer(options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .WithServices(services => - services - .AddSingleton(new OutsideService("inside")) - .AddJsonRpcHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}) - .AddJsonRpcHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}) - ); - }) - .AddSingleton(new OutsideService("outside")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddJsonRpcServer( + options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .WithServices( + services => + services + .AddSingleton(new OutsideService("inside")) + .AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + .AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + ); + } + ) + .AddSingleton(new OutsideService("outside")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); var server = services.GetRequiredService(); await server.Initialize(cts.Token); @@ -145,21 +152,24 @@ public async Task Handlers_Can_Access_External_Service_Provider_And_Access_New_V cts.CancelAfter(TimeSpan.FromSeconds(30)); var count = 1; var services = new ServiceCollection() - .AddJsonRpcServer(options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .WithServices(services => - services - .AddSingleton(new OutsideService("inside")) - .AddJsonRpcHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}) - .AddJsonRpcHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}) - ); - }) - .AddTransient(_ => new OutsideService($"outside{count++}")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddJsonRpcServer( + options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .WithServices( + services => + services + .AddSingleton(new OutsideService("inside")) + .AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + .AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + ); + } + ) + .AddTransient(_ => new OutsideService($"outside{count++}")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); var server = services.GetRequiredService(); await server.Initialize(cts.Token); @@ -182,23 +192,27 @@ public void Should_Bootstrap_Multiple_Servers_Through_Service_Collection() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddJsonRpcServer("serial", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddJsonRpcServer("parallel", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Parallel}); - }) - .AddSingleton(new OutsideService("outside")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddJsonRpcServer( + "serial", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddJsonRpcServer( + "parallel", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel }); + } + ) + .AddSingleton(new OutsideService("outside")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); var resolver = services.GetRequiredService(); var serialServer = resolver.Get("serial").Should().NotBeNull().And.Subject; @@ -216,83 +230,70 @@ public void Should_Throw_When_Multiple_Servers_Are_Added_And_Attempt_To_Resolve_ cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddJsonRpcServer("serial", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddJsonRpcServer("parallel", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Parallel}); - }) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddJsonRpcServer( + "serial", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddJsonRpcServer( + "parallel", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel }); + } + ) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); Action a = () => services.GetRequiredService(); a.Should().Throw(); } [Method("outside")] - class Request : IRequest + private class Request : IRequest { } [Method("ext-outside")] - class ExternalRequest : IRequest + private class ExternalRequest : IRequest { } - class Response + private class Response { public string Value { get; } - public Response(string value) - { - Value = value; - } + public Response(string value) => Value = value; } - class Handler : IJsonRpcRequestHandler + private class Handler : IJsonRpcRequestHandler { private readonly OutsideService _outsideService; - public Handler(OutsideService outsideService) - { - _outsideService = outsideService; - } + public Handler(OutsideService outsideService) => _outsideService = outsideService; - public Task Handle(Request request, CancellationToken cancellationToken) - { - return Task.FromResult(new Response(_outsideService.Value)); - } + public Task Handle(Request request, CancellationToken cancellationToken) => Task.FromResult(new Response(_outsideService.Value)); } - class ExternalHandler : IJsonRpcRequestHandler + private class ExternalHandler : IJsonRpcRequestHandler { private readonly IExternalServiceProvider _outsideService; - public ExternalHandler(IExternalServiceProvider outsideService) - { - _outsideService = outsideService; - } + public ExternalHandler(IExternalServiceProvider outsideService) => _outsideService = outsideService; - public Task Handle(ExternalRequest request, CancellationToken cancellationToken) - { - return Task.FromResult(new Response(_outsideService.GetRequiredService().Value)); - } + public Task Handle(ExternalRequest request, CancellationToken cancellationToken) => + Task.FromResult(new Response(_outsideService.GetRequiredService().Value)); } - class OutsideService + private class OutsideService { - public OutsideService(string value) - { - Value = value; - } + public OutsideService(string value) => Value = value; public string Value { get; } } diff --git a/test/JsonRpc.Tests/SettlerTests.cs b/test/JsonRpc.Tests/SettlerTests.cs index 0b4dbe5b7..cebb13700 100644 --- a/test/JsonRpc.Tests/SettlerTests.cs +++ b/test/JsonRpc.Tests/SettlerTests.cs @@ -143,25 +143,26 @@ public void Should_Complete_After_Final_Request_Timeout() { var container = CreateContainer(_loggerFactory); container.RegisterMany( - reuse: Reuse.Singleton, - made: Parameters.Of - .Name(nameof(waitTime), defaultValue: waitTime) - .Name(nameof(timeout), defaultValue: timeout) - .Type(defaultValue: CancellationToken) - .Type(defaultValue: scheduler) + Reuse.Singleton, + Parameters.Of + .Name(nameof(waitTime), defaultValue: waitTime) + .Name(nameof(timeout), defaultValue: timeout) + .Type(defaultValue: CancellationToken) + .Type(defaultValue: scheduler) ); - return (container.Resolve(), container.Resolve()); + return ( container.Resolve(), container.Resolve() ); } private static IContainer CreateContainer(ILoggerFactory loggerFactory) { var container = new Container() - .WithDependencyInjectionAdapter(new ServiceCollection().AddLogging()) - .With(rules => rules - .WithResolveIEnumerableAsLazyEnumerable() - .With(FactoryMethod.ConstructorWithResolvableArgumentsIncludingNonPublic) - ); + .WithDependencyInjectionAdapter(new ServiceCollection().AddLogging()) + .With( + rules => rules + .WithResolveIEnumerableAsLazyEnumerable() + .With(FactoryMethod.ConstructorWithResolvableArgumentsIncludingNonPublic) + ); container.RegisterInstance(loggerFactory); return container; diff --git a/test/JsonRpc.Tests/TestLanguageServerRegistry.cs b/test/JsonRpc.Tests/TestLanguageServerRegistry.cs index 388666f03..6a5f97a72 100644 --- a/test/JsonRpc.Tests/TestLanguageServerRegistry.cs +++ b/test/JsonRpc.Tests/TestLanguageServerRegistry.cs @@ -6,28 +6,21 @@ namespace JsonRpc.Tests { public class TestLanguageServerRegistry : JsonRpcCommonMethodsBase, IJsonRpcServerRegistry { - private List Handlers { get; set; } = new List(); - private List<(string name, IJsonRpcHandler handler)> NamedHandlers { get; set; } = new List<(string name, IJsonRpcHandler handler)>(); + private List Handlers { get; } = new List(); + private List<(string name, IJsonRpcHandler handler)> NamedHandlers { get; } = new List<(string name, IJsonRpcHandler handler)>(); - private List<(string name, JsonRpcHandlerFactory handlerFunc)> NamedServiceHandlers { get; set; } = + private List<(string name, JsonRpcHandlerFactory handlerFunc)> NamedServiceHandlers { get; } = new List<(string name, JsonRpcHandlerFactory handlerFunc)>(); - public TestLanguageServerRegistry() - { - } - public override IJsonRpcServerRegistry AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options = null) { - NamedHandlers.Add((method, handler)); + NamedHandlers.Add(( method, handler )); return this; } public override IJsonRpcServerRegistry AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptions options = null) => throw new NotImplementedException(); - public override IJsonRpcServerRegistry AddHandler(JsonRpcHandlerOptions options) - { - throw new NotImplementedException(); - } + public override IJsonRpcServerRegistry AddHandler(JsonRpcHandlerOptions options) => throw new NotImplementedException(); public override IJsonRpcServerRegistry AddHandler(string method, JsonRpcHandlerOptions options = null) => throw new NotImplementedException(); @@ -37,7 +30,7 @@ public override IJsonRpcServerRegistry AddHandler(JsonRpcHandlerOptions optio public override IJsonRpcServerRegistry AddHandler(string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions options = null) { - NamedServiceHandlers.Add((method, handlerFunc)); + NamedServiceHandlers.Add(( method, handlerFunc )); return this; } @@ -63,4 +56,4 @@ internal void Populate(HandlerCollection collection, IServiceProvider servicePro } } } -} \ No newline at end of file +} diff --git a/test/Lsp.Tests/AbsoluteUriConverterTests.cs b/test/Lsp.Tests/AbsoluteUriConverterTests.cs index 5300649f3..f0457d3f7 100644 --- a/test/Lsp.Tests/AbsoluteUriConverterTests.cs +++ b/test/Lsp.Tests/AbsoluteUriConverterTests.cs @@ -11,10 +11,7 @@ public class AbsoluteUriConverterTests { private readonly ITestOutputHelper _testOutputHelper; - public AbsoluteUriConverterTests(ITestOutputHelper testOutputHelper) - { - _testOutputHelper = testOutputHelper; - } + public AbsoluteUriConverterTests(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper; [Theory] [ClassData(typeof(DocumentUriTests.WindowsPathStringUris))] @@ -25,8 +22,8 @@ public void Should_Deserialize_VSCode_Style_Uris(string uri, string expected) { _testOutputHelper.WriteLine($"Given: {uri}"); _testOutputHelper.WriteLine($"Expected: {expected}"); - var serializer = new JsonSerializerSettings() { - Converters = {new DocumentUriConverter()} + var serializer = new JsonSerializerSettings { + Converters = { new DocumentUriConverter() } }; JsonConvert.DeserializeObject($"\"{uri}\"", serializer).ToString().Should().Be(expected); } @@ -40,8 +37,8 @@ public void Should_Serialize_VSCode_Style_Uris(string uri, string expected) { _testOutputHelper.WriteLine($"Given: {uri}"); _testOutputHelper.WriteLine($"Expected: {expected}"); - var serializer = new JsonSerializerSettings() { - Converters = {new DocumentUriConverter()} + var serializer = new JsonSerializerSettings { + Converters = { new DocumentUriConverter() } }; JsonConvert.SerializeObject(DocumentUri.Parse(uri), serializer).Trim('"').Should().Be(expected); } diff --git a/test/Lsp.Tests/Capabilities/Client/ClientCapabilitiesTests.cs b/test/Lsp.Tests/Capabilities/Client/ClientCapabilitiesTests.cs index fcf6da7de..31134cc31 100644 --- a/test/Lsp.Tests/Capabilities/Client/ClientCapabilitiesTests.cs +++ b/test/Lsp.Tests/Capabilities/Client/ClientCapabilitiesTests.cs @@ -13,78 +13,71 @@ namespace Lsp.Tests.Capabilities.Client public class ClientCapabilitiesTests : AutoTestBase { // private const Fixtures = - public ClientCapabilitiesTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } + public ClientCapabilitiesTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) + { + } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new ClientCapabilities() - { - Experimental = new Dictionary() - { - { "abc", "test" } + var model = new ClientCapabilities { + Experimental = new Dictionary { + { "abc", "test" } }, - TextDocument = new TextDocumentClientCapabilities() - { - CodeAction = new CodeActionCapability() { DynamicRegistration = true }, - CodeLens = new CodeLensCapability() { DynamicRegistration = true }, - Definition = new DefinitionCapability() { DynamicRegistration = true, LinkSupport = true }, - Declaration = new DeclarationCapability() { DynamicRegistration = true, LinkSupport = true }, - DocumentHighlight = new DocumentHighlightCapability() { DynamicRegistration = true }, - DocumentLink = new DocumentLinkCapability() { DynamicRegistration = true }, - DocumentSymbol = new DocumentSymbolCapability() { DynamicRegistration = true }, - Formatting = new DocumentFormattingCapability() { DynamicRegistration = true }, - Hover = new HoverCapability() { DynamicRegistration = true }, - OnTypeFormatting = new DocumentOnTypeFormattingCapability() { DynamicRegistration = true }, - RangeFormatting = new DocumentRangeFormattingCapability() { DynamicRegistration = true }, - References = new ReferenceCapability() { DynamicRegistration = true }, - Rename = new RenameCapability() { DynamicRegistration = true }, - SignatureHelp = new SignatureHelpCapability() { DynamicRegistration = true }, - Completion = new CompletionCapability() - { + TextDocument = new TextDocumentClientCapabilities { + CodeAction = new CodeActionCapability { DynamicRegistration = true }, + CodeLens = new CodeLensCapability { DynamicRegistration = true }, + Definition = new DefinitionCapability { DynamicRegistration = true, LinkSupport = true }, + Declaration = new DeclarationCapability { DynamicRegistration = true, LinkSupport = true }, + DocumentHighlight = new DocumentHighlightCapability { DynamicRegistration = true }, + DocumentLink = new DocumentLinkCapability { DynamicRegistration = true }, + DocumentSymbol = new DocumentSymbolCapability { DynamicRegistration = true }, + Formatting = new DocumentFormattingCapability { DynamicRegistration = true }, + Hover = new HoverCapability { DynamicRegistration = true }, + OnTypeFormatting = new DocumentOnTypeFormattingCapability { DynamicRegistration = true }, + RangeFormatting = new DocumentRangeFormattingCapability { DynamicRegistration = true }, + References = new ReferenceCapability { DynamicRegistration = true }, + Rename = new RenameCapability { DynamicRegistration = true }, + SignatureHelp = new SignatureHelpCapability { DynamicRegistration = true }, + Completion = new CompletionCapability { DynamicRegistration = true, - CompletionItem = new CompletionItemCapability() - { + CompletionItem = new CompletionItemCapability { SnippetSupport = true } }, - Implementation = new ImplementationCapability() - { + Implementation = new ImplementationCapability { DynamicRegistration = true, LinkSupport = true }, - TypeDefinition = new TypeDefinitionCapability() - { + TypeDefinition = new TypeDefinitionCapability { DynamicRegistration = true, LinkSupport = true }, - Synchronization = new SynchronizationCapability() - { + Synchronization = new SynchronizationCapability { DynamicRegistration = true, WillSave = true, DidSave = true, WillSaveWaitUntil = true }, - FoldingRange = new FoldingRangeCapability() { + FoldingRange = new FoldingRangeCapability { DynamicRegistration = true, LineFoldingOnly = true, RangeLimit = 5000 }, - SelectionRange = new SelectionRangeCapability() { + SelectionRange = new SelectionRangeCapability { DynamicRegistration = true, LineFoldingOnly = true, RangeLimit = 5000 } - }, - Workspace = new WorkspaceClientCapabilities() - { + Workspace = new WorkspaceClientCapabilities { ApplyEdit = true, - WorkspaceEdit = new WorkspaceEditCapability() { DocumentChanges = true }, - DidChangeConfiguration = new DidChangeConfigurationCapability() { DynamicRegistration = true }, - DidChangeWatchedFiles = new DidChangeWatchedFilesCapability() { DynamicRegistration = true }, - ExecuteCommand = new ExecuteCommandCapability() { DynamicRegistration = true }, - Symbol = new WorkspaceSymbolCapability() { DynamicRegistration = true }, + WorkspaceEdit = new WorkspaceEditCapability { DocumentChanges = true }, + DidChangeConfiguration = new DidChangeConfigurationCapability { DynamicRegistration = true }, + DidChangeWatchedFiles = new DidChangeWatchedFilesCapability { DynamicRegistration = true }, + ExecuteCommand = new ExecuteCommandCapability { DynamicRegistration = true }, + Symbol = new WorkspaceSymbolCapability { DynamicRegistration = true }, } }; var result = Fixture.SerializeObject(model); @@ -92,11 +85,14 @@ public void SimpleTest(string expected) result.Should().Be(expected); var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, o => o - .ConfigureForSupports(Logger)); + deresult.Should().BeEquivalentTo( + model, o => o + .ConfigureForSupports(Logger) + ); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void Github_Issue_75(string expected) { Action a = () => JObject.Parse(expected).ToObject(typeof(ClientCapabilities), new Serializer(ClientVersion.Lsp3).JsonSerializer); diff --git a/test/Lsp.Tests/Capabilities/Client/CompletionCapabilityTests.cs b/test/Lsp.Tests/Capabilities/Client/CompletionCapabilityTests.cs index 4ccb4af96..a39f802e0 100644 --- a/test/Lsp.Tests/Capabilities/Client/CompletionCapabilityTests.cs +++ b/test/Lsp.Tests/Capabilities/Client/CompletionCapabilityTests.cs @@ -7,10 +7,11 @@ namespace Lsp.Tests.Capabilities.Client { public class CompletionCapabilityTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new CompletionCapability() { DynamicRegistration = false, CompletionItem = new CompletionItemCapability() { SnippetSupport = false } }; + var model = new CompletionCapability { DynamicRegistration = false, CompletionItem = new CompletionItemCapability { SnippetSupport = false } }; var result = Fixture.SerializeObject(model); result.Should().Be(expected); diff --git a/test/Lsp.Tests/Capabilities/Client/CompletionItemCapabilityTests.cs b/test/Lsp.Tests/Capabilities/Client/CompletionItemCapabilityTests.cs index aa051446c..896e05fc4 100644 --- a/test/Lsp.Tests/Capabilities/Client/CompletionItemCapabilityTests.cs +++ b/test/Lsp.Tests/Capabilities/Client/CompletionItemCapabilityTests.cs @@ -9,11 +9,11 @@ namespace Lsp.Tests.Capabilities.Client { public class CompletionItemCapabilityTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new CompletionItemCapability() - { + var model = new CompletionItemCapability { SnippetSupport = true }; var result = Fixture.SerializeObject(model); @@ -28,9 +28,11 @@ public void SimpleTest(string expected) public void TagSupportTrue() { var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject("{\"tagSupport\":true}"); - deresult.Should().BeEquivalentTo(new CompletionItemCapability() { - TagSupport = new Supports(true) - }); + deresult.Should().BeEquivalentTo( + new CompletionItemCapability { + TagSupport = new Supports(true) + } + ); } [Fact] diff --git a/test/Lsp.Tests/Capabilities/Client/DynamicCapabilityTests.cs b/test/Lsp.Tests/Capabilities/Client/DynamicCapabilityTests.cs index aa7f43c6c..fef00825c 100644 --- a/test/Lsp.Tests/Capabilities/Client/DynamicCapabilityTests.cs +++ b/test/Lsp.Tests/Capabilities/Client/DynamicCapabilityTests.cs @@ -7,10 +7,11 @@ namespace Lsp.Tests.Capabilities.Client { public class DynamicCapabilityTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DynamicCapability() { DynamicRegistration = false }; + var model = new DynamicCapability { DynamicRegistration = false }; var result = Fixture.SerializeObject(model); result.Should().Be(expected); diff --git a/test/Lsp.Tests/Capabilities/Client/PublishDiagnosticsCapabilityTests.cs b/test/Lsp.Tests/Capabilities/Client/PublishDiagnosticsCapabilityTests.cs index f194d5085..244f1da80 100644 --- a/test/Lsp.Tests/Capabilities/Client/PublishDiagnosticsCapabilityTests.cs +++ b/test/Lsp.Tests/Capabilities/Client/PublishDiagnosticsCapabilityTests.cs @@ -13,9 +13,11 @@ public class PublishDiagnosticsCapabilityTests public void TagSupportTrue() { var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject("{\"tagSupport\":true}"); - deresult.Should().BeEquivalentTo(new PublishDiagnosticsCapability() { - TagSupport = new Supports(true) - }); + deresult.Should().BeEquivalentTo( + new PublishDiagnosticsCapability { + TagSupport = new Supports(true) + } + ); } [Fact] diff --git a/test/Lsp.Tests/Capabilities/Client/SynchronizationCapabilityTests.cs b/test/Lsp.Tests/Capabilities/Client/SynchronizationCapabilityTests.cs index 4c7ea56ad..d8e7e7fc8 100644 --- a/test/Lsp.Tests/Capabilities/Client/SynchronizationCapabilityTests.cs +++ b/test/Lsp.Tests/Capabilities/Client/SynchronizationCapabilityTests.cs @@ -7,11 +7,11 @@ namespace Lsp.Tests.Capabilities.Client { public class SynchronizationCapabilityTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new SynchronizationCapability() - { + var model = new SynchronizationCapability { WillSave = false, WillSaveWaitUntil = false, DidSave = false, diff --git a/test/Lsp.Tests/Capabilities/Client/TextDocumentClientCapabilitiesTests.cs b/test/Lsp.Tests/Capabilities/Client/TextDocumentClientCapabilitiesTests.cs index 4d2bec299..1177e7380 100644 --- a/test/Lsp.Tests/Capabilities/Client/TextDocumentClientCapabilitiesTests.cs +++ b/test/Lsp.Tests/Capabilities/Client/TextDocumentClientCapabilitiesTests.cs @@ -13,34 +13,31 @@ public TextDocumentClientCapabilitiesTests(ITestOutputHelper testOutputHelper) : { } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new TextDocumentClientCapabilities() - { - CodeAction = new CodeActionCapability() { DynamicRegistration = true }, - CodeLens = new CodeLensCapability() { DynamicRegistration = true }, - Definition = new DefinitionCapability() { DynamicRegistration = true }, - DocumentHighlight = new DocumentHighlightCapability() { DynamicRegistration = true }, - DocumentLink = new DocumentLinkCapability() { DynamicRegistration = true }, - DocumentSymbol = new DocumentSymbolCapability() { DynamicRegistration = true }, - Formatting = new DocumentFormattingCapability() { DynamicRegistration = true }, - Hover = new HoverCapability() { DynamicRegistration = true }, - OnTypeFormatting = new DocumentOnTypeFormattingCapability() { DynamicRegistration = true }, - RangeFormatting = new DocumentRangeFormattingCapability() { DynamicRegistration = true }, - References = new ReferenceCapability() { DynamicRegistration = true }, - Rename = new RenameCapability() { DynamicRegistration = true }, - SignatureHelp = new SignatureHelpCapability() { DynamicRegistration = true }, - Completion = new CompletionCapability() - { + var model = new TextDocumentClientCapabilities { + CodeAction = new CodeActionCapability { DynamicRegistration = true }, + CodeLens = new CodeLensCapability { DynamicRegistration = true }, + Definition = new DefinitionCapability { DynamicRegistration = true }, + DocumentHighlight = new DocumentHighlightCapability { DynamicRegistration = true }, + DocumentLink = new DocumentLinkCapability { DynamicRegistration = true }, + DocumentSymbol = new DocumentSymbolCapability { DynamicRegistration = true }, + Formatting = new DocumentFormattingCapability { DynamicRegistration = true }, + Hover = new HoverCapability { DynamicRegistration = true }, + OnTypeFormatting = new DocumentOnTypeFormattingCapability { DynamicRegistration = true }, + RangeFormatting = new DocumentRangeFormattingCapability { DynamicRegistration = true }, + References = new ReferenceCapability { DynamicRegistration = true }, + Rename = new RenameCapability { DynamicRegistration = true }, + SignatureHelp = new SignatureHelpCapability { DynamicRegistration = true }, + Completion = new CompletionCapability { DynamicRegistration = true, - CompletionItem = new CompletionItemCapability() - { + CompletionItem = new CompletionItemCapability { SnippetSupport = true } }, - Synchronization = new SynchronizationCapability() - { + Synchronization = new SynchronizationCapability { DynamicRegistration = true, WillSave = true, DidSave = true, @@ -55,7 +52,8 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model, o => o.ConfigureForSupports(Logger)); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void EmptyTest(string expected) { var model = new TextDocumentClientCapabilities(); diff --git a/test/Lsp.Tests/Capabilities/Client/WorkspaceClientCapabilitiesTests.cs b/test/Lsp.Tests/Capabilities/Client/WorkspaceClientCapabilitiesTests.cs index 128d2f19e..5a5d7c99b 100644 --- a/test/Lsp.Tests/Capabilities/Client/WorkspaceClientCapabilitiesTests.cs +++ b/test/Lsp.Tests/Capabilities/Client/WorkspaceClientCapabilitiesTests.cs @@ -13,17 +13,17 @@ public WorkspaceClientCapabilitiesTests(ITestOutputHelper testOutputHelper) : ba { } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new WorkspaceClientCapabilities() - { + var model = new WorkspaceClientCapabilities { ApplyEdit = true, - WorkspaceEdit = new WorkspaceEditCapability() { DocumentChanges = true }, - DidChangeConfiguration = new DidChangeConfigurationCapability() { DynamicRegistration = true }, - DidChangeWatchedFiles = new DidChangeWatchedFilesCapability() { DynamicRegistration = true }, - ExecuteCommand = new ExecuteCommandCapability() { DynamicRegistration = true }, - Symbol = new WorkspaceSymbolCapability() { DynamicRegistration = true }, + WorkspaceEdit = new WorkspaceEditCapability { DocumentChanges = true }, + DidChangeConfiguration = new DidChangeConfigurationCapability { DynamicRegistration = true }, + DidChangeWatchedFiles = new DidChangeWatchedFilesCapability { DynamicRegistration = true }, + ExecuteCommand = new ExecuteCommandCapability { DynamicRegistration = true }, + Symbol = new WorkspaceSymbolCapability { DynamicRegistration = true }, }; var result = Fixture.SerializeObject(model); @@ -34,7 +34,8 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model, o => o.ConfigureForSupports(Logger)); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void EmptyTest(string expected) { var model = new WorkspaceClientCapabilities(); diff --git a/test/Lsp.Tests/Capabilities/Server/CodeLensOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/CodeLensOptionsTests.cs index 57df3ada7..ff35a0e69 100644 --- a/test/Lsp.Tests/Capabilities/Server/CodeLensOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/CodeLensOptionsTests.cs @@ -8,10 +8,11 @@ namespace Lsp.Tests.Capabilities.Server { public class CodeLensOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new CodeLensOptions() { + var model = new CodeLensOptions { ResolveProvider = true, }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Capabilities/Server/CompletionOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/CompletionOptionsTests.cs index 18a39a867..7b64d6db6 100644 --- a/test/Lsp.Tests/Capabilities/Server/CompletionOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/CompletionOptionsTests.cs @@ -8,10 +8,11 @@ namespace Lsp.Tests.Capabilities.Server { public class CompletionOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new CompletionOptions() { + var model = new CompletionOptions { ResolveProvider = false, }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Capabilities/Server/DocumentLinkOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/DocumentLinkOptionsTests.cs index d63946684..07f08a724 100644 --- a/test/Lsp.Tests/Capabilities/Server/DocumentLinkOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/DocumentLinkOptionsTests.cs @@ -8,10 +8,11 @@ namespace Lsp.Tests.Capabilities.Server { public class DocumentLinkOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DocumentLinkOptions() { + var model = new DocumentLinkOptions { ResolveProvider = true, }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Capabilities/Server/DocumentOnTypeFormattingOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/DocumentOnTypeFormattingOptionsTests.cs index 7dd68a340..eb2f15f79 100644 --- a/test/Lsp.Tests/Capabilities/Server/DocumentOnTypeFormattingOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/DocumentOnTypeFormattingOptionsTests.cs @@ -9,10 +9,11 @@ namespace Lsp.Tests.Capabilities.Server { public class DocumentOnTypeFormattingOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DocumentOnTypeFormattingOptions() { + var model = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = ".", MoreTriggerCharacter = ";`".Select(x => x.ToString()).ToArray(), }; @@ -24,10 +25,11 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void Optional(string expected) { - var model = new DocumentOnTypeFormattingOptions() { + var model = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = "." }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Capabilities/Server/ExecuteCommandOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/ExecuteCommandOptionsTests.cs index 456640461..82924e65c 100644 --- a/test/Lsp.Tests/Capabilities/Server/ExecuteCommandOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/ExecuteCommandOptionsTests.cs @@ -8,11 +8,12 @@ namespace Lsp.Tests.Capabilities.Server { public class ExecuteCommandOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new ExecuteCommandOptions() { - Commands = new string[] { "command1", "command2" } + var model = new ExecuteCommandOptions { + Commands = new[] { "command1", "command2" } }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Capabilities/Server/PrepareRenameTests.cs b/test/Lsp.Tests/Capabilities/Server/PrepareRenameTests.cs index 73b03287a..ac5409622 100644 --- a/test/Lsp.Tests/Capabilities/Server/PrepareRenameTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/PrepareRenameTests.cs @@ -6,7 +6,8 @@ namespace Lsp.Tests.Capabilities.Server { public class PrepareRenameTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void Range(string expected) { var range = new Range( @@ -21,11 +22,11 @@ public void Range(string expected) result.Should().Be(expected); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void PlaceholderRange(string expected) { - var placeholderRange = new PlaceholderRange - { + var placeholderRange = new PlaceholderRange { Range = new Range( new Position(1, 2), new Position(3, 4) diff --git a/test/Lsp.Tests/Capabilities/Server/SaveOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/SaveOptionsTests.cs index 40ab2ab0e..500106983 100644 --- a/test/Lsp.Tests/Capabilities/Server/SaveOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/SaveOptionsTests.cs @@ -8,10 +8,11 @@ namespace Lsp.Tests.Capabilities.Server { public class SaveOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new SaveOptions() { + var model = new SaveOptions { IncludeText = false }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Capabilities/Server/ServerCapabilitiesTests.cs b/test/Lsp.Tests/Capabilities/Server/ServerCapabilitiesTests.cs index 37c42a310..4d4423a81 100644 --- a/test/Lsp.Tests/Capabilities/Server/ServerCapabilitiesTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/ServerCapabilitiesTests.cs @@ -10,60 +10,54 @@ namespace Lsp.Tests.Capabilities.Server { public class ServerCapabilitiesTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new ServerCapabilities() - { + var model = new ServerCapabilities { CodeActionProvider = true, - CodeLensProvider = new CodeLensOptions() - { + CodeLensProvider = new CodeLensOptions { ResolveProvider = true, }, - CompletionProvider = new CompletionOptions() - { + CompletionProvider = new CompletionOptions { ResolveProvider = true, TriggerCharacters = new[] { "a", "b", "c" } }, DefinitionProvider = true, DocumentFormattingProvider = true, DocumentHighlightProvider = true, - DocumentLinkProvider = new DocumentLinkOptions() - { + DocumentLinkProvider = new DocumentLinkOptions { ResolveProvider = true }, - DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions() - { + DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = ".", MoreTriggerCharacter = new[] { ";", " " } }, DocumentRangeFormattingProvider = true, DocumentSymbolProvider = true, - ExecuteCommandProvider = new ExecuteCommandOptions() - { - Commands = new string[] { "command1", "command2" } + ExecuteCommandProvider = new ExecuteCommandOptions { + Commands = new[] { "command1", "command2" } }, - Experimental = new Dictionary() { + Experimental = new Dictionary { { "abc", "123" } }, HoverProvider = true, ReferencesProvider = true, RenameProvider = true, - SignatureHelpProvider = new SignatureHelpOptions() - { + SignatureHelpProvider = new SignatureHelpOptions { TriggerCharacters = new[] { ";", " " } }, - TextDocumentSync = new TextDocumentSync(new TextDocumentSyncOptions() - { - Change = TextDocumentSyncKind.Full, - OpenClose = true, - Save = new SaveOptions() - { - IncludeText = true - }, - WillSave = true, - WillSaveWaitUntil = true - }), + TextDocumentSync = new TextDocumentSync( + new TextDocumentSyncOptions { + Change = TextDocumentSyncKind.Full, + OpenClose = true, + Save = new SaveOptions { + IncludeText = true + }, + WillSave = true, + WillSaveWaitUntil = true + } + ), WorkspaceSymbolProvider = true, ColorProvider = true, FoldingRangeProvider = true, @@ -78,12 +72,12 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void Optional(string expected) { - var model = new ServerCapabilities - { - ColorProvider = (DocumentColorOptions)null + var model = new ServerCapabilities { + ColorProvider = (DocumentColorOptions) null }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Capabilities/Server/SignatureHelpOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/SignatureHelpOptionsTests.cs index 3177800b6..c2786f35f 100644 --- a/test/Lsp.Tests/Capabilities/Server/SignatureHelpOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/SignatureHelpOptionsTests.cs @@ -8,10 +8,11 @@ namespace Lsp.Tests.Capabilities.Server { public class SignatureHelpOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new SignatureHelpOptions() { + var model = new SignatureHelpOptions { TriggerCharacters = new[] { "1", "2" } }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncKindTests.cs b/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncKindTests.cs index 898e4cfd0..c0df2fade 100644 --- a/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncKindTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncKindTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Capabilities.Server { public class TextDocumentSyncKindTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = TextDocumentSyncKind.Full; diff --git a/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncOptionsTests.cs index 427c8b9f2..a157b9f2b 100644 --- a/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncOptionsTests.cs @@ -8,13 +8,14 @@ namespace Lsp.Tests.Capabilities.Server { public class TextDocumentSyncOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new TextDocumentSyncOptions() { + var model = new TextDocumentSyncOptions { Change = TextDocumentSyncKind.Full, OpenClose = true, - Save = new SaveOptions() { + Save = new SaveOptions { IncludeText = true }, WillSave = true, diff --git a/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncTests.cs b/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncTests.cs index f7f0570a9..1eb75b92c 100644 --- a/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/TextDocumentSyncTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Capabilities.Server { public class TextDocumentSyncTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void TextDocumentSyncKind_Full(string expected) { var model = new TextDocumentSync(TextDocumentSyncKind.Full); @@ -20,7 +21,8 @@ public void TextDocumentSyncKind_Full(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void TextDocumentSyncKind_Incremental(string expected) { var model = new TextDocumentSync(TextDocumentSyncKind.Incremental); @@ -32,7 +34,8 @@ public void TextDocumentSyncKind_Incremental(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void TextDocumentSyncKind_None(string expected) { var model = new TextDocumentSync(TextDocumentSyncKind.None); @@ -44,20 +47,21 @@ public void TextDocumentSyncKind_None(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void TextDocumentSyncOptions(string expected) { - var model = new TextDocumentSync(new TextDocumentSyncOptions() - { - OpenClose = true, - Change = TextDocumentSyncKind.Full, - Save = new SaveOptions() - { - IncludeText = true - }, - WillSave = true, - WillSaveWaitUntil = true - }); + var model = new TextDocumentSync( + new TextDocumentSyncOptions { + OpenClose = true, + Change = TextDocumentSyncKind.Full, + Save = new SaveOptions { + IncludeText = true + }, + WillSave = true, + WillSaveWaitUntil = true + } + ); var result = Fixture.SerializeObject(model); result.Should().Be(expected); diff --git a/test/Lsp.Tests/ClientCapabilityProviderFixture.cs b/test/Lsp.Tests/ClientCapabilityProviderFixture.cs index 0ef6e44e6..e05dc1ddc 100644 --- a/test/Lsp.Tests/ClientCapabilityProviderFixture.cs +++ b/test/Lsp.Tests/ClientCapabilityProviderFixture.cs @@ -1,6 +1,5 @@ using Microsoft.Extensions.DependencyInjection; using NSubstitute; -using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; @@ -20,15 +19,15 @@ public ClientCapabilityProviderFixture() var handler = Substitute.For(); handler.GetRegistrationOptions().Returns(new ExecuteCommandRegistrationOptions()); - var handlerCollection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()) { handler }; + var handlerCollection = new SharedHandlerCollection( + SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider() + ) { handler }; var capabilityProvider = new ClientCapabilityProvider(handlerCollection, true); Provider = capabilityProvider; } - public ClientCapabilityProvider.IOptionsGetter GetStaticOptions() - { - return Provider.GetStaticOptions(new Supports(true, new ExecuteCommandCapability { DynamicRegistration = false })); - } + public ClientCapabilityProvider.IOptionsGetter GetStaticOptions() => + Provider.GetStaticOptions(new Supports(true, new ExecuteCommandCapability { DynamicRegistration = false })); } } diff --git a/test/Lsp.Tests/ClientCapabilityProviderTests.cs b/test/Lsp.Tests/ClientCapabilityProviderTests.cs index a65de4fb6..b2dcd7a9f 100644 --- a/test/Lsp.Tests/ClientCapabilityProviderTests.cs +++ b/test/Lsp.Tests/ClientCapabilityProviderTests.cs @@ -6,12 +6,12 @@ using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Server; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; +using OmniSharp.Extensions.LanguageServer.Server; using OmniSharp.Extensions.LanguageServer.Shared; using Xunit; @@ -20,11 +20,16 @@ namespace Lsp.Tests public class ClientCapabilityProviderTests { private static readonly Type[] Capabilities = typeof(ClientCapabilities).Assembly.GetTypes() - .Where(x => x.GetInterfaces().Any(i => - i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ConnectedCapability<>))) - .ToArray(); - - [Theory, MemberData(nameof(AllowSupportedCapabilities))] + .Where( + x => x.GetInterfaces().Any( + i => + i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ConnectedCapability<>) + ) + ) + .ToArray(); + + [Theory] + [MemberData(nameof(AllowSupportedCapabilities))] public void Should_AllowSupportedCapabilities(IJsonRpcHandler handler, object instance) { var textDocumentSyncHandler = @@ -32,26 +37,29 @@ public void Should_AllowSupportedCapabilities(IJsonRpcHandler handler, object in var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()) - {textDocumentSyncHandler, handler}; + { textDocumentSyncHandler, handler }; var provider = new ClientCapabilityProvider(collection, true); HasHandler(provider, instance).Should().BeTrue(); } - public static IEnumerable AllowSupportedCapabilities() - { - return GetItems(Capabilities, type => { - var handlerTypes = GetHandlerTypes(type); - var handler = Substitute.For(handlerTypes.ToArray(), new object[0]); - return new[] { - handler, - Activator.CreateInstance(typeof(Supports<>).MakeGenericType(type), true, - Activator.CreateInstance(type)) - }; - }); - } + public static IEnumerable AllowSupportedCapabilities() => + GetItems( + Capabilities, type => { + var handlerTypes = GetHandlerTypes(type); + var handler = Substitute.For(handlerTypes.ToArray(), new object[0]); + return new[] { + handler, + Activator.CreateInstance( + typeof(Supports<>).MakeGenericType(type), true, + Activator.CreateInstance(type) + ) + }; + } + ); - [Theory, MemberData(nameof(AllowUnsupportedCapabilities))] + [Theory] + [MemberData(nameof(AllowUnsupportedCapabilities))] public void Should_AllowUnsupportedCapabilities(IJsonRpcHandler handler, object instance) { var textDocumentSyncHandler = @@ -59,27 +67,27 @@ public void Should_AllowUnsupportedCapabilities(IJsonRpcHandler handler, object var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()) - {textDocumentSyncHandler, handler}; + { textDocumentSyncHandler, handler }; var provider = new ClientCapabilityProvider(collection, true); HasHandler(provider, instance).Should().BeTrue(); } - public static IEnumerable AllowUnsupportedCapabilities() - { - return GetItems(Capabilities, type => { - var handlerTypes = GetHandlerTypes(type); - var handler = Substitute.For(handlerTypes.ToArray(), new object[0]); - return new[] {handler, Activator.CreateInstance(typeof(Supports<>).MakeGenericType(type), false)}; - }); - } + public static IEnumerable AllowUnsupportedCapabilities() => + GetItems( + Capabilities, type => { + var handlerTypes = GetHandlerTypes(type); + var handler = Substitute.For(handlerTypes.ToArray(), new object[0]); + return new[] { handler, Activator.CreateInstance(typeof(Supports<>).MakeGenericType(type), false) }; + } + ); [Fact] public void Should_Invoke_Get_Delegate() { // Given var stub = Substitute - .For, ExecuteCommandOptions>>(); + .For, ExecuteCommandOptions>>(); var provider = new ClientCapabilityProviderFixture().GetStaticOptions(); // When @@ -103,7 +111,8 @@ public void Should_Invoke_Reduce_Delegate() stub.Received().Invoke(Arg.Any>(), Arg.Any>()); } - [Theory, MemberData(nameof(AllowNullSupportsCapabilities))] + [Theory] + [MemberData(nameof(AllowNullSupportsCapabilities))] public void Should_AllowNullSupportedCapabilities(IJsonRpcHandler handler, object instance) { var textDocumentSyncHandler = @@ -111,23 +120,24 @@ public void Should_AllowNullSupportedCapabilities(IJsonRpcHandler handler, objec var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()) - {textDocumentSyncHandler, handler}; + { textDocumentSyncHandler, handler }; var provider = new ClientCapabilityProvider(collection, true); HasHandler(provider, instance).Should().BeTrue(); } - public static IEnumerable AllowNullSupportsCapabilities() - { - return GetItems(Capabilities, type => { - var handlerTypes = GetHandlerTypes(type); - var handler = Substitute.For(handlerTypes.ToArray(), new object[0]); - return new[] {handler, Activator.CreateInstance(typeof(Supports<>).MakeGenericType(type), true)}; - }); - } + public static IEnumerable AllowNullSupportsCapabilities() => + GetItems( + Capabilities, type => { + var handlerTypes = GetHandlerTypes(type); + var handler = Substitute.For(handlerTypes.ToArray(), new object[0]); + return new[] { handler, Activator.CreateInstance(typeof(Supports<>).MakeGenericType(type), true) }; + } + ); - [Theory, MemberData(nameof(DisallowDynamicSupportsCapabilities))] + [Theory] + [MemberData(nameof(DisallowDynamicSupportsCapabilities))] public void Should_DisallowDynamicSupportedCapabilities(IJsonRpcHandler handler, object instance) { var textDocumentSyncHandler = @@ -135,23 +145,23 @@ public void Should_DisallowDynamicSupportedCapabilities(IJsonRpcHandler handler, var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()) - {textDocumentSyncHandler, handler}; + { textDocumentSyncHandler, handler }; var provider = new ClientCapabilityProvider(collection, true); HasHandler(provider, instance).Should().BeFalse(); } - public static IEnumerable DisallowDynamicSupportsCapabilities() - { - return GetItems(Capabilities, type => { - var handlerTypes = GetHandlerTypes(type); - var handler = Substitute.For(handlerTypes.ToArray(), new object[0]); - var capability = Activator.CreateInstance(type); - if (capability is DynamicCapability dyn) dyn.DynamicRegistration = true; - return new[] - {handler, Activator.CreateInstance(typeof(Supports<>).MakeGenericType(type), true, capability)}; - }); - } + public static IEnumerable DisallowDynamicSupportsCapabilities() => + GetItems( + Capabilities, type => { + var handlerTypes = GetHandlerTypes(type); + var handler = Substitute.For(handlerTypes.ToArray(), new object[0]); + var capability = Activator.CreateInstance(type); + if (capability is DynamicCapability dyn) dyn.DynamicRegistration = true; + return new[] + { handler, Activator.CreateInstance(typeof(Supports<>).MakeGenericType(type), true, capability) }; + } + ); [Fact] public void Should_Handle_Mixed_Capabilities() @@ -165,21 +175,25 @@ public void Should_Handle_Mixed_Capabilities() var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()) - {textDocumentSyncHandler, codeActionHandler, definitionHandler, typeDefinitionHandler}; + { textDocumentSyncHandler, codeActionHandler, definitionHandler, typeDefinitionHandler }; var provider = new ClientCapabilityProvider(collection, true); - var capabilities = new ClientCapabilities() { - TextDocument = new TextDocumentClientCapabilities() { - CodeAction = new Supports(true, new CodeActionCapability() { - DynamicRegistration = false, - }), - TypeDefinition = new Supports(true, new TypeDefinitionCapability() { - DynamicRegistration = true, - }) + var capabilities = new ClientCapabilities { + TextDocument = new TextDocumentClientCapabilities { + CodeAction = new Supports( + true, new CodeActionCapability { + DynamicRegistration = false, + } + ), + TypeDefinition = new Supports( + true, new TypeDefinitionCapability { + DynamicRegistration = true, + } + ) } }; provider.GetStaticOptions(capabilities.TextDocument.CodeAction) - .Get(CodeActionOptions.Of).Should().NotBeNull(); + .Get(CodeActionOptions.Of).Should().NotBeNull(); provider.HasStaticHandler(capabilities.TextDocument.Definition).Should().BeTrue(); provider.HasStaticHandler(capabilities.TextDocument.TypeDefinition).Should().BeFalse(); } @@ -192,11 +206,11 @@ public void GH162_TextDocumentSync_Should_Work_Without_WillSave_Or_WillSaveWaitU var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()) - {textDocumentSyncHandler}; + { 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, @@ -223,9 +237,9 @@ public void GH162_TextDocumentSync_Should_Work_With_WillSave_Or_WillSaveWaitUnti didSaveTextDocumentHandler }; 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, @@ -237,31 +251,24 @@ 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) - { - 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 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 GenericHasHandler(ClientCapabilityProvider provider, Supports supports) - where T : DynamicCapability, ConnectedCapability - { - return provider.HasStaticHandler(supports); - } + where T : DynamicCapability, ConnectedCapability => + provider.HasStaticHandler(supports); - private static IEnumerable GetItems(IEnumerable types, Func> func) - { - return types.Select(x => func(x).ToArray()); - } + private static IEnumerable GetItems(IEnumerable types, Func> func) => types.Select(x => func(x).ToArray()); - private static IEnumerable GetHandlerTypes(Type type) - { - return type.GetTypeInfo().ImplementedInterfaces - .Where(x => x.GetTypeInfo().IsGenericType && - x.GetTypeInfo().GetGenericTypeDefinition() == typeof(ConnectedCapability<>)) + private static IEnumerable GetHandlerTypes(Type type) => + type.GetTypeInfo().ImplementedInterfaces + .Where( + x => x.GetTypeInfo().IsGenericType && + x.GetTypeInfo().GetGenericTypeDefinition() == typeof(ConnectedCapability<>) + ) .Select(x => x.GetTypeInfo().GetGenericArguments()[0]); - } } } diff --git a/test/Lsp.Tests/CodeActionKindTests.cs b/test/Lsp.Tests/CodeActionKindTests.cs index 74c9de20e..ed078269a 100644 --- a/test/Lsp.Tests/CodeActionKindTests.cs +++ b/test/Lsp.Tests/CodeActionKindTests.cs @@ -13,10 +13,11 @@ public class CodeActionKindTests public void DefaultBehavior_Should_Only_Support_InitialSymbolKinds() { var serializer = new Serializer(); - var json = serializer.SerializeObject(new CodeAction() - { - Kind = CodeActionKind.Source - }); + var json = serializer.SerializeObject( + new CodeAction { + Kind = CodeActionKind.Source + } + ); var result = serializer.DeserializeObject(json); result.Kind.Should().Be(CodeActionKind.Source); @@ -26,26 +27,28 @@ public void DefaultBehavior_Should_Only_Support_InitialSymbolKinds() public void CustomBehavior_When_SymbolKind_Defined_By_Client() { var serializer = new Serializer(); - serializer.SetClientCapabilities(ClientVersion.Lsp3, new ClientCapabilities() - { - TextDocument = new TextDocumentClientCapabilities - { - CodeAction = new Supports(true, new CodeActionCapability() - { - DynamicRegistration = true, - CodeActionLiteralSupport = new CodeActionLiteralSupportCapability() { - CodeActionKind = new CodeActionKindCapability() { - ValueSet = new Container(CodeActionKind.RefactorInline) + serializer.SetClientCapabilities( + ClientVersion.Lsp3, new ClientCapabilities { + TextDocument = new TextDocumentClientCapabilities { + CodeAction = new Supports( + true, new CodeActionCapability { + DynamicRegistration = true, + CodeActionLiteralSupport = new CodeActionLiteralSupportCapability { + CodeActionKind = new CodeActionKindCapability { + ValueSet = new Container(CodeActionKind.RefactorInline) + } + } } - } - }) + ) + } } - }); + ); - var json = serializer.SerializeObject(new CodeAction() - { - Kind = CodeActionKind.QuickFix - }); + var json = serializer.SerializeObject( + new CodeAction { + Kind = CodeActionKind.QuickFix + } + ); var result = serializer.DeserializeObject(json); result.Kind.Should().Be(CodeActionKind.RefactorInline); diff --git a/test/Lsp.Tests/CompletionItemKindTests.cs b/test/Lsp.Tests/CompletionItemKindTests.cs index 01f63a8eb..ad5ad6165 100644 --- a/test/Lsp.Tests/CompletionItemKindTests.cs +++ b/test/Lsp.Tests/CompletionItemKindTests.cs @@ -13,9 +13,11 @@ public class CompletionItemKindTests public void DefaultBehavior_Should_Only_Support_InitialCompletionItemKinds() { var serializer = new Serializer(); - var json = serializer.SerializeObject(new CompletionItem() { - Kind = CompletionItemKind.Event - }); + var json = serializer.SerializeObject( + new CompletionItem { + Kind = CompletionItemKind.Event + } + ); var result = serializer.DeserializeObject(json); result.Kind.Should().Be(CompletionItemKind.Event); @@ -25,9 +27,11 @@ public void DefaultBehavior_Should_Only_Support_InitialCompletionItemKinds() public void DefaultBehavior_Should_Only_Support_InitialCompletionItemTags() { var serializer = new Serializer(); - var json = serializer.SerializeObject(new CompletionItem() { - Tags = new Container(CompletionItemTag.Deprecated) - }); + var json = serializer.SerializeObject( + new CompletionItem { + Tags = new Container(CompletionItemTag.Deprecated) + } + ); var result = serializer.DeserializeObject(json); result.Tags.Should().Contain(CompletionItemTag.Deprecated); @@ -37,20 +41,26 @@ public void DefaultBehavior_Should_Only_Support_InitialCompletionItemTags() public void CustomBehavior_When_CompletionItemKinds_Defined_By_Client() { var serializer = new Serializer(); - serializer.SetClientCapabilities(ClientVersion.Lsp3, new ClientCapabilities() { - TextDocument = new TextDocumentClientCapabilities { - Completion = new Supports(true, new CompletionCapability() { - DynamicRegistration = true, - CompletionItemKind = new CompletionItemKindCapability() { - ValueSet = new Container(CompletionItemKind.Class) - } - }) + serializer.SetClientCapabilities( + ClientVersion.Lsp3, new ClientCapabilities { + TextDocument = new TextDocumentClientCapabilities { + Completion = new Supports( + true, new CompletionCapability { + DynamicRegistration = true, + CompletionItemKind = new CompletionItemKindCapability { + ValueSet = new Container(CompletionItemKind.Class) + } + } + ) + } } - }); + ); - var json = serializer.SerializeObject(new CompletionItem() { - Kind = CompletionItemKind.Event - }); + var json = serializer.SerializeObject( + new CompletionItem { + Kind = CompletionItemKind.Event + } + ); var result = serializer.DeserializeObject(json); result.Kind.Should().Be(CompletionItemKind.Class); @@ -60,26 +70,31 @@ public void CustomBehavior_When_CompletionItemKinds_Defined_By_Client() public void CustomBehavior_When_CompletionItemTags_Defined_By_Client() { var serializer = new Serializer(); - serializer.SetClientCapabilities(ClientVersion.Lsp3, new ClientCapabilities() { - TextDocument = new TextDocumentClientCapabilities { - Completion = new Supports(true, new CompletionCapability() { - DynamicRegistration = true, - CompletionItem = new CompletionItemCapability() { - TagSupport = new CompletionItemTagSupportCapability() { - ValueSet = new Container() + serializer.SetClientCapabilities( + ClientVersion.Lsp3, new ClientCapabilities { + TextDocument = new TextDocumentClientCapabilities { + Completion = new Supports( + true, new CompletionCapability { + DynamicRegistration = true, + CompletionItem = new CompletionItemCapability { + TagSupport = new CompletionItemTagSupportCapability { + ValueSet = new Container() + } + } } - } - }) + ) + } } - }); + ); - var json = serializer.SerializeObject(new CompletionItem() { - Tags = new Container(CompletionItemTag.Deprecated) - }); + var json = serializer.SerializeObject( + new CompletionItem { + Tags = new Container(CompletionItemTag.Deprecated) + } + ); var result = serializer.DeserializeObject(json); result.Tags.Should().BeEmpty(); } } } - diff --git a/test/Lsp.Tests/DiagnosticKindTests.cs b/test/Lsp.Tests/DiagnosticKindTests.cs index 9fdd55495..f8588358a 100644 --- a/test/Lsp.Tests/DiagnosticKindTests.cs +++ b/test/Lsp.Tests/DiagnosticKindTests.cs @@ -13,10 +13,11 @@ public class DiagnosticKindTests public void DefaultBehavior_Should_Only_Support_InitialDiagnosticTags() { var serializer = new Serializer(); - var json = serializer.SerializeObject(new Diagnostic() - { - Tags = new Container(DiagnosticTag.Deprecated) - }); + var json = serializer.SerializeObject( + new Diagnostic { + Tags = new Container(DiagnosticTag.Deprecated) + } + ); var result = serializer.DeserializeObject(json); result.Tags.Should().Contain(DiagnosticTag.Deprecated); @@ -26,23 +27,25 @@ public void DefaultBehavior_Should_Only_Support_InitialDiagnosticTags() public void CustomBehavior_When_DiagnosticTag_Defined_By_Client() { var serializer = new Serializer(); - serializer.SetClientCapabilities(ClientVersion.Lsp3, new ClientCapabilities() - { - TextDocument = new TextDocumentClientCapabilities - { - PublishDiagnostics = new Supports(true, new PublishDiagnosticsCapability() - { - TagSupport = new PublishDiagnosticsTagSupportCapability() { - ValueSet = new Container() - } - }) + serializer.SetClientCapabilities( + ClientVersion.Lsp3, new ClientCapabilities { + TextDocument = new TextDocumentClientCapabilities { + PublishDiagnostics = new Supports( + true, new PublishDiagnosticsCapability { + TagSupport = new PublishDiagnosticsTagSupportCapability { + ValueSet = new Container() + } + } + ) + } } - }); + ); - var json = serializer.SerializeObject(new Diagnostic() - { - Tags = new Container(DiagnosticTag.Deprecated) - }); + var json = serializer.SerializeObject( + new Diagnostic { + Tags = new Container(DiagnosticTag.Deprecated) + } + ); var result = serializer.DeserializeObject(json); result.Tags.Should().BeEmpty(); diff --git a/test/Lsp.Tests/DocumentSymbolKindTests.cs b/test/Lsp.Tests/DocumentSymbolKindTests.cs index 6eb0a79a1..0f234212d 100644 --- a/test/Lsp.Tests/DocumentSymbolKindTests.cs +++ b/test/Lsp.Tests/DocumentSymbolKindTests.cs @@ -1,9 +1,10 @@ using FluentAssertions; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; 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; + #pragma warning disable 618 namespace Lsp.Tests @@ -14,10 +15,11 @@ public class DocumentSymbolKindTests public void DefaultBehavior_Should_Only_Support_InitialSymbolKinds() { var serializer = new Serializer(); - var json = serializer.SerializeObject(new SymbolInformation() - { - Kind = SymbolKind.Event - }); + var json = serializer.SerializeObject( + new SymbolInformation { + Kind = SymbolKind.Event + } + ); var result = serializer.DeserializeObject(json); result.Kind.Should().Be(SymbolKind.Event); @@ -27,10 +29,11 @@ public void DefaultBehavior_Should_Only_Support_InitialSymbolKinds() public void DefaultBehavior_Should_Only_Support_InitialSymbolTags() { var serializer = new Serializer(); - var json = serializer.SerializeObject(new SymbolInformation() - { - Tags = new Container(SymbolTag.Deprecated) - }); + var json = serializer.SerializeObject( + new SymbolInformation { + Tags = new Container(SymbolTag.Deprecated) + } + ); var result = serializer.DeserializeObject(json); result.Tags.Should().Contain(SymbolTag.Deprecated); @@ -40,25 +43,26 @@ public void DefaultBehavior_Should_Only_Support_InitialSymbolTags() public void CustomBehavior_When_SymbolKind_Defined_By_Client() { var serializer = new Serializer(); - serializer.SetClientCapabilities(ClientVersion.Lsp3, new ClientCapabilities() - { - TextDocument = new TextDocumentClientCapabilities - { - DocumentSymbol = new Supports(true, new DocumentSymbolCapability() - { - DynamicRegistration = true, - SymbolKind = new SymbolKindCapability() - { - ValueSet = new Container(SymbolKind.Class) - } - }) + serializer.SetClientCapabilities( + ClientVersion.Lsp3, new ClientCapabilities { + TextDocument = new TextDocumentClientCapabilities { + DocumentSymbol = new Supports( + true, new DocumentSymbolCapability { + DynamicRegistration = true, + SymbolKind = new SymbolKindCapability { + ValueSet = new Container(SymbolKind.Class) + } + } + ) + } } - }); + ); - var json = serializer.SerializeObject(new DocumentSymbol() - { - Kind = SymbolKind.Event - }); + var json = serializer.SerializeObject( + new DocumentSymbol { + Kind = SymbolKind.Event + } + ); var result = serializer.DeserializeObject(json); result.Kind.Should().Be(SymbolKind.Class); @@ -68,24 +72,26 @@ public void CustomBehavior_When_SymbolKind_Defined_By_Client() public void CustomBehavior_When_SymbolTag_Defined_By_Client() { var serializer = new Serializer(); - serializer.SetClientCapabilities(ClientVersion.Lsp3, new ClientCapabilities() - { - TextDocument = new TextDocumentClientCapabilities - { - DocumentSymbol = new Supports(true, new DocumentSymbolCapability() - { - DynamicRegistration = true, - TagSupport = new TagSupportCapability() { - ValueSet = new Container() - } - }) + serializer.SetClientCapabilities( + ClientVersion.Lsp3, new ClientCapabilities { + TextDocument = new TextDocumentClientCapabilities { + DocumentSymbol = new Supports( + true, new DocumentSymbolCapability { + DynamicRegistration = true, + TagSupport = new TagSupportCapability { + ValueSet = new Container() + } + } + ) + } } - }); + ); - var json = serializer.SerializeObject(new DocumentSymbol() - { - Tags = new Container(SymbolTag.Deprecated) - }); + var json = serializer.SerializeObject( + new DocumentSymbol { + Tags = new Container(SymbolTag.Deprecated) + } + ); var result = serializer.DeserializeObject(json); result.Tags.Should().BeEmpty(); diff --git a/test/Lsp.Tests/DocumentUriTests.cs b/test/Lsp.Tests/DocumentUriTests.cs index 66b7e5d76..e97f5a923 100644 --- a/test/Lsp.Tests/DocumentUriTests.cs +++ b/test/Lsp.Tests/DocumentUriTests.cs @@ -13,10 +13,7 @@ public class DocumentUriTests { private readonly ITestOutputHelper _testOutputHelper; - public DocumentUriTests(ITestOutputHelper testOutputHelper) - { - _testOutputHelper = testOutputHelper; - } + public DocumentUriTests(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper; [Fact] public void IsEquatable() @@ -26,8 +23,8 @@ public void IsEquatable() var uri3 = DocumentUri.Parse("file:///c:/Users/mb/src/gh/Cake.Json/src/Cake.Json/NotNamespaces.cs"); uri1.Should().Be(uri2); uri1.Should().NotBe(uri3); - (uri1 == uri2).Should().BeTrue(); - (uri1 != uri2).Should().BeFalse(); + ( uri1 == uri2 ).Should().BeTrue(); + ( uri1 != uri2 ).Should().BeFalse(); } [Theory] @@ -43,7 +40,9 @@ public class WindowsFileSystemPaths : BaseSourceDestination { private const string WindowsPath = "c:\\Users\\mb\\src\\gh\\Cake.Json\\src\\Cake.Json\\{0}s.cs"; - public WindowsFileSystemPaths() : base(WindowsPath, "file:///c:/Users/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs") { } + public WindowsFileSystemPaths() : base(WindowsPath, "file:///c:/Users/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs") + { + } } [Theory] @@ -59,7 +58,9 @@ public class UncFileSystemPaths : BaseSourceDestination { private const string UncPath = "\\\\myserver\\Users\\mb\\src\\gh\\Cake.Json\\src\\Cake.Json\\{0}s.cs"; - public UncFileSystemPaths() : base(UncPath, "file://myserver/Users/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs") { } + public UncFileSystemPaths() : base(UncPath, "file://myserver/Users/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs") + { + } } [Theory] @@ -75,7 +76,9 @@ public class UnixFileSystemPaths : BaseSourceDestination { private const string UnixPath = "/usr/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; - public UnixFileSystemPaths() : base(UnixPath, "file:///usr/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs") { } + public UnixFileSystemPaths() : base(UnixPath, "file:///usr/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs") + { + } } [Theory] @@ -91,7 +94,9 @@ public class WindowsPathStringUris : BaseSourceDestination { private const string WindowsPath = "file:///c:/Users/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; - public WindowsPathStringUris() : base(WindowsPath, WindowsPath) { } + public WindowsPathStringUris() : base(WindowsPath, WindowsPath) + { + } } [Theory] @@ -107,7 +112,9 @@ public class WindowsPathAltStringUris : BaseSourceDestination { private const string WindowsPathAlt = "file://c:/Users/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; - public WindowsPathAltStringUris() : base(WindowsPathAlt, WindowsPathAlt) { } + public WindowsPathAltStringUris() : base(WindowsPathAlt, WindowsPathAlt) + { + } } [Theory] @@ -123,7 +130,9 @@ public class UncPathStringUris : BaseSourceDestination { private const string UncPath = "file://myserver/Users/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; - public UncPathStringUris() : base(UncPath, UncPath) { } + public UncPathStringUris() : base(UncPath, UncPath) + { + } } [Theory] @@ -139,7 +148,9 @@ public class UnixPathStringUris : BaseSourceDestination { private const string UnixPath = "file:///usr/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; - public UnixPathStringUris() : base(UnixPath, UnixPath) { } + public UnixPathStringUris() : base(UnixPath, UnixPath) + { + } } [Theory] @@ -155,13 +166,19 @@ public void Should_Handle_Resource_String_Uris(string uri, string expected) public class ResourceStringUris : BaseSourceDestination { private const string ResourcePath = "untitled:{0}-1"; - public ResourceStringUris() : base(ResourcePath, ResourcePath) { } + + public ResourceStringUris() : base(ResourcePath, ResourcePath) + { + } } public class ResourceStringUrisWithPaths : BaseSourceDestination { private const string ResourcePathWithPath = "untitled:{0}-1/some/path"; - public ResourceStringUrisWithPaths() : base(ResourcePathWithPath, ResourcePathWithPath) { } + + public ResourceStringUrisWithPaths() : base(ResourcePathWithPath, ResourcePathWithPath) + { + } } [Theory] @@ -176,7 +193,10 @@ public void Should_Handle_Windows_Uris(Uri uri, string expected) public class WindowsPathUris : UriSourceDestination { private const string WindowsPath = "file:///c:/Users/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; - public WindowsPathUris() : base(WindowsPath, WindowsPath) { } + + public WindowsPathUris() : base(WindowsPath, WindowsPath) + { + } } [Theory] @@ -191,7 +211,10 @@ public void Should_Handle_Unc_Uris(Uri uri, string expected) public class UncPathUris : UriSourceDestination { private const string UncPath = "file://myserver/Users/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; - public UncPathUris() : base(UncPath, UncPath) { } + + public UncPathUris() : base(UncPath, UncPath) + { + } } [Theory] @@ -206,7 +229,10 @@ public void Should_Handle_Unix_Uris(Uri uri, string expected) public class UnixPathUris : UriSourceDestination { private const string UnixPath = "file:///usr/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; - public UnixPathUris() : base(UnixPath, UnixPath) { } + + public UnixPathUris() : base(UnixPath, UnixPath) + { + } } [Theory] @@ -223,7 +249,9 @@ public class WindowsFileSystemToFileUri : BaseSourceDestination private const string WindowsSourcePath = "c:\\Users\\mb\\src\\gh\\Cake.Json\\src\\Cake.Json\\{0}s.cs"; private const string WindowsDestinationPath = "file:///c:/Users/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; - public WindowsFileSystemToFileUri() : base(WindowsSourcePath, WindowsDestinationPath) { } + public WindowsFileSystemToFileUri() : base(WindowsSourcePath, WindowsDestinationPath) + { + } } [Theory] @@ -240,7 +268,9 @@ public class UncFileSystemToFileUri : BaseSourceDestination private const string UncSourcePath = "\\\\myserver\\Users\\mb\\src\\gh\\Cake.Json\\src\\Cake.Json\\{0}s.cs"; private const string UncDestinationPath = "file://myserver/Users/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; - public UncFileSystemToFileUri() : base(UncSourcePath, UncDestinationPath) { } + public UncFileSystemToFileUri() : base(UncSourcePath, UncDestinationPath) + { + } } [Theory] @@ -257,7 +287,9 @@ public class UnixFileSystemToFileUri : BaseSourceDestination private const string UnixSourcePath = "/usr/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; private const string UnixDestinationPath = "file:///usr/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; - public UnixFileSystemToFileUri() : base(UnixSourcePath, UnixDestinationPath) { } + public UnixFileSystemToFileUri() : base(UnixSourcePath, UnixDestinationPath) + { + } } [Theory] @@ -274,7 +306,9 @@ public class WindowsFileUriToFileSystem : UriSourceDestination private const string WindowsSourcePath = "file:///c:/Users/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; private const string WindowsDestinationPath = "c:\\Users\\mb\\src\\gh\\Cake.Json\\src\\Cake.Json\\{0}s.cs"; - public WindowsFileUriToFileSystem() : base(WindowsSourcePath, WindowsDestinationPath, false) { } + public WindowsFileUriToFileSystem() : base(WindowsSourcePath, WindowsDestinationPath, false) + { + } } [Theory] @@ -291,7 +325,9 @@ public class UncFileUriToFileSystem : UriSourceDestination private const string UncSourcePath = "file://myserver/Users/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; private const string UncDestinationPath = "\\\\myserver\\Users\\mb\\src\\gh\\Cake.Json\\src\\Cake.Json\\{0}s.cs"; - public UncFileUriToFileSystem() : base(UncSourcePath, UncDestinationPath, false) { } + public UncFileUriToFileSystem() : base(UncSourcePath, UncDestinationPath, false) + { + } } [Theory] @@ -308,10 +344,12 @@ public class UnixFileUriToFileSystem : UriSourceDestination private const string UnixSourcePath = "file:///usr/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; private const string UnixDestinationPath = "/usr/mb/src/gh/Cake.Json/src/Cake.Json/{0}s.cs"; - public UnixFileUriToFileSystem() : base(UnixSourcePath, UnixDestinationPath, false) { } + public UnixFileUriToFileSystem() : base(UnixSourcePath, UnixDestinationPath, false) + { + } } - private static string[] EncodedStrings = new[] {"Namespace", "Пространствоимен", "汉字漢字", "のはでした", "コンサート"}; + private static readonly string[] EncodedStrings = { "Namespace", "Пространствоимен", "汉字漢字", "のはでした", "コンサート" }; public class UriSourceDestination : IEnumerable { @@ -333,24 +371,30 @@ public IEnumerator GetEnumerator() { var encodedData = _encode ? Uri.EscapeDataString(data) : data; if (_sourceFormat.Replace("c:", "c%3A") != string.Format(_sourceFormat, data)) - items.Add(( - new Uri(string.Format(_sourceFormat, data).Replace("c:", "c%3A")), - string.Format(_destinationFormat, encodedData) - )); + items.Add( + ( + new Uri(string.Format(_sourceFormat, data).Replace("c:", "c%3A")), + string.Format(_destinationFormat, encodedData) + ) + ); if (_sourceFormat.Replace("c:", "c%3a") != string.Format(_sourceFormat, data)) - items.Add(( - new Uri(string.Format(_sourceFormat, data).Replace("c:", "c%3a")), + items.Add( + ( + new Uri(string.Format(_sourceFormat, data).Replace("c:", "c%3a")), + string.Format(_destinationFormat, encodedData) + ) + ); + items.Add( + ( + new Uri(string.Format(_sourceFormat, data)), string.Format(_destinationFormat, encodedData) - )); - items.Add(( - new Uri(string.Format(_sourceFormat, data)), - string.Format(_destinationFormat, encodedData) - )); + ) + ); } foreach (var item in items.Distinct()) { - yield return new object[] {item.source, item.destination}; + yield return new object[] { item.source, item.destination }; } } @@ -374,24 +418,30 @@ public IEnumerator GetEnumerator() foreach (var data in EncodedStrings) { if (_sourceFormat.Replace("c:", "c%3A") != string.Format(_sourceFormat, data)) - items.Add(( - string.Format(_sourceFormat, data).Replace("c:", "c%3A"), - string.Format(_destinationFormat, Uri.EscapeDataString(data)) - )); + items.Add( + ( + string.Format(_sourceFormat, data).Replace("c:", "c%3A"), + string.Format(_destinationFormat, Uri.EscapeDataString(data)) + ) + ); if (_sourceFormat.Replace("c:", "c%3a") != string.Format(_sourceFormat, data)) - items.Add(( - string.Format(_sourceFormat, data).Replace("c:", "c%3a"), + items.Add( + ( + string.Format(_sourceFormat, data).Replace("c:", "c%3a"), + string.Format(_destinationFormat, Uri.EscapeDataString(data)) + ) + ); + items.Add( + ( + string.Format(_sourceFormat, data), string.Format(_destinationFormat, Uri.EscapeDataString(data)) - )); - items.Add(( - string.Format(_sourceFormat, data), - string.Format(_destinationFormat, Uri.EscapeDataString(data)) - )); + ) + ); } foreach (var item in items.Distinct()) { - yield return new object[] {item.source, item.destination}; + yield return new object[] { item.source, item.destination }; } } diff --git a/test/Lsp.Tests/ExecuteCommandSyncHandlerExtensions.cs b/test/Lsp.Tests/ExecuteCommandSyncHandlerExtensions.cs index c79b9f074..34bc679a5 100644 --- a/test/Lsp.Tests/ExecuteCommandSyncHandlerExtensions.cs +++ b/test/Lsp.Tests/ExecuteCommandSyncHandlerExtensions.cs @@ -8,14 +8,11 @@ namespace Lsp.Tests { internal static class ExecuteCommandSyncExtensions { - public static IExecuteCommandHandler With(Container commands) - { - return Substitute.For().With(commands); - } + public static IExecuteCommandHandler With(Container commands) => Substitute.For().With(commands); public static IExecuteCommandHandler With(this IExecuteCommandHandler handler, Container commands) { - ((IExecuteCommandHandler)handler).GetRegistrationOptions().Returns(new ExecuteCommandRegistrationOptions { Commands = commands }); + handler.GetRegistrationOptions().Returns(new ExecuteCommandRegistrationOptions { Commands = commands }); handler.Handle(Arg.Any(), Arg.Any()).Returns(Unit.Value); diff --git a/test/Lsp.Tests/Fixture.cs b/test/Lsp.Tests/Fixture.cs index d01c4459d..fc37f0036 100644 --- a/test/Lsp.Tests/Fixture.cs +++ b/test/Lsp.Tests/Fixture.cs @@ -3,18 +3,15 @@ using System.IO; using System.Text; using Newtonsoft.Json; -using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; -using Serializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Serializer; +using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; +using ISerializer = OmniSharp.Extensions.JsonRpc.ISerializer; namespace Lsp.Tests { - static class Fixture + internal static class Fixture { - public static string SerializeObject(object value, ClientVersion version = ClientVersion.Lsp3) - { - return SerializeObject(value, null, (JsonSerializerSettings)null, version); - } + public static string SerializeObject(object value, ClientVersion version = ClientVersion.Lsp3) => SerializeObject(value, null, null, version); public static string SerializeObject(object value, Type type, JsonSerializerSettings settings, ClientVersion version = ClientVersion.Lsp3) { @@ -35,7 +32,7 @@ private static string SerializeObjectInternal(object value, Type type, ISerializ serializer.JsonSerializer.Serialize(jsonWriter, value, type); } - return sw.ToString()?.Replace("\r\n", "\n")?.TrimEnd();//?.Replace("\n", "\r\n"); + return sw.ToString()?.Replace("\r\n", "\n")?.TrimEnd(); //?.Replace("\n", "\r\n"); } } } diff --git a/test/Lsp.Tests/FluentAssertionsExtensions.cs b/test/Lsp.Tests/FluentAssertionsExtensions.cs index 06ae3a6a2..ae9bc7278 100644 --- a/test/Lsp.Tests/FluentAssertionsExtensions.cs +++ b/test/Lsp.Tests/FluentAssertionsExtensions.cs @@ -9,41 +9,38 @@ namespace Lsp.Tests { public static class FluentAssertionsExtensions { - 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>() - ; - } + 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>(); } } diff --git a/test/Lsp.Tests/FoundationTests.cs b/test/Lsp.Tests/FoundationTests.cs index 2449b36d0..cfd5fec46 100644 --- a/test/Lsp.Tests/FoundationTests.cs +++ b/test/Lsp.Tests/FoundationTests.cs @@ -13,18 +13,14 @@ using Microsoft.Extensions.Logging; using NSubstitute; using NSubstitute.Core; -using NSubstitute.Extensions; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Client; -using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Document.Proposals; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; using OmniSharp.Extensions.LanguageServer.Server; using Xunit; @@ -36,17 +32,11 @@ 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 { @@ -54,7 +44,12 @@ public ActionDelegateData() { { var baseOptions = new LanguageServerOptions().WithPipe(new Pipe()); - void BaseDelegate(LanguageServerOptions o) => o.WithPipe(new Pipe()); + + void BaseDelegate(LanguageServerOptions o) + { + o.WithPipe(new Pipe()); + } + var serviceProvider = new ServiceCollection().BuildServiceProvider(); Add(new ActionDelegate("create (server): options", () => LanguageServer.Create(baseOptions))); Add(new ActionDelegate("create (server): options, serviceProvider", () => LanguageServer.Create(baseOptions, serviceProvider))); @@ -63,16 +58,29 @@ public ActionDelegateData() Add(new ActionDelegate("from (server): options", () => LanguageServer.From(baseOptions))); 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))); + Add( + new ActionDelegate( + "from (server): options, serviceProvider, cancellationToken", () => LanguageServer.From(baseOptions, serviceProvider, CancellationToken.None) + ) + ); Add(new ActionDelegate("from (server): options, serviceProvider", () => LanguageServer.From(baseOptions, serviceProvider))); Add(new ActionDelegate("from (server): action", () => LanguageServer.From(BaseDelegate))); 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))); + Add( + new ActionDelegate( + "from (server): action, serviceProvider, cancellationToken", () => LanguageServer.From(BaseDelegate, serviceProvider, CancellationToken.None) + ) + ); Add(new ActionDelegate("from (server): action, serviceProvider", () => LanguageServer.From(BaseDelegate, serviceProvider))); } { var baseOptions = new LanguageClientOptions().WithPipe(new Pipe()); - void BaseDelegate(LanguageClientOptions o) => o.WithPipe(new Pipe()); + + void BaseDelegate(LanguageClientOptions o) + { + o.WithPipe(new Pipe()); + } + var serviceProvider = new ServiceCollection().BuildServiceProvider(); Add(new ActionDelegate("create (client): options", () => LanguageClient.Create(baseOptions))); Add(new ActionDelegate("create (client): options, serviceProvider", () => LanguageClient.Create(baseOptions, serviceProvider))); @@ -81,11 +89,19 @@ public ActionDelegateData() Add(new ActionDelegate("from (client): options", () => LanguageClient.From(baseOptions))); 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))); + Add( + new ActionDelegate( + "from (client): options, serviceProvider, cancellationToken", () => LanguageClient.From(baseOptions, serviceProvider, CancellationToken.None) + ) + ); Add(new ActionDelegate("from (client): options, serviceProvider", () => LanguageClient.From(baseOptions, serviceProvider))); Add(new ActionDelegate("from (client): action", () => LanguageClient.From(BaseDelegate))); 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))); + Add( + new ActionDelegate( + "from (client): action, serviceProvider, cancellationToken", () => LanguageClient.From(BaseDelegate, serviceProvider, CancellationToken.None) + ) + ); Add(new ActionDelegate("from (client): action, serviceProvider", () => LanguageClient.From(BaseDelegate, serviceProvider))); } } @@ -99,7 +115,7 @@ public class ActionDelegate public ActionDelegate(string name, Action method) { _name = name; - this.Method = method; + Method = method; } public override string ToString() => _name; @@ -119,14 +135,14 @@ public void Debugger_Display_Should_Not_Throw(Type type) a2.Should().NotThrow().And.NotBeNull(); } - class DebuggerDisplayTypes : TheoryData + private class DebuggerDisplayTypes : TheoryData { public DebuggerDisplayTypes() { foreach (var item in typeof(DocumentSymbol).Assembly.ExportedTypes - .Where(z => !z.IsGenericTypeDefinition) - .Where(z => z.GetCustomAttributes().Any(z => z.Value.StartsWith("{DebuggerDisplay"))) - .Where(z => z.GetConstructors().Any(z => z.GetParameters().Length == 0)) + .Where(z => !z.IsGenericTypeDefinition) + .Where(z => z.GetCustomAttributes().Any(z => z.Value.StartsWith("{DebuggerDisplay"))) + .Where(z => z.GetConstructors().Any(z => z.GetParameters().Length == 0)) ) { Add(item); @@ -136,19 +152,15 @@ 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"); - } + .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"); - } + .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))] @@ -179,150 +191,171 @@ public void HandlersShouldAbstractClass(ILspHandlerTypeDescriptor descriptor) 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(z => - abstractHandler.IsAssignableFrom(z) - && abstractHandler != z - && !z.IsGenericTypeDefinition + var delegatingHandler = descriptor.HandlerType.Assembly.DefinedTypes.FirstOrDefault( + z => + abstractHandler.IsAssignableFrom(z) + && abstractHandler != z + && !z.IsGenericTypeDefinition ); if (delegatingHandler != null) { _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"); } } [Theory(DisplayName = "Handler extension method classes with appropriately named methods")] [ClassData(typeof(TypeHandlerExtensionData))] - public void HandlersShouldExtensionMethodClassWithMethods(ILspHandlerTypeDescriptor descriptor, string onMethodName, string sendMethodName, - Type extensionClass, string extensionClassName) + public void HandlersShouldExtensionMethodClassWithMethods( + ILspHandlerTypeDescriptor descriptor, string onMethodName, string sendMethodName, + Type extensionClass, string extensionClassName + ) { // This test requires a refactor, the delegating handlers have been removed and replaced by shared implementations // TODO: // * Check for IPartialItem(s)<> extension methods // * Also update events to have a nicer fire and forget abstract class - _logger.LogInformation("Handler: {Type} {Extension} {ExtensionName} {OnMethod} {SendMethod}", descriptor.HandlerType, - extensionClass, extensionClassName, onMethodName, sendMethodName); + _logger.LogInformation( + "Handler: {Type} {Extension} {ExtensionName} {OnMethod} {SendMethod}", descriptor.HandlerType, + extensionClass, extensionClassName, onMethodName, sendMethodName + ); 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() - .BeTrue($"{descriptor.HandlerType.FullName} is missing event extension methods named {onMethodName}"); + .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() - .BeTrue($"{descriptor.HandlerType.FullName} is missing execute extension methods named {sendMethodName}"); + .BeTrue($"{descriptor.HandlerType.FullName} is missing execute extension methods named {sendMethodName}"); var registries = extensionClass.GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(z => z.Name == onMethodName || z.Name == sendMethodName) - .Select(z => z.GetParameters()[0].ParameterType) - .Distinct() - .ToHashSet(); + .Where(z => z.Name == onMethodName || z.Name == sendMethodName) + .Select(z => z.GetParameters()[0].ParameterType) + .Distinct() + .ToHashSet(); if (descriptor.Direction == Direction.Bidirectional) { registries - .Where(z => typeof(ILanguageClientProxy).IsAssignableFrom(z) || typeof(ILanguageServerRegistry).IsAssignableFrom(z)) - .Should().HaveCountGreaterOrEqualTo(1, - $"{descriptor.HandlerType.FullName} there should be methods for both handing the event and sending the event"); + .Where(z => typeof(ILanguageClientProxy).IsAssignableFrom(z) || typeof(ILanguageServerRegistry).IsAssignableFrom(z)) + .Should().HaveCountGreaterOrEqualTo( + 1, + $"{descriptor.HandlerType.FullName} there should be methods for both handing the event and sending the event" + ); registries - .Where(z => typeof(ILanguageServerProxy).IsAssignableFrom(z) || typeof(ILanguageClientRegistry).IsAssignableFrom(z)) - .Should().HaveCountGreaterOrEqualTo(1, - $"{descriptor.HandlerType.FullName} there should be methods for both handing the event and sending the event"); + .Where(z => typeof(ILanguageServerProxy).IsAssignableFrom(z) || typeof(ILanguageClientRegistry).IsAssignableFrom(z)) + .Should().HaveCountGreaterOrEqualTo( + 1, + $"{descriptor.HandlerType.FullName} there should be methods for both handing the event and sending the event" + ); } else if (descriptor.Direction == Direction.ServerToClient) { registries - .Where(z => typeof(ILanguageServerProxy).IsAssignableFrom(z) || typeof(ILanguageClientRegistry).IsAssignableFrom(z)) - .Should().HaveCountGreaterOrEqualTo(1, - $"{descriptor.HandlerType.FullName} there should be methods for both handing the event and sending the event"); + .Where(z => typeof(ILanguageServerProxy).IsAssignableFrom(z) || typeof(ILanguageClientRegistry).IsAssignableFrom(z)) + .Should().HaveCountGreaterOrEqualTo( + 1, + $"{descriptor.HandlerType.FullName} there should be methods for both handing the event and sending the event" + ); registries - .Where(z => typeof(ILanguageClientProxy).IsAssignableFrom(z) || typeof(ILanguageServerRegistry).IsAssignableFrom(z)) - .Should().HaveCount(0, $"{descriptor.HandlerType.FullName} must not cross the streams or be made bidirectional"); + .Where(z => typeof(ILanguageClientProxy).IsAssignableFrom(z) || typeof(ILanguageServerRegistry).IsAssignableFrom(z)) + .Should().HaveCount(0, $"{descriptor.HandlerType.FullName} must not cross the streams or be made bidirectional"); } else if (descriptor.Direction == Direction.ClientToServer) { registries - .Where(z => typeof(ILanguageClientProxy).IsAssignableFrom(z) || typeof(ILanguageServerRegistry).IsAssignableFrom(z)) - .Should().HaveCountGreaterOrEqualTo(1, - $"{descriptor.HandlerType.FullName} there should be methods for both handing the event and sending the event"); + .Where(z => typeof(ILanguageClientProxy).IsAssignableFrom(z) || typeof(ILanguageServerRegistry).IsAssignableFrom(z)) + .Should().HaveCountGreaterOrEqualTo( + 1, + $"{descriptor.HandlerType.FullName} there should be methods for both handing the event and sending the event" + ); registries - .Where(z => typeof(ILanguageServerProxy).IsAssignableFrom(z) || typeof(ILanguageClientRegistry).IsAssignableFrom(z)) - .Should().HaveCount(0, $"{descriptor.HandlerType.FullName} must not cross the streams or be made bidirectional"); + .Where(z => typeof(ILanguageServerProxy).IsAssignableFrom(z) || typeof(ILanguageClientRegistry).IsAssignableFrom(z)) + .Should().HaveCount(0, $"{descriptor.HandlerType.FullName} must not cross the streams or be made bidirectional"); } } [Theory(DisplayName = "Handler all expected extensions methods based on method direction")] [ClassData(typeof(TypeHandlerExtensionData))] - public void HandlersShouldHaveExpectedExtensionMethodsBasedOnDirection(ILspHandlerTypeDescriptor descriptor, string onMethodName, string sendMethodName, - Type extensionClass, string extensionClassName) + public void HandlersShouldHaveExpectedExtensionMethodsBasedOnDirection( + ILspHandlerTypeDescriptor descriptor, string onMethodName, string sendMethodName, + Type extensionClass, string extensionClassName + ) { - _logger.LogInformation("Handler: {Type} {Extension} {ExtensionName} {OnMethod} {SendMethod}", descriptor.HandlerType, - extensionClass, extensionClassName, onMethodName, sendMethodName); + _logger.LogInformation( + "Handler: {Type} {Extension} {ExtensionName} {OnMethod} {SendMethod}", descriptor.HandlerType, + 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"))}, + 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"))}, + 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"))}, + { ( "Server", info => info.ParameterType.Name.EndsWith("Client") ), ( "Client", info => info.ParameterType.Name.EndsWith("Server") ) }, _ => throw new NotImplementedException(descriptor.HandlerType.FullName) }; foreach (var item in expectedEventRegistries) { extensionClass.GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(z => z.Name == onMethodName) - .Where(z => item.matcher(z.GetParameters()[0])) - .Should().HaveCountGreaterOrEqualTo(1, $"{descriptor.HandlerType.FullName} is missing a registry implementation for {item.type}"); + .Where(z => z.Name == onMethodName) + .Where(z => item.matcher(z.GetParameters()[0])) + .Should().HaveCountGreaterOrEqualTo(1, $"{descriptor.HandlerType.FullName} is missing a registry implementation for {item.type}"); } foreach (var item in expectedRequestHandlers) { extensionClass.GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(z => z.Name == sendMethodName) - .Where(z => item.matcher(z.GetParameters()[0])) - .Should().HaveCountGreaterOrEqualTo(1, $"{descriptor.HandlerType.FullName} is missing a request implementation for {item.type}"); + .Where(z => z.Name == sendMethodName) + .Where(z => item.matcher(z.GetParameters()[0])) + .Should().HaveCountGreaterOrEqualTo(1, $"{descriptor.HandlerType.FullName} is missing a request implementation for {item.type}"); } } [Theory(DisplayName = "Extension methods handle partial results for partial items")] [ClassData(typeof(TypeHandlerExtensionData))] - public void HandlersShouldHaveActionsForBothCompleteAndPartialResults(ILspHandlerTypeDescriptor descriptor, string onMethodName, string sendMethodName, - Type extensionClass, string extensionClassName) + public void HandlersShouldHaveActionsForBothCompleteAndPartialResults( + ILspHandlerTypeDescriptor descriptor, string onMethodName, string sendMethodName, + Type extensionClass, string extensionClassName + ) { - _logger.LogInformation("Handler: {Type} {Extension} {ExtensionName} {OnMethod} {SendMethod}", descriptor.HandlerType, - extensionClass, extensionClassName, onMethodName, sendMethodName); + _logger.LogInformation( + "Handler: {Type} {Extension} {ExtensionName} {OnMethod} {SendMethod}", descriptor.HandlerType, + extensionClass, extensionClassName, onMethodName, sendMethodName + ); var onMethodRegistries = extensionClass.GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(z => z.Name == onMethodName) - .Select(z => z.GetParameters()[0].ParameterType) - .Distinct() - .ToHashSet(); + .Where(z => z.Name == onMethodName) + .Select(z => z.GetParameters()[0].ParameterType) + .Distinct() + .ToHashSet(); var sendMethodRegistries = extensionClass.GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(z => z.Name == sendMethodName) - .Select(z => z.GetParameters()[0].ParameterType) - .Distinct() - .ToHashSet(); + .Where(z => z.Name == sendMethodName) + .Select(z => z.GetParameters()[0].ParameterType) + .Distinct() + .ToHashSet(); { var matcher = new MethodMatcher(onMethodRegistries, descriptor, extensionClass); Func ForAnyParameter(Func m) { - return (info) => info.GetParameters().Any(m); + return info => info.GetParameters().Any(m); } Func ForParameter(int index, Func m) { - return (info) => m(info.GetParameters()[index]); + return info => m(info.GetParameters()[index]); } var containsCancellationToken = ForAnyParameter(info => info.ParameterType.GetGenericArguments().Reverse().Take(2).Any(x => x == typeof(CancellationToken))); @@ -340,20 +373,26 @@ Func ForParameter(int index, Func m) 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, - takesCapability, containsCancellationToken, returns); + matcher.Match( + $"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 observesPartialResultType = ForAnyParameter(info => - info.ParameterType.GetGenericArguments().Skip(1).FirstOrDefault() == typeof(IObserver<>).MakeGenericType(descriptor.PartialItemType)); + var observesPartialResultType = ForAnyParameter( + info => + 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($"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, - containsCancellationToken, observesPartialResultType); + matcher.Match( + $"Action<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType.Name}>, CancellationToken>", isAction, takesParameter, + containsCancellationToken, observesPartialResultType + ); // matcher.Match($"Func<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType.Name}>, CancellationToken, Task>", isFunc, takesParameter, // containsCancellationToken, observesPartialResultType, returnsTask); if (descriptor.HasCapability) @@ -362,7 +401,8 @@ Func ForParameter(int index, Func m) $"Action<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType.Name}>, {descriptor.CapabilityType.Name}, CancellationToken>", isAction, takesParameter, - capability, containsCancellationToken, observesPartialResultType); + capability, containsCancellationToken, observesPartialResultType + ); // matcher.Match( // $"Func<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType.Name}>, {descriptor.CapabilityType.Name}, CancellationToken, Task>", // isFunc, @@ -374,17 +414,23 @@ Func ForParameter(int index, Func m) if (descriptor.HasPartialItems) { 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(typeof(IEnumerable<>).MakeGenericType(descriptor.PartialItemsType))); - - matcher.Match($"Action<{descriptor.ParamsType.Name}, IObserver>>", isAction, takesParameter, - observesPartialResultType); + var observesPartialResultType = ForAnyParameter( + info => + info.ParameterType.GetGenericArguments().Skip(1).FirstOrDefault() == + typeof(IObserver<>).MakeGenericType(typeof(IEnumerable<>).MakeGenericType(descriptor.PartialItemsType)) + ); + + matcher.Match( + $"Action<{descriptor.ParamsType.Name}, IObserver>>", isAction, takesParameter, + observesPartialResultType + ); // matcher.Match($"Func<{descriptor.ParamsType.Name}, IObserver>, Task>", isFunc, takesParameter, // observesPartialResultType, returnsTask); - matcher.Match($"Action<{descriptor.ParamsType.Name}, IObserver>, CancellationToken>", isAction, + matcher.Match( + $"Action<{descriptor.ParamsType.Name}, IObserver>, CancellationToken>", isAction, takesParameter, - containsCancellationToken, observesPartialResultType); + containsCancellationToken, observesPartialResultType + ); // matcher.Match($"Func<{descriptor.ParamsType.Name}, IObserver>, CancellationToken, Task>", isFunc, // takesParameter, // containsCancellationToken, observesPartialResultType, returnsTask); @@ -394,7 +440,8 @@ Func ForParameter(int index, Func m) $"Action<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemsType.Name}>, {descriptor.CapabilityType.Name}, CancellationToken>", isAction, takesParameter, - capability, containsCancellationToken, observesPartialResultType); + capability, containsCancellationToken, observesPartialResultType + ); // matcher.Match( // $"Func<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemsType.Name}>, {descriptor.CapabilityType.Name}, CancellationToken, Task>", // isFunc, @@ -412,10 +459,14 @@ Func ForParameter(int index, Func m) 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, - takesCapability, containsCancellationToken, returns); - matcher.Match($"Action<{descriptor.ParamsType.Name}, {descriptor.CapabilityType.Name}, CancellationToken>", isAction, takesParameter, takesCapability, - containsCancellationToken); + matcher.Match( + $"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, + containsCancellationToken + ); } } } @@ -431,17 +482,20 @@ Func ForParameter(int index, Func m) { Func partialReturnType = info => typeof(IRequestProgressObservable<,>).MakeGenericType(typeof(IEnumerable<>).MakeGenericType(descriptor.PartialItemsType), descriptor.ResponseType) - .IsAssignableFrom(info.ReturnType); + .IsAssignableFrom(info.ReturnType); matcher.Match( $"Func<{descriptor.ParamsType.Name}, CancellationToken, IProgressObservable, {descriptor.ResponseType.Name}>>", - takesParameter, containsCancellationToken, partialReturnType); + takesParameter, containsCancellationToken, partialReturnType + ); } else if (descriptor.IsRequest && descriptor.HasPartialItem) { Func partialReturnType = info => 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); + matcher.Match( + $"Func<{descriptor.ParamsType.Name}, CancellationToken, IProgressObservable<{descriptor.PartialItemType.Name}, {descriptor.ResponseType.Name}>>", + takesParameter, containsCancellationToken, partialReturnType + ); } else if (descriptor.IsRequest) { @@ -455,15 +509,17 @@ Func ForParameter(int index, Func m) } - class MethodMatcher + private class MethodMatcher { private readonly IEnumerable _registries; private readonly ILspHandlerTypeDescriptor _descriptor; private readonly Type _extensionClass; private readonly string _methodName; - public MethodMatcher(IEnumerable registries, - ILspHandlerTypeDescriptor descriptor, Type extensionClass, string methodName = null) + public MethodMatcher( + IEnumerable registries, + ILspHandlerTypeDescriptor descriptor, Type extensionClass, string methodName = null + ) { _registries = registries; _descriptor = descriptor; @@ -476,54 +532,68 @@ public void Match(string description, params Func[] matchers) foreach (var registry in _registries) { var methods = _extensionClass.GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(z => _methodName == null || z.Name == _methodName) - .Where(z => matchers.All(matcher => matcher(z))) - .ToHashSet(); - methods.Count.Should().BeGreaterThan(0, - $"{_descriptor.HandlerType.FullName} missing extension with parameter type {description} method for {registry.FullName}"); + .Where(z => _methodName == null || z.Name == _methodName) + .Where(z => matchers.All(matcher => matcher(z))) + .ToHashSet(); + methods.Count.Should().BeGreaterThan( + 0, + $"{_descriptor.HandlerType.FullName} missing extension with parameter type {description} method for {registry.FullName}" + ); foreach (var method in methods) { if (method.Name == GetOnMethodName(_descriptor)) { - var registrySub = Substitute.For(new Type[] {method.GetParameters()[0].ParameterType}, Array.Empty()); + var registrySub = Substitute.For(new[] { method.GetParameters()[0].ParameterType }, Array.Empty()); SubstitutionContext.Current.GetCallRouterFor(registrySub).SetReturnForType( method.GetParameters()[0].ParameterType, - (IReturn) new ReturnValue(registrySub) + new ReturnValue(registrySub) ); // registrySub.ReturnsForAll(x => registrySub); - method.Invoke(null, + method.Invoke( + null, new[] { - registrySub, Substitute.For(new Type[] {method.GetParameters()[1].ParameterType}, Array.Empty()), - }.Concat(method.GetParameters().Skip(2).Select(z => - !z.ParameterType.IsGenericType - ? Activator.CreateInstance(z.ParameterType) - : Substitute.For(new Type[] {z.ParameterType}, Array.Empty())) - ) - .ToArray()); + registrySub, Substitute.For(new[] { method.GetParameters()[1].ParameterType }, Array.Empty()), + }.Concat( + method.GetParameters().Skip(2).Select( + z => + !z.ParameterType.IsGenericType + ? Activator.CreateInstance(z.ParameterType) + : Substitute.For(new[] { z.ParameterType }, Array.Empty()) + ) + ) + .ToArray() + ); registrySub.Received().ReceivedCalls() - .Any(z => z.GetMethodInfo().Name == nameof(IJsonRpcHandlerRegistry>.AddHandler) && - z.GetArguments().Length == 3 && - z.GetArguments()[0].Equals(_descriptor.Method)) - .Should().BeTrue($"{_descriptor.HandlerType.Name} {description} should have the correct method."); + .Any( + z => z.GetMethodInfo().Name == nameof(IJsonRpcHandlerRegistry>.AddHandler) && + z.GetArguments().Length == 3 && + z.GetArguments()[0].Equals(_descriptor.Method) + ) + .Should().BeTrue($"{_descriptor.HandlerType.Name} {description} should have the correct method."); if (_descriptor.HasRegistration && method.GetParameters().Length == 3) { - method.GetParameters()[2].ParameterType.Should().Be(_descriptor.RegistrationType, - $"{_descriptor.HandlerType.FullName} {description} is has incorrect registration type {method.GetParameters()[2].ParameterType.FullName}"); + method.GetParameters()[2].ParameterType.Should().Be( + _descriptor.RegistrationType, + $"{_descriptor.HandlerType.FullName} {description} is has incorrect registration type {method.GetParameters()[2].ParameterType.FullName}" + ); method.GetParameters()[2].IsOptional.Should() - .BeFalse($"{_descriptor.HandlerType.FullName} {description} Registration types should not be optional"); + .BeFalse($"{_descriptor.HandlerType.FullName} {description} Registration types should not be optional"); } } if (_descriptor.IsRequest && method.Name == GetSendMethodName(_descriptor)) { - method.GetParameters().Last().ParameterType.Should().Be(typeof(CancellationToken), - $"{_descriptor.HandlerType.Name} {description} send method must have optional cancellation token"); + method.GetParameters().Last().ParameterType.Should().Be( + typeof(CancellationToken), + $"{_descriptor.HandlerType.Name} {description} send method must have optional cancellation token" + ); method.GetParameters().Last().IsOptional.Should().BeTrue( - $"{_descriptor.HandlerType.Name} {description} send method must have optional cancellation token"); + $"{_descriptor.HandlerType.Name} {description} send method must have optional cancellation token" + ); } } } @@ -534,8 +604,10 @@ public class ParamsShouldHaveMethodAttributeData : TheoryData { public ParamsShouldHaveMethodAttributeData() { - foreach (var type in typeof(CompletionParams).Assembly.ExportedTypes.Where(z => - z.IsClass && !z.IsAbstract && z.GetInterfaces().Any(z => z.IsGenericType && typeof(IRequest<>).IsAssignableFrom(z.GetGenericTypeDefinition())))) + foreach (var type in typeof(CompletionParams).Assembly.ExportedTypes.Where( + z => + z.IsClass && !z.IsAbstract && z.GetInterfaces().Any(z => z.IsGenericType && typeof(IRequest<>).IsAssignableFrom(z.GetGenericTypeDefinition())) + )) { Add(type); } @@ -547,8 +619,8 @@ public class HandlersShouldHaveMethodAttributeData : TheoryData 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)}) + .Where(z => !z.Name.EndsWith("Manager")) + .Except(new[] { typeof(ITextDocumentSyncHandler) }) ) { if (type.IsGenericTypeDefinition && !MethodAttribute.AllFrom(type).Any()) continue; @@ -562,8 +634,8 @@ public class TypeHandlerData : TheoryData 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)}) + .Where(z => !z.Name.EndsWith("Manager")) + .Except(new[] { typeof(ITextDocumentSyncHandler) }) ) { if (type.IsGenericTypeDefinition && !MethodAttribute.AllFrom(type).Any()) continue; @@ -574,7 +646,7 @@ public TypeHandlerData() public class TypeHandlerExtensionData : TheoryData { - public static Type[] HandlersToSkip = new[] { + public static Type[] HandlersToSkip = { typeof(ISemanticTokensHandler), typeof(ISemanticTokensDeltaHandler), typeof(ISemanticTokensRangeHandler), @@ -583,9 +655,9 @@ public class TypeHandlerExtensionData : TheoryData z.IsInterface && typeof(IJsonRpcHandler).IsAssignableFrom(z)) - .Where(z => !z.Name.EndsWith("Manager")) - .Except(new[] {typeof(ITextDocumentSyncHandler)}) + .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; @@ -610,44 +682,36 @@ public TypeHandlerExtensionData() } } - private static string GetExtensionClassName(IHandlerTypeDescriptor descriptor) - { - return SpecialCasedHandlerName(descriptor) + "Extensions"; - ; - } + private static string GetExtensionClassName(IHandlerTypeDescriptor descriptor) => SpecialCasedHandlerName(descriptor) + "Extensions"; - private static string SpecialCasedHandlerName(IHandlerTypeDescriptor descriptor) - { - return new Regex(@"(\w+(?:\`\d)?)$") - .Replace(descriptor.HandlerType.Name ?? string.Empty, - descriptor.HandlerType.Name.Substring(1, descriptor.HandlerType.Name.IndexOf("Handler", StringComparison.Ordinal) - 1)) - ; - } + private static string SpecialCasedHandlerName(IHandlerTypeDescriptor descriptor) => + new Regex(@"(\w+(?:\`\d)?)$") + .Replace( + descriptor.HandlerType.Name ?? string.Empty, + descriptor.HandlerType.Name.Substring(1, descriptor.HandlerType.Name.IndexOf("Handler", StringComparison.Ordinal) - 1) + ); private static Type GetExtensionClass(IHandlerTypeDescriptor descriptor) { var name = GetExtensionClassName(descriptor); return descriptor.HandlerType.Assembly.GetExportedTypes() - .FirstOrDefault(z => z.IsClass && z.IsAbstract && (z.Name == name || z.Name == name + "Base")); + .FirstOrDefault(z => z.IsClass && z.IsAbstract && ( z.Name == name || z.Name == name + "Base" )); } - private static string GetOnMethodName(IHandlerTypeDescriptor descriptor) - { - return "On" + SpecialCasedHandlerName(descriptor); - } + private static string GetOnMethodName(IHandlerTypeDescriptor descriptor) => "On" + SpecialCasedHandlerName(descriptor); private static string GetSendMethodName(ILspHandlerTypeDescriptor descriptor) { var name = SpecialCasedHandlerName(descriptor); if (name.StartsWith("Did") - || name.StartsWith("Log") - || name.StartsWith("Show") - || name.StartsWith("Register") - || name.StartsWith("Prepare") - || name.StartsWith("Publish") - || name.StartsWith("ApplyWorkspaceEdit") - || name.StartsWith("Execute") - || name.StartsWith("Unregister")) + || name.StartsWith("Log") + || name.StartsWith("Show") + || name.StartsWith("Register") + || name.StartsWith("Prepare") + || name.StartsWith("Publish") + || name.StartsWith("ApplyWorkspaceEdit") + || name.StartsWith("Execute") + || name.StartsWith("Unregister")) { return name; } diff --git a/test/Lsp.Tests/HandlerResolverTests.cs b/test/Lsp.Tests/HandlerResolverTests.cs index 270fdc3b3..a11e24f9c 100644 --- a/test/Lsp.Tests/HandlerResolverTests.cs +++ b/test/Lsp.Tests/HandlerResolverTests.cs @@ -1,18 +1,18 @@ using System; +using System.Collections.Generic; using System.Linq; using FluentAssertions; -using OmniSharp.Extensions.LanguageServer.Protocol; -using NSubstitute; -using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using Xunit; -using System.Collections.Generic; using MediatR; using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using OmniSharp.Extensions.JsonRpc; +using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.General; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; using OmniSharp.Extensions.LanguageServer.Shared; +using Xunit; namespace Lsp.Tests { @@ -26,7 +26,7 @@ public class HandlerResolverTests public void Should_Contain_AllDefinedMethods(Type requestHandler, string key, int count) { var handler = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()); - var sub = (IJsonRpcHandler)Substitute.For(new Type[] { requestHandler }, new object[0]); + var sub = (IJsonRpcHandler) Substitute.For(new[] { requestHandler }, new object[0]); handler.Add(sub); handler.Should().Contain(x => x.Method == key); @@ -58,7 +58,7 @@ public void Should_Contain_AllConcreteDefinedMethods() public void Should_Contain_AllDefinedTextDocumentSyncMethods(string key, int count) { var handler = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()); - var sub = (IJsonRpcHandler)TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.something"), "csharp"); + var sub = (IJsonRpcHandler) TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.something"), "csharp"); handler.Add(sub); handler.Should().Contain(x => x.Method == key); @@ -132,12 +132,14 @@ public void Should_Contain_AllDefinedMethods_ForDifferentKeys(string key, int co public void Should_Contain_AllDefinedMethods_OnLanguageServer(Type requestHandler, Type type2, string key, string key2, int count) { var handler = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()); - var sub = (IJsonRpcHandler)Substitute.For(new Type[] { requestHandler, type2 }, new object[0]); + var sub = (IJsonRpcHandler) Substitute.For(new[] { requestHandler, type2 }, new object[0]); if (sub is IRegistration reg) reg.GetRegistrationOptions() - .Returns(new TextDocumentRegistrationOptions() { - DocumentSelector = new DocumentSelector() - }); + .Returns( + new TextDocumentRegistrationOptions { + DocumentSelector = new DocumentSelector() + } + ); handler.Add(sub); handler.Should().Contain(x => x.Method == key); handler.Should().Contain(x => x.Method == key2); @@ -149,18 +151,22 @@ public void Should_Contain_AllDefinedMethods_OnLanguageServer(Type requestHandle public void Should_Contain_AllDefinedMethods_OnLanguageServer_WithDifferentKeys(Type requestHandler, Type type2, string key, string key2, int count) { var handler = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()); - var sub = (IJsonRpcHandler)Substitute.For(new Type[] { requestHandler, type2 }, new object[0]); + var sub = (IJsonRpcHandler) Substitute.For(new[] { requestHandler, type2 }, new object[0]); if (sub is IRegistration reg) reg.GetRegistrationOptions() - .Returns(new TextDocumentRegistrationOptions() { - DocumentSelector = new DocumentSelector() { } - }); - var sub2 = (IJsonRpcHandler)Substitute.For(new Type[] { requestHandler, type2 }, new object[0]); + .Returns( + new TextDocumentRegistrationOptions { + DocumentSelector = new DocumentSelector() + } + ); + var sub2 = (IJsonRpcHandler) Substitute.For(new[] { requestHandler, type2 }, new object[0]); if (sub2 is IRegistration reg2) reg2.GetRegistrationOptions() - .Returns(new TextDocumentRegistrationOptions() { - DocumentSelector = new DocumentSelector() - }); + .Returns( + new TextDocumentRegistrationOptions { + DocumentSelector = new DocumentSelector() + } + ); handler.Add(sub); handler.Add(sub2); handler.Should().Contain(x => x.Method == key); @@ -173,8 +179,8 @@ public void Should_Contain_AllDefinedMethods_OnLanguageServer_WithDifferentKeys( public void Should_AllowSpecificHandlers_ToBeAdded(string method, Type handlerType) { var handler = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()); - var sub = (IJsonRpcHandler)Substitute.For(new Type[] { handlerType }, new object[0]); - var sub2 = (IJsonRpcHandler)Substitute.For(new Type[] { handlerType }, new object[0]); + var sub = (IJsonRpcHandler) Substitute.For(new[] { handlerType }, new object[0]); + var sub2 = (IJsonRpcHandler) Substitute.For(new[] { handlerType }, new object[0]); handler.Add(method, sub, null); handler.Add(method, sub2, null); handler.Should().Contain(x => x.Method == method); @@ -196,44 +202,52 @@ public void Should_DealWithClassesThatImplementMultipleHandlers_WithoutConflicti [Fact] public void Should_DealWithClassesThatImplementMultipleHandlers_BySettingKeyAccordingly() { - var codeLensHandler = Substitute.For(new Type[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]); - ((ICodeLensHandler)codeLensHandler).GetRegistrationOptions() - .Returns(new CodeLensRegistrationOptions() { - DocumentSelector = new DocumentSelector(DocumentFilter.ForLanguage("foo")) - }); + var codeLensHandler = Substitute.For(new[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]); + ( (ICodeLensHandler) codeLensHandler ).GetRegistrationOptions() + .Returns( + new CodeLensRegistrationOptions { + DocumentSelector = new DocumentSelector(DocumentFilter.ForLanguage("foo")) + } + ); var handler = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()); handler.Add(codeLensHandler as IJsonRpcHandler); var descriptor = handler.OfType().Select(x => x.Key); - descriptor.Should().BeEquivalentTo(new [] { "[foo]", "[foo]" }); + descriptor.Should().BeEquivalentTo("[foo]", "[foo]"); } public static IEnumerable Should_DealWithClassesThatImplementMultipleHandlers_WithoutConflictingRegistrations_Data() { - var codeLensHandler = Substitute.For(new Type[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler), typeof(ICanBeIdentifiedHandler) }, new object[0]); - ((ICodeLensHandler)codeLensHandler).GetRegistrationOptions() - .Returns(new CodeLensRegistrationOptions() { - DocumentSelector = new DocumentSelector() { } - }); - - yield return new object[] { TextDocumentNames.CodeLensResolve, codeLensHandler }; - - var documentLinkHandler = Substitute.For(new Type[] { typeof(IDocumentLinkHandler), typeof(IDocumentLinkResolveHandler), typeof(ICanBeIdentifiedHandler) }, new object[0]); - ((IDocumentLinkHandler)documentLinkHandler).GetRegistrationOptions() - .Returns(new DocumentLinkRegistrationOptions() { - DocumentSelector = new DocumentSelector() { } - }); - - yield return new object[] { TextDocumentNames.DocumentLinkResolve, documentLinkHandler }; - - var completionHandler = Substitute.For(new Type[] { typeof(ICompletionHandler), typeof(ICompletionResolveHandler), typeof(ICanBeIdentifiedHandler) }, new object[0]); - ((ICompletionHandler)completionHandler).GetRegistrationOptions() - .Returns(new CompletionRegistrationOptions() { - DocumentSelector = new DocumentSelector() { } - }); - - yield return new object[] { TextDocumentNames.CompletionResolve, completionHandler }; + var codeLensHandler = Substitute.For(new[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler), typeof(ICanBeIdentifiedHandler) }, new object[0]); + ( (ICodeLensHandler) codeLensHandler ).GetRegistrationOptions() + .Returns( + new CodeLensRegistrationOptions { + DocumentSelector = new DocumentSelector() + } + ); + + yield return new[] { TextDocumentNames.CodeLensResolve, codeLensHandler }; + + var documentLinkHandler = Substitute.For(new[] { typeof(IDocumentLinkHandler), typeof(IDocumentLinkResolveHandler), typeof(ICanBeIdentifiedHandler) }, new object[0]); + ( (IDocumentLinkHandler) documentLinkHandler ).GetRegistrationOptions() + .Returns( + new DocumentLinkRegistrationOptions { + DocumentSelector = new DocumentSelector() + } + ); + + yield return new[] { TextDocumentNames.DocumentLinkResolve, documentLinkHandler }; + + var completionHandler = Substitute.For(new[] { typeof(ICompletionHandler), typeof(ICompletionResolveHandler), typeof(ICanBeIdentifiedHandler) }, new object[0]); + ( (ICompletionHandler) completionHandler ).GetRegistrationOptions() + .Returns( + new CompletionRegistrationOptions { + DocumentSelector = new DocumentSelector() + } + ); + + yield return new[] { TextDocumentNames.CompletionResolve, completionHandler }; } } } diff --git a/test/Lsp.Tests/Integration/ConnectionAndDisconnectionTests.cs b/test/Lsp.Tests/Integration/ConnectionAndDisconnectionTests.cs index 76e45fe60..3b280d925 100644 --- a/test/Lsp.Tests/Integration/ConnectionAndDisconnectionTests.cs +++ b/test/Lsp.Tests/Integration/ConnectionAndDisconnectionTests.cs @@ -1,8 +1,6 @@ using System; -using System.IO.Pipelines; using System.Threading.Tasks; using FluentAssertions; -using MediatR; using NSubstitute; using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.JsonRpc.Testing; @@ -16,9 +14,10 @@ namespace Lsp.Tests.Integration { public class ConnectionAndDisconnectionTests : LanguageProtocolTestBase { - public ConnectionAndDisconnectionTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions() - .ConfigureForXUnit(outputHelper) - .WithTestTimeout(TimeSpan.FromSeconds(20)) + public ConnectionAndDisconnectionTests(ITestOutputHelper outputHelper) : base( + new JsonRpcTestOptions() + .ConfigureForXUnit(outputHelper) + .WithTestTimeout(TimeSpan.FromSeconds(20)) ) { } @@ -85,24 +84,28 @@ public async Task Client_Should_Support_Links() private void ConfigureClient(LanguageClientOptions options) { - options.OnRequest("keepalive", (ct) => Task.FromResult(true)); + options.OnRequest("keepalive", ct => Task.FromResult(true)); options.WithLink("keepalive", "ka"); options.WithLink("throw", "t"); - options.OnRequest("throw", async ct => { - throw new NotSupportedException(); - return Task.CompletedTask; - }); + options.OnRequest( + "throw", async ct => { + throw new NotSupportedException(); + return Task.CompletedTask; + } + ); } private void ConfigureServer(LanguageServerOptions options) { - options.OnRequest("keepalive", (ct) => Task.FromResult(true)); + options.OnRequest("keepalive", ct => Task.FromResult(true)); options.WithLink("keepalive", "ka"); options.WithLink("throw", "t"); - options.OnRequest("throw", async ct => { - throw new NotSupportedException(); - return Task.CompletedTask; - }); + options.OnRequest( + "throw", async ct => { + throw new NotSupportedException(); + return Task.CompletedTask; + } + ); } } } diff --git a/test/Lsp.Tests/Integration/DynamicRegistrationTests.cs b/test/Lsp.Tests/Integration/DynamicRegistrationTests.cs index 2a08f5a97..8a1c3eede 100644 --- a/test/Lsp.Tests/Integration/DynamicRegistrationTests.cs +++ b/test/Lsp.Tests/Integration/DynamicRegistrationTests.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Reactive.Linq; -using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using FluentAssertions; using NSubstitute; @@ -24,10 +23,11 @@ namespace Lsp.Tests.Integration { public class DynamicRegistrationTests : LanguageProtocolTestBase { - public DynamicRegistrationTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions() - .ConfigureForXUnit(outputHelper) - .WithSettleTimeSpan(TimeSpan.FromSeconds(1)) - .WithSettleTimeout(TimeSpan.FromSeconds(2)) + public DynamicRegistrationTests(ITestOutputHelper outputHelper) : base( + new JsonRpcTestOptions() + .ConfigureForXUnit(outputHelper) + .WithSettleTimeSpan(TimeSpan.FromSeconds(1)) + .WithSettleTimeout(TimeSpan.FromSeconds(2)) ) { } @@ -41,8 +41,9 @@ public async Task Should_Register_Dynamically_After_Initialization() await SettleNext(); - client.RegistrationManager.CurrentRegistrations.Should().Contain(x => - x.Method == TextDocumentNames.Completion && SelectorMatches(x, z => z.HasLanguage && z.Language == "csharp") + client.RegistrationManager.CurrentRegistrations.Should().Contain( + x => + x.Method == TextDocumentNames.Completion && SelectorMatches(x, z => z.HasLanguage && z.Language == "csharp") ); } @@ -56,19 +57,22 @@ public async Task Should_Register_Dynamically_While_Server_Is_Running() await ServerEvents.Settle(); await ClientEvents.Settle(); - server.Register(x => x - .OnCompletion( - (@params, token) => Task.FromResult(new CompletionList()), - registrationOptions: new CompletionRegistrationOptions() { - DocumentSelector = DocumentSelector.ForLanguage("vb") - }) + server.Register( + x => x + .OnCompletion( + (@params, token) => Task.FromResult(new CompletionList()), + new CompletionRegistrationOptions { + DocumentSelector = DocumentSelector.ForLanguage("vb") + } + ) ); await ServerEvents.Settle(); await ClientEvents.Settle(); - client.RegistrationManager.CurrentRegistrations.Should().Contain(x => - x.Method == TextDocumentNames.Completion && SelectorMatches(x, z => z.HasLanguage && z.Language == "vb") + client.RegistrationManager.CurrentRegistrations.Should().Contain( + x => + x.Method == TextDocumentNames.Completion && SelectorMatches(x, z => z.HasLanguage && z.Language == "vb") ); } @@ -81,29 +85,34 @@ public async Task Should_Register_Links_Dynamically_While_Server_Is_Running() await SettleNext(); - server.Register(x => x - .OnCompletion( - (@params, token) => Task.FromResult(new CompletionList()), - registrationOptions: new CompletionRegistrationOptions() { - DocumentSelector = DocumentSelector.ForLanguage("vb") - }) + server.Register( + x => x + .OnCompletion( + (@params, token) => Task.FromResult(new CompletionList()), + new CompletionRegistrationOptions { + DocumentSelector = DocumentSelector.ForLanguage("vb") + } + ) ); await SettleNext(); - client.RegistrationManager.CurrentRegistrations.Should().Contain(x => - x.Method == TextDocumentNames.Completion && SelectorMatches(x, z => z.HasLanguage && z.Language == "vb") + client.RegistrationManager.CurrentRegistrations.Should().Contain( + x => + x.Method == TextDocumentNames.Completion && SelectorMatches(x, z => z.HasLanguage && z.Language == "vb") ); } [Fact] public async Task Should_Gather_Linked_Registrations() { - var (client, server) = await Initialize(ConfigureClient, + var (client, server) = await Initialize( + ConfigureClient, options => { ConfigureServer(options); options.WithLink(TextDocumentNames.SemanticTokensFull, "@/" + TextDocumentNames.SemanticTokensFull); - }); + } + ); await SettleNext(); @@ -122,33 +131,37 @@ public async Task Should_Unregister_Dynamically_While_Server_Is_Running() await Events.SettleNext(); - var disposable = server.Register(x => x.OnCompletion( - (@params, token) => Task.FromResult(new CompletionList()), - registrationOptions: new CompletionRegistrationOptions() { - DocumentSelector = DocumentSelector.ForLanguage("vb") - }) + var disposable = server.Register( + x => x.OnCompletion( + (@params, token) => Task.FromResult(new CompletionList()), + new CompletionRegistrationOptions { + DocumentSelector = DocumentSelector.ForLanguage("vb") + } + ) ); await SettleNext(); disposable.Dispose(); await SettleNext(); - client.RegistrationManager.CurrentRegistrations.Should().NotContain(x => - x.Method == TextDocumentNames.Completion && SelectorMatches(x, z => z.HasLanguage && z.Language == "vb") + client.RegistrationManager.CurrentRegistrations.Should().NotContain( + x => + x.Method == TextDocumentNames.Completion && SelectorMatches(x, z => z.HasLanguage && z.Language == "vb") ); } [Fact] public async Task Should_Gather_Static_Registrations() { - var (client, server) = await Initialize(ConfigureClient, + var (client, server) = await Initialize( + ConfigureClient, options => { ConfigureServer(options); - var semanticRegistrationOptions = new SemanticTokensRegistrationOptions() { + var semanticRegistrationOptions = new SemanticTokensRegistrationOptions { Id = Guid.NewGuid().ToString(), Legend = new SemanticTokensLegend(), - Full = new SemanticTokensCapabilityRequestFull() {Delta = true}, - Range = new SemanticTokensCapabilityRequestRange() { }, + Full = new SemanticTokensCapabilityRequestFull { Delta = true }, + Range = new SemanticTokensCapabilityRequestRange(), DocumentSelector = DocumentSelector.ForLanguage("csharp") }; @@ -156,119 +169,140 @@ public async Task Should_Gather_Static_Registrations() // This forces it to do that. options.OnInitialized( (server, request, response, token) => { - response.Capabilities.SemanticTokensProvider = SemanticTokensOptions.Of(semanticRegistrationOptions, - Enumerable.Empty()); + response.Capabilities.SemanticTokensProvider = SemanticTokensOptions.Of( + semanticRegistrationOptions, + Enumerable.Empty() + ); response.Capabilities.SemanticTokensProvider.Id = semanticRegistrationOptions.Id; return Task.CompletedTask; - }); - }); + } + ); + } + ); client.RegistrationManager.CurrentRegistrations.Should().Contain(x => x.Method == TextDocumentNames.SemanticTokensFull); } [Fact] public async Task Should_Register_Static_When_Dynamic_Is_Disabled() { - var (client, server) = await Initialize(options => { - ConfigureClient(options); - options.DisableDynamicRegistration(); - }, ConfigureServer); - - client.ServerSettings.Capabilities.CompletionProvider.Should().BeEquivalentTo(new CompletionOptions() { - 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 CompletionItemCapability() { - DeprecatedSupport = true, - DocumentationFormat = new[] {MarkupKind.Markdown}, - PreselectSupport = true, - SnippetSupport = true, - TagSupport = new CompletionItemTagSupportCapability() { - ValueSet = new[] { - CompletionItemTag.Deprecated - } + var (client, server) = await Initialize( + options => { + ConfigureClient(options); + options.DisableDynamicRegistration(); + }, ConfigureServer + ); + + client.ServerSettings.Capabilities.CompletionProvider.Should().BeEquivalentTo( + new CompletionOptions { + 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 CompletionItemCapability { + DeprecatedSupport = true, + DocumentationFormat = new[] { MarkupKind.Markdown }, + PreselectSupport = true, + SnippetSupport = true, + TagSupport = new CompletionItemTagSupportCapability { + ValueSet = new[] { + CompletionItemTag.Deprecated + } + }, + CommitCharactersSupport = true }, - CommitCharactersSupport = true - }, - ContextSupport = true, - CompletionItemKind = new CompletionItemKindCapability() { - ValueSet = new Container(Enum.GetValues(typeof(CompletionItemKind)) - .Cast()) - } - }, x => x.ConfigureForSupports().Excluding(z => z.DynamicRegistration)); - client.ClientSettings.Capabilities.TextDocument.Completion.Value.Should().BeEquivalentTo(new CompletionCapability() { - CompletionItem = new CompletionItemCapability() { - DeprecatedSupport = true, - DocumentationFormat = new[] {MarkupKind.Markdown}, - PreselectSupport = true, - SnippetSupport = true, - TagSupport = new CompletionItemTagSupportCapability() { - ValueSet = new[] { - CompletionItemTag.Deprecated - } + ContextSupport = true, + CompletionItemKind = new CompletionItemKindCapability { + ValueSet = new Container( + Enum.GetValues(typeof(CompletionItemKind)) + .Cast() + ) + } + }, x => x.ConfigureForSupports().Excluding(z => z.DynamicRegistration) + ); + client.ClientSettings.Capabilities.TextDocument.Completion.Value.Should().BeEquivalentTo( + new CompletionCapability { + CompletionItem = new CompletionItemCapability { + DeprecatedSupport = true, + DocumentationFormat = new[] { MarkupKind.Markdown }, + PreselectSupport = true, + SnippetSupport = true, + TagSupport = new CompletionItemTagSupportCapability { + ValueSet = new[] { + CompletionItemTag.Deprecated + } + }, + CommitCharactersSupport = true }, - CommitCharactersSupport = true - }, - ContextSupport = true, - CompletionItemKind = new CompletionItemKindCapability() { - ValueSet = new Container(Enum.GetValues(typeof(CompletionItemKind)) - .Cast()) - } - }, x => x.ConfigureForSupports().Excluding(z => z.DynamicRegistration)); + ContextSupport = true, + CompletionItemKind = new CompletionItemKindCapability { + ValueSet = new Container( + Enum.GetValues(typeof(CompletionItemKind)) + .Cast() + ) + } + }, x => x.ConfigureForSupports().Excluding(z => z.DynamicRegistration) + ); client.RegistrationManager.CurrentRegistrations.Should().NotContain(x => x.Method == TextDocumentNames.SemanticTokensFull); } private void ConfigureClient(LanguageClientOptions options) { - options.WithCapability(new CompletionCapability() { - CompletionItem = new CompletionItemCapability() { - DeprecatedSupport = true, - DocumentationFormat = new[] {MarkupKind.Markdown}, - PreselectSupport = true, - SnippetSupport = true, - TagSupport = new CompletionItemTagSupportCapability() { - ValueSet = new[] { - CompletionItemTag.Deprecated - } + options.WithCapability( + new CompletionCapability { + CompletionItem = new CompletionItemCapability { + DeprecatedSupport = true, + DocumentationFormat = new[] { MarkupKind.Markdown }, + PreselectSupport = true, + SnippetSupport = true, + TagSupport = new CompletionItemTagSupportCapability { + ValueSet = new[] { + CompletionItemTag.Deprecated + } + }, + CommitCharactersSupport = true }, - CommitCharactersSupport = true - }, - ContextSupport = true, - CompletionItemKind = new CompletionItemKindCapability() { - ValueSet = new Container(Enum.GetValues(typeof(CompletionItemKind)) - .Cast()) + ContextSupport = true, + CompletionItemKind = new CompletionItemKindCapability { + ValueSet = new Container( + Enum.GetValues(typeof(CompletionItemKind)) + .Cast() + ) + } } - }); + ); - options.WithCapability(new SemanticTokensCapability() { - TokenModifiers = SemanticTokenModifier.Defaults.ToArray(), - TokenTypes = SemanticTokenType.Defaults.ToArray() - }); + options.WithCapability( + new SemanticTokensCapability { + TokenModifiers = SemanticTokenModifier.Defaults.ToArray(), + TokenTypes = SemanticTokenType.Defaults.ToArray() + } + ); } private void ConfigureServer(LanguageServerOptions options) { options.OnCompletion( (@params, token) => Task.FromResult(new CompletionList()), - registrationOptions: new CompletionRegistrationOptions() { + new CompletionRegistrationOptions { DocumentSelector = DocumentSelector.ForLanguage("csharp"), ResolveProvider = false, TriggerCharacters = new Container("a", "b"), AllCommitCharacters = new Container("1", "2"), - }); + } + ); options.OnSemanticTokens( (builder, @params, ct) => { return Task.CompletedTask; }, (@params, token) => { return Task.FromResult(new SemanticTokensDocument(new SemanticTokensLegend())); }, - new SemanticTokensRegistrationOptions()); + new SemanticTokensRegistrationOptions() + ); } - private bool SelectorMatches(Registration registration, Func documentFilter) - { - return SelectorMatches(registration.RegisterOptions, documentFilter); - } + private bool SelectorMatches(Registration registration, Func documentFilter) => SelectorMatches(registration.RegisterOptions, documentFilter); private bool SelectorMatches(object options, Func documentFilter) { diff --git a/test/Lsp.Tests/Integration/EventingTests.cs b/test/Lsp.Tests/Integration/EventingTests.cs index 3fc55e05b..d05f0c3dc 100644 --- a/test/Lsp.Tests/Integration/EventingTests.cs +++ b/test/Lsp.Tests/Integration/EventingTests.cs @@ -56,13 +56,14 @@ public async Task Initialize_Delegate_Is_Supported() public async Task Initialize_Interface_Is_Supported_On_Handlers() { var onLanguageClientInitialize = - Substitute.For(new Type[] {typeof(IOnLanguageClientInitialize), typeof(PublishDiagnosticsHandler)}, Array.Empty()) as IOnLanguageClientInitialize; + Substitute.For(new[] { typeof(IOnLanguageClientInitialize), typeof(PublishDiagnosticsHandler) }, Array.Empty()) as IOnLanguageClientInitialize; var onLanguageServerInitialize = - Substitute.For(new Type[] {typeof(IOnLanguageServerInitialize), typeof(CompletionHandler)}, new object[] {new CompletionRegistrationOptions()}) as + Substitute.For(new[] { typeof(IOnLanguageServerInitialize), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }) as IOnLanguageServerInitialize; var (client, server) = await Initialize( options => options.AddHandler(onLanguageClientInitialize as IJsonRpcHandler), - options => options.AddHandler(onLanguageServerInitialize as IJsonRpcHandler)); + options => options.AddHandler(onLanguageServerInitialize as IJsonRpcHandler) + ); await onLanguageClientInitialize.Received(1).OnInitialize(client, client.ClientSettings, Arg.Any()); await onLanguageServerInitialize.Received(1).OnInitialize(server, server.ClientSettings, Arg.Any()); @@ -72,9 +73,9 @@ public async Task Initialize_Interface_Is_Supported_On_Handlers() public async Task Initialize_Interface_Is_Supported_On_Handlers_After_Startup() { var onLanguageClientInitialize = - Substitute.For(new Type[] {typeof(IOnLanguageClientInitialize), typeof(PublishDiagnosticsHandler)}, Array.Empty()) as IOnLanguageClientInitialize; + Substitute.For(new[] { typeof(IOnLanguageClientInitialize), typeof(PublishDiagnosticsHandler) }, Array.Empty()) as IOnLanguageClientInitialize; var onLanguageServerInitialize = - Substitute.For(new Type[] {typeof(IOnLanguageServerInitialize), typeof(CompletionHandler)}, new object[] {new CompletionRegistrationOptions()}) as + Substitute.For(new[] { typeof(IOnLanguageServerInitialize), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }) as IOnLanguageServerInitialize; var (client, server) = await Initialize(o => { }, o => { }); @@ -120,13 +121,14 @@ public async Task Initialized_Delegate_Is_Supported() public async Task Initialized_Interface_Is_Supported_On_Handlers() { var onLanguageClientInitialized = - Substitute.For(new Type[] {typeof(IOnLanguageClientInitialized), typeof(PublishDiagnosticsHandler)}, Array.Empty()) as IOnLanguageClientInitialized; + Substitute.For(new[] { typeof(IOnLanguageClientInitialized), typeof(PublishDiagnosticsHandler) }, Array.Empty()) as IOnLanguageClientInitialized; var onLanguageServerInitialized = - Substitute.For(new Type[] {typeof(IOnLanguageServerInitialized), typeof(CompletionHandler)}, new object[] {new CompletionRegistrationOptions()}) as + Substitute.For(new[] { typeof(IOnLanguageServerInitialized), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }) as IOnLanguageServerInitialized; var (client, server) = await Initialize( options => options.AddHandler(onLanguageClientInitialized as IJsonRpcHandler), - options => options.AddHandler(onLanguageServerInitialized as IJsonRpcHandler)); + options => options.AddHandler(onLanguageServerInitialized as IJsonRpcHandler) + ); await onLanguageClientInitialized.Received(1).OnInitialized(client, client.ClientSettings, client.ServerSettings, Arg.Any()); await onLanguageServerInitialized.Received(1).OnInitialized(server, server.ClientSettings, server.ServerSettings, Arg.Any()); @@ -136,9 +138,9 @@ public async Task Initialized_Interface_Is_Supported_On_Handlers() public async Task Initialized_Interface_Is_Supported_On_Handlers_After_Startup() { var onLanguageClientInitialized = - Substitute.For(new Type[] {typeof(IOnLanguageClientInitialized), typeof(PublishDiagnosticsHandler)}, Array.Empty()) as IOnLanguageClientInitialized; + Substitute.For(new[] { typeof(IOnLanguageClientInitialized), typeof(PublishDiagnosticsHandler) }, Array.Empty()) as IOnLanguageClientInitialized; var onLanguageServerInitialized = - Substitute.For(new Type[] {typeof(IOnLanguageServerInitialized), typeof(CompletionHandler)}, new object[] {new CompletionRegistrationOptions()}) as + Substitute.For(new[] { typeof(IOnLanguageServerInitialized), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }) as IOnLanguageServerInitialized; var (client, server) = await Initialize(o => { }, o => { }); @@ -184,13 +186,14 @@ public async Task Started_Delegate_Is_Supported() public async Task Started_Interface_Is_Supported_On_Handlers() { var onLanguageClientStarted = - Substitute.For(new Type[] {typeof(IOnLanguageClientStarted), typeof(PublishDiagnosticsHandler)}, Array.Empty()) as IOnLanguageClientStarted; + Substitute.For(new[] { typeof(IOnLanguageClientStarted), typeof(PublishDiagnosticsHandler) }, Array.Empty()) as IOnLanguageClientStarted; var onLanguageServerStarted = - Substitute.For(new Type[] {typeof(IOnLanguageServerStarted), typeof(CompletionHandler)}, new object[] {new CompletionRegistrationOptions()}) as + Substitute.For(new[] { typeof(IOnLanguageServerStarted), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }) as IOnLanguageServerStarted; var (client, server) = await Initialize( options => options.AddHandler(onLanguageClientStarted as IJsonRpcHandler), - options => options.AddHandler(onLanguageServerStarted as IJsonRpcHandler)); + options => options.AddHandler(onLanguageServerStarted as IJsonRpcHandler) + ); await onLanguageClientStarted.Received(1).OnStarted(client, Arg.Any()); await onLanguageServerStarted.Received(1).OnStarted(server, Arg.Any()); @@ -200,9 +203,9 @@ public async Task Started_Interface_Is_Supported_On_Handlers() public async Task Started_Interface_Is_Supported_On_Handlers_After_Startup() { var onLanguageClientStarted = - Substitute.For(new Type[] {typeof(IOnLanguageClientStarted), typeof(PublishDiagnosticsHandler)}, Array.Empty()) as IOnLanguageClientStarted; + Substitute.For(new[] { typeof(IOnLanguageClientStarted), typeof(PublishDiagnosticsHandler) }, Array.Empty()) as IOnLanguageClientStarted; var onLanguageServerStarted = - Substitute.For(new Type[] {typeof(IOnLanguageServerStarted), typeof(CompletionHandler)}, new object[] {new CompletionRegistrationOptions()}) as + Substitute.For(new[] { typeof(IOnLanguageServerStarted), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }) as IOnLanguageServerStarted; var (client, server) = await Initialize(o => { }, o => { }); diff --git a/test/Lsp.Tests/Integration/ExecuteCommandTests.cs b/test/Lsp.Tests/Integration/ExecuteCommandTests.cs index 5898debda..e682f8a54 100644 --- a/test/Lsp.Tests/Integration/ExecuteCommandTests.cs +++ b/test/Lsp.Tests/Integration/ExecuteCommandTests.cs @@ -33,17 +33,25 @@ public async Task Should_Execute_A_Command() var command = Substitute.For>(); var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a", 1, "2", false) - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand(command, new ExecuteCommandRegistrationOptions() { - Commands = new Container("execute-a") - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a", 1, "2", false) + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + command, new ExecuteCommandRegistrationOptions { + Commands = new Container("execute-a") + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -63,25 +71,37 @@ public async Task Should_Execute_The_Correct_Command() var commandb = Substitute.For>(); var (client, server) = await Initialize( options => { - options.WithCapability(new ExecuteCommandCapability() { - DynamicRegistration = false - }); + options.WithCapability( + new ExecuteCommandCapability { + DynamicRegistration = false + } + ); }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-b", 1, "2", false ) - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand(commanda, new ExecuteCommandRegistrationOptions() { - Commands = new Container("execute-a") - }); - - options.OnExecuteCommand(commandb, new ExecuteCommandRegistrationOptions() { - Commands = new Container("execute-b") - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-b", 1, "2", false) + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + commanda, new ExecuteCommandRegistrationOptions { + Commands = new Container("execute-a") + } + ); + + options.OnExecuteCommand( + commandb, new ExecuteCommandRegistrationOptions { + Commands = new Container("execute-b") + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -102,13 +122,19 @@ public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Is_Defined() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a", 1, "2", false ) - })); - }, new CompletionRegistrationOptions() { - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a", 1, "2", false) + } + ) + ); + }, new CompletionRegistrationOptions() + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -126,19 +152,27 @@ public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Name_Is_Given var command = Substitute.For>(); var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = new Command() { - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - } - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand(command, new ExecuteCommandRegistrationOptions() { - Commands = new Container("execute-a") - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = new Command { + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + } + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + command, new ExecuteCommandRegistrationOptions { + Commands = new Container("execute-a") + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -159,21 +193,31 @@ public async Task Should_Fail_To_Execute_A_Command() var commandb = Substitute.For>(); var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a",1, "2", false ) - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand(commandb, new ExecuteCommandRegistrationOptions() { - Commands = new Container("execute-b") - }); - - options.OnExecuteCommand(commandc, new ExecuteCommandRegistrationOptions() { - Commands = new Container("execute-c") - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a", 1, "2", false) + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + commandb, new ExecuteCommandRegistrationOptions { + Commands = new Container("execute-b") + } + ); + + options.OnExecuteCommand( + commandc, new ExecuteCommandRegistrationOptions { + Commands = new Container("execute-c") + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -193,19 +237,27 @@ public async Task Should_Execute_1_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a", 1 ) - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand("execute-a", (i) => { - i.Should().Be(1); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a", 1) + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + "execute-a", i => { + i.Should().Be(1); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -222,20 +274,28 @@ public async Task Should_Execute_2_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a", 1, "2" ) - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand("execute-a", (i, s) => { - i.Should().Be(1); - s.Should().Be("2"); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a", 1, "2") + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + "execute-a", (i, s) => { + i.Should().Be(1); + s.Should().Be("2"); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -252,21 +312,29 @@ public async Task Should_Execute_3_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a", 1, "2", true ) - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand("execute-a", (i, s, arg3) => { - i.Should().Be(1); - s.Should().Be("2"); - arg3.Should().BeTrue(); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a", 1, "2", true) + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + "execute-a", (i, s, arg3) => { + i.Should().Be(1); + s.Should().Be("2"); + arg3.Should().BeTrue(); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -283,22 +351,30 @@ public async Task Should_Execute_4_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a", 1, "2", true, new Range((0, 1), (1, 1)) ) - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand("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))); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a", 1, "2", true, new Range(( 0, 1 ), ( 1, 1 ))) + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + "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 ))); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -315,23 +391,33 @@ public async Task Should_Execute_5_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a", 1, "2", true, new Range((0, 1), (1, 1)), new Dictionary() { ["a"] = "123", ["b"] = "456" } ) - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand>("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))); - arg5.Should().ContainKeys("a", "b"); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create( + "execute-a", 1, "2", true, new Range(( 0, 1 ), ( 1, 1 )), new Dictionary { ["a"] = "123", ["b"] = "456" } + ) + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand>( + "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 ))); + arg5.Should().ContainKeys("a", "b"); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -348,24 +434,35 @@ public async Task Should_Execute_6_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a",1, "2", true, new Range((0, 1), (1, 1)), new Dictionary() { ["a"] = "123", ["b"] = "456" }, Guid.NewGuid() ) - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand, Guid>("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))); - arg5.Should().ContainKeys("a", "b"); - arg6.Should().NotBeEmpty(); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create( + "execute-a", 1, "2", true, new Range(( 0, 1 ), ( 1, 1 )), new Dictionary { ["a"] = "123", ["b"] = "456" }, + Guid.NewGuid() + ) + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand, Guid>( + "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 ))); + arg5.Should().ContainKeys("a", "b"); + arg6.Should().NotBeEmpty(); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -382,19 +479,27 @@ public async Task Should_Execute_1_With_Missing_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a") - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand("execute-a", (i) => { - i.Should().Be(default); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a") + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + "execute-a", i => { + i.Should().Be(default); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -411,20 +516,28 @@ public async Task Should_Execute_2_With_Missing_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a") - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand("execute-a", (i, s) => { - i.Should().Be(default); - s.Should().Be(default); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a") + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + "execute-a", (i, s) => { + i.Should().Be(default); + s.Should().Be(default); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -441,21 +554,29 @@ public async Task Should_Execute_3_With_Missing_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a") - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand("execute-a", (i, s, arg3) => { - i.Should().Be(default); - s.Should().Be(default); - arg3.Should().Be(default); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a") + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + "execute-a", (i, s, arg3) => { + i.Should().Be(default); + s.Should().Be(default); + arg3.Should().Be(default); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -472,22 +593,30 @@ public async Task Should_Execute_4_With_Missing_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a") - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand("execute-a", (i, s, arg3, arg4) => { - i.Should().Be(default); - s.Should().Be(default); - arg3.Should().Be(default); - arg4.Should().Be(default); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a") + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + "execute-a", (i, s, arg3, arg4) => { + i.Should().Be(default); + s.Should().Be(default); + arg3.Should().Be(default); + arg4.Should().Be(default); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -504,23 +633,31 @@ public async Task Should_Execute_5_With_Missing_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a") - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand>("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.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a") + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand>( + "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.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -537,24 +674,32 @@ public async Task Should_Execute_6_With_Missing_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a") - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand, Guid>("execute-a", (i, s, arg3, arg4, arg5, arg6) => { - i.Should().Be(default); - s.Should().Be(default); - arg3.Should().Be(default); - arg4.Should().Be(default); - arg5.Should().BeNull(); - arg6.Should().BeEmpty(); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a") + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand, Guid>( + "execute-a", (i, s, arg3, arg4, arg5, arg6) => { + i.Should().Be(default); + s.Should().Be(default); + arg3.Should().Be(default); + arg4.Should().Be(default); + arg5.Should().BeNull(); + arg6.Should().BeEmpty(); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -571,19 +716,27 @@ public async Task Should_Execute_1_Null_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a") - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand("execute-a", (i) => { - i.Should().Be(default); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a") + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + "execute-a", i => { + i.Should().Be(default); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -600,20 +753,28 @@ public async Task Should_Execute_2_Null_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a") - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand("execute-a", (i, s) => { - i.Should().Be(default); - s.Should().Be(default); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a") + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + "execute-a", (i, s) => { + i.Should().Be(default); + s.Should().Be(default); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -630,21 +791,29 @@ public async Task Should_Execute_3_Null_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a") - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand("execute-a", (i, s, arg3) => { - i.Should().Be(default); - s.Should().Be(default); - arg3.Should().Be(default); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a") + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + "execute-a", (i, s, arg3) => { + i.Should().Be(default); + s.Should().Be(default); + arg3.Should().Be(default); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -661,22 +830,30 @@ public async Task Should_Execute_4_Null_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a") - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand("execute-a", (i, s, arg3, arg4) => { - i.Should().Be(default); - s.Should().Be(default); - arg3.Should().Be(default); - arg4.Should().Be(default); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a") + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand( + "execute-a", (i, s, arg3, arg4) => { + i.Should().Be(default); + s.Should().Be(default); + arg3.Should().Be(default); + arg4.Should().Be(default); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -693,23 +870,31 @@ public async Task Should_Execute_5_Null_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a") - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand>("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.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a") + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand>( + "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.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -726,24 +911,32 @@ public async Task Should_Execute_6_Null_Args() { var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion(x => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = Command.Create("execute-a") - })); - }, new CompletionRegistrationOptions() { - }); - - options.OnExecuteCommand, Guid>("execute-a", (i, s, arg3, arg4, arg5, arg6) => { - i.Should().Be(default); - s.Should().Be(default); - arg3.Should().Be(default); - arg4.Should().Be(default); - arg5.Should().BeNull(); - arg6.Should().BeEmpty(); - - return Task.CompletedTask; - }); - }); + options.OnCompletion( + x => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = Command.Create("execute-a") + } + ) + ); + }, new CompletionRegistrationOptions() + ); + + options.OnExecuteCommand, Guid>( + "execute-a", (i, s, arg3, arg4, arg5, arg6) => { + i.Should().Be(default); + s.Should().Be(default); + arg3.Should().Be(default); + arg4.Should().Be(default); + arg5.Should().BeNull(); + arg6.Should().BeEmpty(); + + return Task.CompletedTask; + } + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); diff --git a/test/Lsp.Tests/Integration/InitializationTests.cs b/test/Lsp.Tests/Integration/InitializationTests.cs index a4f24ea3d..eba3bcf95 100644 --- a/test/Lsp.Tests/Integration/InitializationTests.cs +++ b/test/Lsp.Tests/Integration/InitializationTests.cs @@ -14,7 +14,9 @@ namespace Lsp.Tests.Integration { public class InitializationTests : LanguageProtocolTestBase { - public InitializationTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper)) { } + public InitializationTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper)) + { + } [Fact] public async Task Logs_should_be_allowed_during_startup() @@ -25,25 +27,25 @@ public async Task Logs_should_be_allowed_during_startup() _logs.Should().ContainInOrder("OnInitialize", "OnInitialized"); } - private List _logs = new List(); + private readonly List _logs = new List(); - private void ConfigureClient(LanguageClientOptions options) - { - options.OnLogMessage(log => { - _logs.Add(log.Message); - }); - } + private void ConfigureClient(LanguageClientOptions options) => + options.OnLogMessage(log => { _logs.Add(log.Message); }); private void ConfigureServer(LanguageServerOptions options) { - options.OnInitialize((server, request, token) => { - server.Window.LogInfo("OnInitialize"); - return Task.CompletedTask; - }); - options.OnInitialized((server, request, response, token) => { - server.Window.LogInfo("OnInitialized"); - return Task.CompletedTask; - }); + options.OnInitialize( + (server, request, token) => { + server.Window.LogInfo("OnInitialize"); + return Task.CompletedTask; + } + ); + options.OnInitialized( + (server, request, response, token) => { + server.Window.LogInfo("OnInitialized"); + return Task.CompletedTask; + } + ); } } -} \ No newline at end of file +} diff --git a/test/Lsp.Tests/Integration/LanguageServerConfigurationTests.cs b/test/Lsp.Tests/Integration/LanguageServerConfigurationTests.cs index 2d5e9c58b..1a99ab3ee 100644 --- a/test/Lsp.Tests/Integration/LanguageServerConfigurationTests.cs +++ b/test/Lsp.Tests/Integration/LanguageServerConfigurationTests.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using System.Reactive.Linq; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Extensions.Configuration; @@ -24,10 +23,10 @@ public LanguageServerConfigurationTests(ITestOutputHelper outputHelper) : base(n [Fact] public async Task Should_Not_Support_Configuration_It_Not_Configured() { - var (client, server, configuration) = await InitializeWithConfiguration(ConfigureClient, o => {}); + var (client, server, configuration) = await InitializeWithConfiguration(ConfigureClient, o => { }); server.Configuration.AsEnumerable().Should().BeEmpty(); - configuration.Update("mysection", new Dictionary() {["key"] = "value"}); + configuration.Update("mysection", new Dictionary { ["key"] = "value" }); await server.Configuration.WaitForChange(CancellationToken); server.Configuration.AsEnumerable().Should().BeEmpty(); @@ -39,7 +38,7 @@ public async Task Should_Update_Configuration_On_Server() var (client, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); server.Configuration.AsEnumerable().Should().BeEmpty(); - configuration.Update("mysection", new Dictionary() {["key"] = "value"}); + configuration.Update("mysection", new Dictionary { ["key"] = "value" }); await server.Configuration.WaitForChange(CancellationToken); server.Configuration["mysection:key"].Should().Be("value"); @@ -51,9 +50,9 @@ public async Task Should_Update_Scoped_Configuration() var (client, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); var scopedConfiguration = await server.Configuration.GetScopedConfiguration(DocumentUri.From("/my/file.cs")); - configuration.Update("mysection", new Dictionary() {["key"] = "value"}); + configuration.Update("mysection", new Dictionary { ["key"] = "value" }); await server.Configuration.WaitForChange(CancellationToken); - configuration.Update("mysection", DocumentUri.From("/my/file.cs"), new Dictionary() {["key"] = "scopedvalue"}); + configuration.Update("mysection", DocumentUri.From("/my/file.cs"), new Dictionary { ["key"] = "scopedvalue" }); await server.Configuration.WaitForChange(CancellationToken); server.Configuration["mysection:key"].Should().Be("value"); @@ -66,15 +65,15 @@ public async Task Should_Fallback_To_Original_Configuration() var (client, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); var scopedConfiguration = await server.Configuration.GetScopedConfiguration(DocumentUri.From("/my/file.cs")); - configuration.Update("mysection", new Dictionary() {["key"] = "value"}); + configuration.Update("mysection", new Dictionary { ["key"] = "value" }); await server.Configuration.WaitForChange(CancellationToken); - configuration.Update("mysection", DocumentUri.From("/my/file.cs"), new Dictionary() {["key"] = "scopedvalue"}); + configuration.Update("mysection", DocumentUri.From("/my/file.cs"), new Dictionary { ["key"] = "scopedvalue" }); await server.Configuration.WaitForChange(CancellationToken); server.Configuration["mysection:key"].Should().Be("value"); scopedConfiguration["mysection:key"].Should().Be("scopedvalue"); - configuration.Update("mysection", DocumentUri.From("/my/file.cs"), new Dictionary() {}); + configuration.Update("mysection", DocumentUri.From("/my/file.cs"), new Dictionary()); await scopedConfiguration.WaitForChange(CancellationToken); await Task.Delay(1000); @@ -88,9 +87,9 @@ public async Task Should_Only_Update_Configuration_Items_That_Are_Defined() var (client, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); server.Configuration.AsEnumerable().Should().BeEmpty(); - configuration.Update("mysection", new Dictionary() {["key"] = "value"}); + configuration.Update("mysection", new Dictionary { ["key"] = "value" }); await server.Configuration.WaitForChange(CancellationToken); - configuration.Update("notmysection", new Dictionary() {["key"] = "value"}); + configuration.Update("notmysection", new Dictionary { ["key"] = "value" }); await server.Configuration.WaitForChange(CancellationToken); server.Configuration["mysection:key"].Should().Be("value"); @@ -101,9 +100,6 @@ private void ConfigureClient(LanguageClientOptions options) { } - private void ConfigureServer(LanguageServerOptions options) - { - options.WithConfigurationSection("mysection"); - } + private void ConfigureServer(LanguageServerOptions options) => options.WithConfigurationSection("mysection"); } } diff --git a/test/Lsp.Tests/Integration/LogMessageTests.cs b/test/Lsp.Tests/Integration/LogMessageTests.cs index 17c204b72..3a07b54d5 100644 --- a/test/Lsp.Tests/Integration/LogMessageTests.cs +++ b/test/Lsp.Tests/Integration/LogMessageTests.cs @@ -1,7 +1,5 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Reactive.Linq; using System.Threading.Tasks; using FluentAssertions; using NSubstitute; @@ -33,12 +31,16 @@ public async Task Should_Log_Messages_Through_Window_Extension_Methods() server.Window.LogInfo("Here's something cool..."); server.Window.LogWarning("Uh-oh..."); server.Window.Log("Just gotta let you know!"); - server.Window.Log(new LogMessageParams() { - Type = MessageType.Log, Message = "1234" - }); - server.Window.LogMessage(new LogMessageParams() { - Type = MessageType.Log, Message = "1234" - }); + server.Window.Log( + new LogMessageParams { + Type = MessageType.Log, Message = "1234" + } + ); + server.Window.LogMessage( + new LogMessageParams { + Type = MessageType.Log, Message = "1234" + } + ); await Task.Delay(1000); @@ -58,12 +60,16 @@ public async Task Should_Log_Messages_Through_Server_Extension_Methods() server.LogInfo("Here's something cool..."); server.LogWarning("Uh-oh..."); server.Log("Just gotta let you know!"); - server.Log(new LogMessageParams() { - Type = MessageType.Log, Message = "1234" - }); - server.LogMessage(new LogMessageParams() { - Type = MessageType.Log, Message = "1234" - }); + server.Log( + new LogMessageParams { + Type = MessageType.Log, Message = "1234" + } + ); + server.LogMessage( + new LogMessageParams { + Type = MessageType.Log, Message = "1234" + } + ); await Task.Delay(1000); @@ -74,10 +80,7 @@ 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.Tests/Integration/PartialItemTests.cs b/test/Lsp.Tests/Integration/PartialItemTests.cs index f58d08b7d..d97f70c0a 100644 --- a/test/Lsp.Tests/Integration/PartialItemTests.cs +++ b/test/Lsp.Tests/Integration/PartialItemTests.cs @@ -31,9 +31,11 @@ public PartialItemTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOp public async Task Should_Behave_Like_A_Task() { var (client, server) = await Initialize(ConfigureClient, ConfigureServerWithDelegateCodeLens); - var result = await client.TextDocument.RequestCodeLens(new CodeLensParams() { - TextDocument = new TextDocumentIdentifier(@"c:\test.cs") - }, CancellationToken); + var result = await client.TextDocument.RequestCodeLens( + new CodeLensParams { + TextDocument = new TextDocumentIdentifier(@"c:\test.cs") + }, CancellationToken + ); result.Should().HaveCount(3); result.Select(z => z.Command.Name).Should().ContainInOrder("CodeLens 1", "CodeLens 2", "CodeLens 3"); @@ -45,9 +47,11 @@ public async Task Should_Behave_Like_An_Observable() var (client, server) = await Initialize(ConfigureClient, ConfigureServerWithDelegateCodeLens); var items = new List(); - await client.TextDocument.RequestCodeLens(new CodeLensParams() { - TextDocument = new TextDocumentIdentifier(@"c:\test.cs") - }, CancellationToken).ForEachAsync(x => items.AddRange(x)); + await client.TextDocument.RequestCodeLens( + new CodeLensParams { + TextDocument = new TextDocumentIdentifier(@"c:\test.cs") + }, CancellationToken + ).ForEachAsync(x => items.AddRange(x)); items.Should().HaveCount(3); items.Select(z => z.Command.Name).Should().ContainInOrder("CodeLens 1", "CodeLens 2", "CodeLens 3"); @@ -58,9 +62,11 @@ public async Task Should_Behave_Like_An_Observable_Without_Progress_Support() { var (client, server) = await Initialize(ConfigureClient, ConfigureServerWithDelegateCodeLens); - var response = await client.SendRequest(new CodeLensParams() { - TextDocument = new TextDocumentIdentifier(@"c:\test.cs") - }, CancellationToken); + var response = await client.SendRequest( + new CodeLensParams { + TextDocument = new TextDocumentIdentifier(@"c:\test.cs") + }, CancellationToken + ); response.Should().HaveCount(3); response.Select(z => z.Command.Name).Should().ContainInOrder("CodeLens 1", "CodeLens 2", "CodeLens 3"); @@ -74,11 +80,11 @@ public async Task Should_Behave_Like_An_Observable_With_WorkDone() var items = new List(); var work = new List(); client.TextDocument - .ObserveWorkDone( - new CodeLensParams() {TextDocument = new TextDocumentIdentifier(@"c:\test.cs")}, - (client, request) => CodeLensExtensions.RequestCodeLens(client, request, CancellationToken), - Observer.Create(z => work.Add(z)) - ).Subscribe(x => items.AddRange(x)); + .ObserveWorkDone( + new CodeLensParams { TextDocument = new TextDocumentIdentifier(@"c:\test.cs") }, + (client, request) => client.RequestCodeLens(request, CancellationToken), + Observer.Create(z => work.Add(z)) + ).Subscribe(x => items.AddRange(x)); await Task.Delay(1000); @@ -92,45 +98,45 @@ public async Task Should_Behave_Like_An_Observable_With_WorkDone() private void ConfigureClient(LanguageClientOptions options) { - } - private void ConfigureServerWithDelegateCodeLens(LanguageServerOptions options) - { - options.OnCodeLens((@params, observer, capability, cancellationToken) => { - observer.OnNext(new [] { - new CodeLens() { - Command = new Command() { - Name = "CodeLens 1" + private void ConfigureServerWithDelegateCodeLens(LanguageServerOptions options) => + options.OnCodeLens( + (@params, observer, capability, cancellationToken) => { + observer.OnNext( + new[] { + new CodeLens { + Command = new Command { + Name = "CodeLens 1" + } + }, } - }, - }); - observer.OnNext(new [] { - new CodeLens() { - Command = new Command() { - Name = "CodeLens 2" + ); + observer.OnNext( + new[] { + new CodeLens { + Command = new Command { + Name = "CodeLens 2" + } + }, } - }, - }); - observer.OnNext(new [] { - new CodeLens() { - Command = new Command() { - Name = "CodeLens 3" + ); + observer.OnNext( + new[] { + new CodeLens { + Command = new Command { + Name = "CodeLens 3" + } + }, } - }, - }); - observer.OnCompleted(); - }, new CodeLensRegistrationOptions() { - // DocumentSelector = DocumentSelector.ForPattern("**/*.cs") - }); - } + ); + observer.OnCompleted(); + }, new CodeLensRegistrationOptions() + ); - private void ConfigureServerWithClassCodeLens(LanguageServerOptions options) - { - options.AddHandler(); - } + private void ConfigureServerWithClassCodeLens(LanguageServerOptions options) => options.AddHandler(); - class InnerCodeLensHandler : CodeLensHandler + private class InnerCodeLensHandler : CodeLensHandler { private readonly IServerWorkDoneManager _workDoneManager; private readonly IProgressManager _progressManager; @@ -144,63 +150,80 @@ public InnerCodeLensHandler(IServerWorkDoneManager workDoneManager, IProgressMan public override async Task Handle(CodeLensParams request, CancellationToken cancellationToken) { var partial = _progressManager.For(request, cancellationToken); - var workDone = _workDoneManager.For(request, new WorkDoneProgressBegin() { - - Cancellable = true, - Message = "Begin", - Percentage = 0, - Title = "Work is pending" - }, onComplete: () => new WorkDoneProgressEnd() { - Message = "End" - }); - - partial.OnNext(new [] { - new CodeLens() { - Command = new Command() { - Name = "CodeLens 1" - } - }, - }); - workDone.OnNext(new WorkDoneProgressReport() { - Percentage = 10, - Message = "Report 1" - }); - - partial.OnNext(new [] { - new CodeLens() { - Command = new Command() { - Name = "CodeLens 2" - } - }, - }); - workDone.OnNext(new WorkDoneProgressReport() { - Percentage = 20, - Message = "Report 2" - }); - - partial.OnNext(new [] { - new CodeLens() { - Command = new Command() { - Name = "CodeLens 3" - } - }, - }); - workDone.OnNext(new WorkDoneProgressReport() { - Percentage = 30, - Message = "Report 3" - }); - - partial.OnNext(new [] { - new CodeLens() { - Command = new Command() { - Name = "CodeLens 4" - } - }, - }); - workDone.OnNext(new WorkDoneProgressReport() { - Percentage = 40, - Message = "Report 4" - }); + var workDone = _workDoneManager.For( + request, new WorkDoneProgressBegin { + Cancellable = true, + Message = "Begin", + Percentage = 0, + Title = "Work is pending" + }, onComplete: () => new WorkDoneProgressEnd { + Message = "End" + } + ); + + partial.OnNext( + new[] { + new CodeLens { + Command = new Command { + Name = "CodeLens 1" + } + }, + } + ); + workDone.OnNext( + new WorkDoneProgressReport { + Percentage = 10, + Message = "Report 1" + } + ); + + partial.OnNext( + new[] { + new CodeLens { + Command = new Command { + Name = "CodeLens 2" + } + }, + } + ); + workDone.OnNext( + new WorkDoneProgressReport { + Percentage = 20, + Message = "Report 2" + } + ); + + partial.OnNext( + new[] { + new CodeLens { + Command = new Command { + Name = "CodeLens 3" + } + }, + } + ); + workDone.OnNext( + new WorkDoneProgressReport { + Percentage = 30, + Message = "Report 3" + } + ); + + partial.OnNext( + new[] { + new CodeLens { + Command = new Command { + Name = "CodeLens 4" + } + }, + } + ); + workDone.OnNext( + new WorkDoneProgressReport { + Percentage = 40, + Message = "Report 4" + } + ); workDone.OnCompleted(); @@ -211,6 +234,5 @@ public override async Task Handle(CodeLensParams request, Can public override Task Handle(CodeLens request, CancellationToken cancellationToken) => Task.FromResult(request); } - } } diff --git a/test/Lsp.Tests/Integration/ProgressTests.cs b/test/Lsp.Tests/Integration/ProgressTests.cs index c35955b2d..de76c19a6 100644 --- a/test/Lsp.Tests/Integration/ProgressTests.cs +++ b/test/Lsp.Tests/Integration/ProgressTests.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Reactive.Linq; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; @@ -10,10 +9,10 @@ using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Models; +using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Server; using Xunit; using Xunit.Abstractions; -using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; namespace Lsp.Tests.Integration { @@ -23,7 +22,7 @@ public ProgressTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptio { } - class Data + private class Data { public string Value { get; set; } = "Value"; } @@ -39,26 +38,36 @@ public async Task Should_Send_Progress_From_Server_To_Client() var observer = client.ProgressManager.For(token, CancellationToken); server.ProgressManager.Monitor(token, x => x.ToObject(server.Services.GetRequiredService().JsonSerializer)).Subscribe(x => data.Add(x.Value)); - observer.OnNext(new Data() { - Value = "1" - }); - observer.OnNext(new Data() { - Value = "3" - }); - observer.OnNext(new Data() { - Value = "2" - }); - observer.OnNext(new Data() { - Value = "4" - }); - observer.OnNext(new Data() { - Value = "5" - }); + observer.OnNext( + new Data { + Value = "1" + } + ); + observer.OnNext( + new Data { + Value = "3" + } + ); + observer.OnNext( + new Data { + Value = "2" + } + ); + observer.OnNext( + new Data { + Value = "4" + } + ); + observer.OnNext( + new Data { + Value = "5" + } + ); await Task.Delay(1000); observer.OnCompleted(); - data.Should().ContainInOrder(new [] { "1", "3", "2", "4", "5" }); + data.Should().ContainInOrder("1", "3", "2", "4", "5"); } [Fact(Skip = "Test fails periodically on CI but not locally")] @@ -72,21 +81,31 @@ public async Task Should_Send_Progress_From_Client_To_Server() using var observer = server.ProgressManager.For(token, CancellationToken); client.ProgressManager.Monitor(token, x => x.ToObject(client.Services.GetRequiredService().JsonSerializer)).Subscribe(x => data.Add(x.Value)); - observer.OnNext(new Data() { - Value = "1" - }); - observer.OnNext(new Data() { - Value = "3" - }); - observer.OnNext(new Data() { - Value = "2" - }); - observer.OnNext(new Data() { - Value = "4" - }); - observer.OnNext(new Data() { - Value = "5" - }); + observer.OnNext( + new Data { + Value = "1" + } + ); + observer.OnNext( + new Data { + Value = "3" + } + ); + observer.OnNext( + new Data { + Value = "2" + } + ); + observer.OnNext( + new Data { + Value = "4" + } + ); + observer.OnNext( + new Data { + Value = "5" + } + ); await Task.Delay(1000); observer.OnCompleted(); @@ -112,44 +131,56 @@ public async Task Should_Support_Creating_Work_Done_From_Sever_To_Client() using var workDoneObservable = client.WorkDoneManager.Monitor(token); workDoneObservable.Subscribe(x => data.Add(x)); - using var workDoneObserver = await server.WorkDoneManager.Create(token, new WorkDoneProgressBegin() { - Cancellable = true, - Message = "Begin", - Percentage = 0, - Title = "Work is pending" - }, onComplete: () => new WorkDoneProgressEnd() { - Message = "End" - }); - - workDoneObserver.OnNext(new WorkDoneProgressReport() { - Percentage = 10, - Message = "Report 1" - }); - - workDoneObserver.OnNext(new WorkDoneProgressReport() { - Percentage = 20, - Message = "Report 2" - }); - - workDoneObserver.OnNext(new WorkDoneProgressReport() { - Percentage = 30, - Message = "Report 3" - }); - - workDoneObserver.OnNext(new WorkDoneProgressReport() { - Percentage = 40, - Message = "Report 4" - }); + using var workDoneObserver = await server.WorkDoneManager.Create( + token, new WorkDoneProgressBegin { + Cancellable = true, + Message = "Begin", + Percentage = 0, + Title = "Work is pending" + }, onComplete: () => new WorkDoneProgressEnd { + Message = "End" + } + ); + + workDoneObserver.OnNext( + new WorkDoneProgressReport { + Percentage = 10, + Message = "Report 1" + } + ); + + workDoneObserver.OnNext( + new WorkDoneProgressReport { + Percentage = 20, + Message = "Report 2" + } + ); + + workDoneObserver.OnNext( + new WorkDoneProgressReport { + Percentage = 30, + Message = "Report 3" + } + ); + + workDoneObserver.OnNext( + new WorkDoneProgressReport { + Percentage = 40, + Message = "Report 4" + } + ); workDoneObserver.OnCompleted(); await Task.Delay(1000); - var results = data.Select(z => z switch { - WorkDoneProgressBegin begin => begin.Message, - WorkDoneProgressReport begin => begin.Message, - WorkDoneProgressEnd begin => begin.Message, - }); + var results = data.Select( + z => z switch { + WorkDoneProgressBegin begin => begin.Message, + WorkDoneProgressReport begin => begin.Message, + WorkDoneProgressEnd begin => begin.Message, + } + ); results.Should().ContainInOrder("Begin", "Report 1", "Report 2", "Report 3", "Report 4", "End"); } @@ -164,44 +195,56 @@ public async Task Should_Support_Observing_Work_Done_From_Client_To_Server_Reque using var workDoneObservable = client.WorkDoneManager.Monitor(token); workDoneObservable.Subscribe(x => data.Add(x)); - using var workDoneObserver = await server.WorkDoneManager.Create(token, new WorkDoneProgressBegin() { - Cancellable = true, - Message = "Begin", - Percentage = 0, - Title = "Work is pending" - }, onComplete: () => new WorkDoneProgressEnd() { - Message = "End" - }); - - workDoneObserver.OnNext(new WorkDoneProgressReport() { - Percentage = 10, - Message = "Report 1" - }); - - workDoneObserver.OnNext(new WorkDoneProgressReport() { - Percentage = 20, - Message = "Report 2" - }); - - workDoneObserver.OnNext(new WorkDoneProgressReport() { - Percentage = 30, - Message = "Report 3" - }); - - workDoneObserver.OnNext(new WorkDoneProgressReport() { - Percentage = 40, - Message = "Report 4" - }); + using var workDoneObserver = await server.WorkDoneManager.Create( + token, new WorkDoneProgressBegin { + Cancellable = true, + Message = "Begin", + Percentage = 0, + Title = "Work is pending" + }, onComplete: () => new WorkDoneProgressEnd { + Message = "End" + } + ); + + workDoneObserver.OnNext( + new WorkDoneProgressReport { + Percentage = 10, + Message = "Report 1" + } + ); + + workDoneObserver.OnNext( + new WorkDoneProgressReport { + Percentage = 20, + Message = "Report 2" + } + ); + + workDoneObserver.OnNext( + new WorkDoneProgressReport { + Percentage = 30, + Message = "Report 3" + } + ); + + workDoneObserver.OnNext( + new WorkDoneProgressReport { + Percentage = 40, + Message = "Report 4" + } + ); workDoneObserver.OnCompleted(); await Task.Delay(1000); - var results = data.Select(z => z switch { - WorkDoneProgressBegin begin => begin.Message, - WorkDoneProgressReport begin => begin.Message, - WorkDoneProgressEnd begin => begin.Message, - }); + var results = data.Select( + z => z switch { + WorkDoneProgressBegin begin => begin.Message, + WorkDoneProgressReport begin => begin.Message, + WorkDoneProgressEnd begin => begin.Message, + } + ); results.Should().ContainInOrder("Begin", "Report 1", "Report 2", "Report 3", "Report 4", "End"); } @@ -216,54 +259,65 @@ public async Task Should_Support_Cancelling_Work_Done_From_Client_To_Server_Requ using var workDoneObservable = client.WorkDoneManager.Monitor(token); workDoneObservable.Subscribe(x => data.Add(x)); - using var workDoneObserver = await server.WorkDoneManager.Create(token, new WorkDoneProgressBegin() { - Cancellable = true, - Message = "Begin", - Percentage = 0, - Title = "Work is pending" - }, onComplete: () => new WorkDoneProgressEnd() { - Message = "End" - }); - - workDoneObserver.OnNext(new WorkDoneProgressReport() { - Percentage = 10, - Message = "Report 1" - }); - - workDoneObserver.OnNext(new WorkDoneProgressReport() { - Percentage = 20, - Message = "Report 2" - }); + using var workDoneObserver = await server.WorkDoneManager.Create( + token, new WorkDoneProgressBegin { + Cancellable = true, + Message = "Begin", + Percentage = 0, + Title = "Work is pending" + }, onComplete: () => new WorkDoneProgressEnd { + Message = "End" + } + ); + + workDoneObserver.OnNext( + new WorkDoneProgressReport { + Percentage = 10, + Message = "Report 1" + } + ); + + workDoneObserver.OnNext( + new WorkDoneProgressReport { + Percentage = 20, + Message = "Report 2" + } + ); await SettleNext(); workDoneObservable.Dispose(); - workDoneObserver.OnNext(new WorkDoneProgressReport() { - Percentage = 30, - Message = "Report 3" - }); + workDoneObserver.OnNext( + new WorkDoneProgressReport { + Percentage = 30, + Message = "Report 3" + } + ); - workDoneObserver.OnNext(new WorkDoneProgressReport() { - Percentage = 40, - Message = "Report 4" - }); + workDoneObserver.OnNext( + new WorkDoneProgressReport { + Percentage = 40, + Message = "Report 4" + } + ); await Task.Delay(1000); workDoneObserver.OnCompleted(); - var results = data.Select(z => z switch { - WorkDoneProgressBegin begin => begin.Message, - WorkDoneProgressReport begin => begin.Message, - WorkDoneProgressEnd begin => begin.Message, - }); + var results = data.Select( + z => z switch { + WorkDoneProgressBegin begin => begin.Message, + WorkDoneProgressReport begin => begin.Message, + WorkDoneProgressEnd begin => begin.Message, + } + ); results.Should().ContainInOrder("Begin", "Report 1", "Report 2"); } private void ConfigureClient(LanguageClientOptions options) { - } private void ConfigureServer(LanguageServerOptions options) diff --git a/test/Lsp.Tests/Integration/RequestCancellationTests.cs b/test/Lsp.Tests/Integration/RequestCancellationTests.cs index 5715fe647..118f95311 100644 --- a/test/Lsp.Tests/Integration/RequestCancellationTests.cs +++ b/test/Lsp.Tests/Integration/RequestCancellationTests.cs @@ -34,9 +34,11 @@ public async Task Should_Cancel_Pending_Requests() Func> action = () => { var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(10)); CancellationToken.Register(cts.Cancel); - return client.TextDocument.RequestCompletion(new CompletionParams() { - TextDocument = "/a/file.cs" - }, cts.Token).AsTask(); + return client.TextDocument.RequestCompletion( + new CompletionParams { + TextDocument = "/a/file.cs" + }, cts.Token + ).AsTask(); }; action.Should().Throw(); } @@ -46,17 +48,21 @@ public async Task Should_Abandon_Pending_Requests_For_Text_Changes() { var (client, server) = await Initialize(ConfigureClient, ConfigureServer); - var request1 = client.TextDocument.RequestCompletion(new CompletionParams() { - TextDocument = "/a/file.cs" - }, CancellationToken).AsTask(); - - client.TextDocument.DidChangeTextDocument(new DidChangeTextDocumentParams() { - TextDocument = new VersionedTextDocumentIdentifier() { - Uri = "/a/file.cs", - Version = 123, - }, - ContentChanges = new Container() - }); + var request1 = client.TextDocument.RequestCompletion( + new CompletionParams { + TextDocument = "/a/file.cs" + }, CancellationToken + ).AsTask(); + + client.TextDocument.DidChangeTextDocument( + new DidChangeTextDocumentParams { + TextDocument = new VersionedTextDocumentIdentifier { + Uri = "/a/file.cs", + Version = 123, + }, + ContentChanges = new Container() + } + ); Func action = () => request1; action.Should().Throw(); @@ -66,14 +72,18 @@ public async Task Should_Abandon_Pending_Requests_For_Text_Changes() public async Task Should_Cancel_Requests_After_Timeout() { Func action = async () => { - var (client, server) = await Initialize(ConfigureClient, x => { - ConfigureServer(x); - x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(3000)); - }); - - await client.TextDocument.RequestCompletion(new CompletionParams() { - TextDocument = "/a/file.cs" - }, CancellationToken).AsTask(); + var (client, server) = await Initialize( + ConfigureClient, x => { + ConfigureServer(x); + x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(3000)); + } + ); + + await client.TextDocument.RequestCompletion( + new CompletionParams { + TextDocument = "/a/file.cs" + }, CancellationToken + ).AsTask(); }; action.Should().Throw(); } @@ -81,32 +91,42 @@ await client.TextDocument.RequestCompletion(new CompletionParams() { [Fact] public async Task Should_Cancel_Requests_After_Timeout_without_Content_Modified() { - var (client, server) = await Initialize(ConfigureClient, x => { - ConfigureServer(x); - x.WithContentModifiedSupport(false).WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(3000)); - }); - - Func action = () => client.TextDocument.RequestCompletion(new CompletionParams() { - TextDocument = "/a/file.cs" - }, CancellationToken).AsTask(); + var (client, server) = await Initialize( + ConfigureClient, x => { + ConfigureServer(x); + x.WithContentModifiedSupport(false).WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(3000)); + } + ); + + Func action = () => client.TextDocument.RequestCompletion( + new CompletionParams { + TextDocument = "/a/file.cs" + }, CancellationToken + ).AsTask(); action.Should().Throw(); } [Fact] public async Task Can_Publish_Diagnostics_Delayed() { - var (client, server) = await Initialize(ConfigureClient, x => { - ConfigureServer(x); - x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(10000)); - }); - - server.TextDocument.PublishDiagnostics(new PublishDiagnosticsParams() { - Diagnostics = new Container(new Diagnostic() { - Message = "asdf", - }), - Uri = DocumentUri.File("/from/file"), - Version = 1 - }); + var (client, server) = await Initialize( + ConfigureClient, x => { + ConfigureServer(x); + x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(10000)); + } + ); + + server.TextDocument.PublishDiagnostics( + new PublishDiagnosticsParams { + Diagnostics = new Container( + new Diagnostic { + Message = "asdf", + } + ), + Uri = DocumentUri.File("/from/file"), + Version = 1 + } + ); await ServerEvents.Settle(); await ClientEvents.Settle(); @@ -118,29 +138,31 @@ public async Task Can_Publish_Diagnostics_Delayed() private readonly ConcurrentDictionary> _diagnostics = new ConcurrentDictionary>(); - private void ConfigureClient(LanguageClientOptions options) - { - options.OnPublishDiagnostics(async (request, ct) => { - try - { - TestOptions.ClientLoggerFactory.CreateLogger("test").LogCritical("start"); - await Task.Delay(500, ct); - _diagnostics.AddOrUpdate(request.Uri, (a) => request.Diagnostics, (a, b) => request.Diagnostics); + private void ConfigureClient(LanguageClientOptions options) => + options.OnPublishDiagnostics( + async (request, ct) => { + try + { + TestOptions.ClientLoggerFactory.CreateLogger("test").LogCritical("start"); + await Task.Delay(500, ct); + _diagnostics.AddOrUpdate(request.Uri, a => request.Diagnostics, (a, b) => request.Diagnostics); + } + catch (Exception e) + { + TestOptions.ClientLoggerFactory.CreateLogger("test").LogCritical(e, "error"); + } } - catch (Exception e) - { - TestOptions.ClientLoggerFactory.CreateLogger("test").LogCritical(e, "error"); - } - }); - } + ); private void ConfigureServer(LanguageServerOptions options) { options.WithContentModifiedSupport(true); - options.OnCompletion(async (x, ct) => { - await Task.Delay(50000, ct); - return new CompletionList(); - }, new CompletionRegistrationOptions()); + options.OnCompletion( + async (x, ct) => { + await Task.Delay(50000, ct); + return new CompletionList(); + }, new CompletionRegistrationOptions() + ); options.OnDidChangeTextDocument(async x => { await Task.Delay(20); }, new TextDocumentChangeRegistrationOptions()); } } diff --git a/test/Lsp.Tests/Integration/ShowMessageTests.cs b/test/Lsp.Tests/Integration/ShowMessageTests.cs index 46c4da30f..d7929639d 100644 --- a/test/Lsp.Tests/Integration/ShowMessageTests.cs +++ b/test/Lsp.Tests/Integration/ShowMessageTests.cs @@ -1,10 +1,8 @@ using System; -using System.Linq; using System.Collections.Generic; -using System.Reactive.Linq; +using System.Linq; using System.Threading.Tasks; using FluentAssertions; -using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; @@ -34,12 +32,16 @@ public async Task Should_Show_Messages_Through_Window_Extension_Methods() server.Window.ShowInfo("Here's something cool..."); server.Window.ShowWarning("Uh-oh..."); server.Window.Show("Just gotta let you know!"); - server.Window.Show(new ShowMessageParams() { - Type = MessageType.Log, Message = "1234" - }); - server.Window.ShowMessage(new ShowMessageParams() { - Type = MessageType.Log, Message = "1234" - }); + server.Window.Show( + new ShowMessageParams { + Type = MessageType.Log, Message = "1234" + } + ); + server.Window.ShowMessage( + new ShowMessageParams { + Type = MessageType.Log, Message = "1234" + } + ); await Task.Delay(1000); @@ -59,12 +61,16 @@ public async Task Should_Show_Messages_Through_Server_Extension_Methods() server.ShowInfo("Here's something cool..."); server.ShowWarning("Uh-oh..."); server.Show("Just gotta let you know!"); - server.Show(new ShowMessageParams() { - Type = MessageType.Log, Message = "1234" - }); - server.ShowMessage(new ShowMessageParams() { - Type = MessageType.Log, Message = "1234" - }); + server.Show( + new ShowMessageParams { + Type = MessageType.Log, Message = "1234" + } + ); + server.ShowMessage( + new ShowMessageParams { + Type = MessageType.Log, Message = "1234" + } + ); await Task.Delay(1000); @@ -75,10 +81,7 @@ 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.Tests/Integration/TypedCodeLensTests.cs b/test/Lsp.Tests/Integration/TypedCodeLensTests.cs index c8d1a2388..0bd796571 100644 --- a/test/Lsp.Tests/Integration/TypedCodeLensTests.cs +++ b/test/Lsp.Tests/Integration/TypedCodeLensTests.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; @@ -12,16 +11,15 @@ using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; using Serilog.Events; using Xunit; using Xunit.Abstractions; +using HandlerIdentity = OmniSharp.Extensions.LanguageServer.Protocol.Models.HandlerIdentity; namespace Lsp.Tests.Integration { public class TypedCodeLensTests : LanguageProtocolTestBase { - public TypedCodeLensTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper, LogEventLevel.Verbose)) { } @@ -29,101 +27,124 @@ public TypedCodeLensTests(ITestOutputHelper outputHelper) : base(new JsonRpcTest [Fact] public async Task Should_Aggregate_With_All_Related_Handlers() { - var (client, server) = await Initialize( options => { }, options => { var identifier = Substitute.For(); identifier.GetTextDocumentAttributes(Arg.Any()).Returns( - call => new TextDocumentAttributes(call.ArgAt(0), "file", "csharp")); + call => new TextDocumentAttributes(call.ArgAt(0), "file", "csharp") + ); options.AddTextDocumentIdentifier(identifier); - options.OnCodeLens((codeLensParams) => { - return Task.FromResult(new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "data-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - })); + options.OnCodeLens( + codeLensParams => { + return Task.FromResult( + new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "data-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ) + ); }, - (codeLens) => { + codeLens => { codeLens.Command.Name = "resolved-a"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { + new CodeLensRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") - }); - - options.OnCodeLens((codeLensParams) => { - return Task.FromResult(new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "nested-b", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - Data = new Nested() { - Date = DateTimeOffset.Now - } - })); + } + ); + + options.OnCodeLens( + codeLensParams => { + return Task.FromResult( + new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "nested-b", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + Data = new Nested { + Date = DateTimeOffset.Now + } + } + ) + ); }, - (codeLens) => { + codeLens => { codeLens.Command.Name = "resolved-b"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { + new CodeLensRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") - }); - - options.OnCodeLens((codeLensParams) => { - return Task.FromResult(new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "no-data-c", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - } - })); + } + ); + + options.OnCodeLens( + codeLensParams => { + return Task.FromResult( + new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "no-data-c", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + } + } + ) + ); }, - (codeLens) => { + codeLens => { codeLens.Command.Name = "resolved-c"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { + new CodeLensRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") - }); - - options.OnCodeLens((codeLensParams) => { - return Task.FromResult(new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "not-included", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - } - })); + } + ); + + options.OnCodeLens( + codeLensParams => { + return Task.FromResult( + new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "not-included", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + } + } + ) + ); }, - (codeLens) => { + codeLens => { codeLens.Command.Name = "resolved-d"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { + new CodeLensRegistrationOptions { DocumentSelector = DocumentSelector.ForLanguage("vb") - }); - }); + } + ); + } + ); - var codeLens = await client.RequestCodeLens(new CodeLensParams() { - TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), - }); + var codeLens = await client.RequestCodeLens( + new CodeLensParams { + TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), + } + ); var lens = codeLens.ToArray(); var responses = await Task.WhenAll(lens.Select(z => client.ResolveCodeLens(z))); - responses.Select(z => z.Command.Name).Should().Contain(new [] { "resolved-a", "resolved-b", "resolved-c" }); + responses.Select(z => z.Command.Name).Should().Contain(new[] { "resolved-a", "resolved-b", "resolved-c" }); responses.Select(z => z.Command.Name).Should().NotContain("resolved-d"); lens.Length.Should().Be(3); } @@ -131,24 +152,28 @@ public async Task Should_Aggregate_With_All_Related_Handlers() [Fact] public async Task Should_Resolve_With_Data_Capability() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCodeLens((codeLensParams, capability, token) => { - return Task.FromResult(new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - })); - }, + options.OnCodeLens( + (codeLensParams, capability, token) => { + return Task.FromResult( + new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ) + ); + }, (codeLens, capability, token) => { codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); @@ -156,10 +181,10 @@ public async Task Should_Resolve_With_Data_Capability() codeLens.Command.Name = "resolved"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { - }); - }); + new CodeLensRegistrationOptions() + ); + } + ); var items = await client.RequestCodeLens(new CodeLensParams()); @@ -172,27 +197,29 @@ public async Task Should_Resolve_With_Data_Capability() [Fact] public async Task Should_Resolve_With_Partial_Data_Capability() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCodeLens((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 Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - }); - - observer.OnNext(a); - observer.OnCompleted(); - }, + options.OnCodeLens( + (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 Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ); + + observer.OnNext(a); + observer.OnCompleted(); + }, (codeLens, capability, token) => { codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); @@ -200,10 +227,10 @@ public async Task Should_Resolve_With_Partial_Data_Capability() codeLens.Command.Name = "resolved"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { - }); - }); + new CodeLensRegistrationOptions() + ); + } + ); var item = await client.RequestCodeLens(new CodeLensParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -214,24 +241,28 @@ public async Task Should_Resolve_With_Partial_Data_Capability() [Fact] public async Task Should_Resolve_With_Data_CancellationToken() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCodeLens((codeLensParams, token) => { - return Task.FromResult(new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - })); - }, + options.OnCodeLens( + (codeLensParams, token) => { + return Task.FromResult( + new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ) + ); + }, (codeLens, token) => { codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); @@ -239,10 +270,10 @@ public async Task Should_Resolve_With_Data_CancellationToken() codeLens.Command.Name = "resolved"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { - }); - }); + new CodeLensRegistrationOptions() + ); + } + ); var items = await client.RequestCodeLens(new CodeLensParams()); @@ -255,27 +286,29 @@ public async Task Should_Resolve_With_Data_CancellationToken() [Fact] public async Task Should_Resolve_With_Partial_Data_CancellationToken() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCodeLens((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 Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - }); - - observer.OnNext(a); - observer.OnCompleted(); - }, + options.OnCodeLens( + (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 Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ); + + observer.OnNext(a); + observer.OnCompleted(); + }, (codeLens, token) => { codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); @@ -283,10 +316,10 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() codeLens.Command.Name = "resolved"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { - }); - }); + new CodeLensRegistrationOptions() + ); + } + ); var item = await client.RequestCodeLens(new CodeLensParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -297,35 +330,39 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() [Fact] public async Task Should_Resolve_With_Data() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCodeLens((codeLensParams) => { - return Task.FromResult(new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - })); - }, - (codeLens) => { + options.OnCodeLens( + codeLensParams => { + return Task.FromResult( + new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ) + ); + }, + codeLens => { codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); codeLens.Data.Name.Should().Be("name"); codeLens.Command.Name = "resolved"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { - }); - }); + new CodeLensRegistrationOptions() + ); + } + ); var items = await client.RequestCodeLens(new CodeLensParams()); @@ -338,38 +375,40 @@ public async Task Should_Resolve_With_Data() [Fact] public async Task Should_Resolve_With_Partial_Data() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCodeLens((codeLensParams, observer) => { - var a = new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - }); - - observer.OnNext(a); - observer.OnCompleted(); - }, - (codeLens) => { + options.OnCodeLens( + (codeLensParams, observer) => { + var a = new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ); + + observer.OnNext(a); + observer.OnCompleted(); + }, + codeLens => { codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); codeLens.Data.Name.Should().Be("name"); codeLens.Command.Name = "resolved"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { - }); - }); + new CodeLensRegistrationOptions() + ); + } + ); var item = await client.RequestCodeLens(new CodeLensParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -381,24 +420,29 @@ public async Task Should_Resolve_With_Partial_Data() [Fact] public async Task Should_Resolve_Capability() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCodeLens((codeLensParams, capability, token) => { - return Task.FromResult(new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - } - })); - }, + options.OnCodeLens( + (codeLensParams, capability, token) => { + return Task.FromResult( + new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + } + } + ) + ); + }, (codeLens, capability, token) => { codeLens.Command.Name = "resolved"; return Task.FromResult(codeLens); }, - new CodeLensRegistrationOptions() { - }); - }); + new CodeLensRegistrationOptions() + ); + } + ); var items = await client.RequestCodeLens(new CodeLensParams()); @@ -411,28 +455,30 @@ public async Task Should_Resolve_Capability() [Fact] public async Task Should_Resolve_Partial_Capability() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCodeLens((codeLensParams, observer, capability, token) => { - var a = new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - }); - - observer.OnNext(a); - observer.OnCompleted(); - }, + options.OnCodeLens( + (codeLensParams, observer, capability, token) => { + var a = new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + } + ); + observer.OnNext(a); + observer.OnCompleted(); + }, (codeLens, capability, token) => { codeLens.Command.Name = "resolved"; return Task.FromResult(codeLens); }, - new CodeLensRegistrationOptions() { - }); - }); + new CodeLensRegistrationOptions() + ); + } + ); var item = await client.RequestCodeLens(new CodeLensParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -443,25 +489,29 @@ public async Task Should_Resolve_Partial_Capability() [Fact] public async Task Should_Resolve_CancellationToken() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCodeLens((codeLensParams, token) => { - return Task.FromResult(new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - })); - }, + options.OnCodeLens( + (codeLensParams, token) => { + return Task.FromResult( + new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + } + ) + ); + }, (codeLens, token) => { codeLens.Command.Name = "resolved"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { - }); - }); + new CodeLensRegistrationOptions() + ); + } + ); var items = await client.RequestCodeLens(new CodeLensParams()); @@ -474,28 +524,30 @@ public async Task Should_Resolve_CancellationToken() [Fact] public async Task Should_Resolve_Partial_CancellationToken() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCodeLens((codeLensParams, observer, token) => { - var a = new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - }); - - observer.OnNext(a); - observer.OnCompleted(); - }, + options.OnCodeLens( + (codeLensParams, observer, token) => { + var a = new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + } + ); + + observer.OnNext(a); + observer.OnCompleted(); + }, (codeLens, token) => { codeLens.Command.Name = "resolved"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { - }); - }); + new CodeLensRegistrationOptions() + ); + } + ); var item = await client.RequestCodeLens(new CodeLensParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -506,25 +558,29 @@ public async Task Should_Resolve_Partial_CancellationToken() [Fact] public async Task Should_Resolve() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCodeLens((codeLensParams) => { - return Task.FromResult(new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - })); - }, - (codeLens) => { + options.OnCodeLens( + codeLensParams => { + return Task.FromResult( + new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + } + ) + ); + }, + codeLens => { codeLens.Command.Name = "resolved"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { - }); - }); + new CodeLensRegistrationOptions() + ); + } + ); var items = await client.RequestCodeLens(new CodeLensParams()); @@ -537,28 +593,30 @@ public async Task Should_Resolve() [Fact] public async Task Should_Resolve_Partial() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCodeLens((codeLensParams, observer) => { - var a = new CodeLensContainer(new CodeLens() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - }); - - observer.OnNext(a); - observer.OnCompleted(); - }, - (codeLens) => { + options.OnCodeLens( + (codeLensParams, observer) => { + var a = new CodeLensContainer( + new CodeLens { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + } + ); + + observer.OnNext(a); + observer.OnCompleted(); + }, + codeLens => { codeLens.Command.Name = "resolved"; return Task.FromResult(codeLens); }, - - new CodeLensRegistrationOptions() { - }); - }); + new CodeLensRegistrationOptions() + ); + } + ); var item = await client.RequestCodeLens(new CodeLensParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -566,15 +624,14 @@ public async Task Should_Resolve_Partial() item.Command.Name.Should().Be("resolved"); } - class Data : HandlerIdentity + private class Data : HandlerIdentity { public string Name { get; set; } public Guid Id { get; set; } public Nested Child { get; set; } - } - class Nested : HandlerIdentity + private class Nested : HandlerIdentity { public DateTimeOffset Date { get; set; } } diff --git a/test/Lsp.Tests/Integration/TypedCompletionTests.cs b/test/Lsp.Tests/Integration/TypedCompletionTests.cs index cfb747183..d773c1c87 100644 --- a/test/Lsp.Tests/Integration/TypedCompletionTests.cs +++ b/test/Lsp.Tests/Integration/TypedCompletionTests.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; @@ -15,12 +14,12 @@ using Serilog.Events; using Xunit; using Xunit.Abstractions; +using HandlerIdentity = OmniSharp.Extensions.LanguageServer.Protocol.Models.HandlerIdentity; namespace Lsp.Tests.Integration { public class TypedCompletionTests : LanguageProtocolTestBase { - public TypedCompletionTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper, LogEventLevel.Verbose)) { } @@ -32,91 +31,115 @@ public async Task Should_Aggregate_With_All_Related_Handlers() options => { }, options => { var identifier = Substitute.For(); identifier.GetTextDocumentAttributes(Arg.Any()).Returns( - call => new TextDocumentAttributes(call.ArgAt(0), "file", "csharp")); + call => new TextDocumentAttributes(call.ArgAt(0), "file", "csharp") + ); options.AddTextDocumentIdentifier(identifier); - options.OnCompletion((codeLensParams) => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "data-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - })); - }, - (codeLens) => { + options.OnCompletion( + codeLensParams => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = new Command { + Name = "data-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ) + ); + }, + codeLens => { codeLens.Command.Name = "resolved-a"; return Task.FromResult(codeLens); }, - - new CompletionRegistrationOptions() { + new CompletionRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") - }); - - options.OnCompletion((codeLensParams) => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "nested-b", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - Data = new Nested() { - Date = DateTimeOffset.Now - } - })); - }, - (codeLens) => { + } + ); + + options.OnCompletion( + codeLensParams => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = new Command { + Name = "nested-b", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + Data = new Nested { + Date = DateTimeOffset.Now + } + } + ) + ); + }, + codeLens => { codeLens.Command.Name = "resolved-b"; return Task.FromResult(codeLens); }, - - new CompletionRegistrationOptions() { + new CompletionRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") - }); - - options.OnCompletion((codeLensParams) => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "no-data-c", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - } - })); - }, - (codeLens) => { + } + ); + + options.OnCompletion( + codeLensParams => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = new Command { + Name = "no-data-c", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + } + } + ) + ); + }, + codeLens => { codeLens.Command.Name = "resolved-c"; return Task.FromResult(codeLens); }, - - new CompletionRegistrationOptions() { + new CompletionRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") - }); - - options.OnCompletion((codeLensParams) => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "not-included", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - } - })); - }, - (codeLens) => { + } + ); + + options.OnCompletion( + codeLensParams => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = new Command { + Name = "not-included", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + } + } + ) + ); + }, + codeLens => { codeLens.Command.Name = "resolved-d"; return Task.FromResult(codeLens); }, - - new CompletionRegistrationOptions() { + new CompletionRegistrationOptions { DocumentSelector = DocumentSelector.ForLanguage("vb") - }); - }); + } + ); + } + ); - var codeLens = await client.RequestCompletion(new CompletionParams() { - TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), - }); + var codeLens = await client.RequestCompletion( + new CompletionParams { + TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), + } + ); var lens = codeLens.ToArray(); @@ -129,35 +152,39 @@ public async Task Should_Aggregate_With_All_Related_Handlers() [Fact] public async Task Should_Resolve_With_Data_Capability() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion((completionParams, capability, token) => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - })); + options.OnCompletion( + (completionParams, capability, token) => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ) + ); }, (completionItem, capability, token) => { - AssertionExtensions.Should((Guid) completionItem.Data.Id).NotBeEmpty(); - AssertionExtensions.Should((object) completionItem.Data.Child).NotBeNull(); - AssertionExtensions.Should((string) completionItem.Data.Name).Be("name"); + completionItem.Data.Id.Should().NotBeEmpty(); + completionItem.Data.Child.Should().NotBeNull(); + completionItem.Data.Name.Should().Be("name"); completionItem.Detail = "resolved"; - return Task.FromResult>(completionItem); + return Task.FromResult(completionItem); }, - - new CompletionRegistrationOptions() { - }); - }); + new CompletionRegistrationOptions() + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -170,23 +197,25 @@ public async Task Should_Resolve_With_Data_Capability() [Fact] public async Task Should_Resolve_With_Partial_Data_Capability() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion((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 Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue + options.OnCompletion( + (completionParams, observer, capability, token) => { + var a = new CompletionList( + new CompletionItem { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Id = Guid.NewGuid(), - Name = "name" + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } } - }); + ); observer.OnNext(a); observer.OnCompleted(); @@ -198,10 +227,10 @@ public async Task Should_Resolve_With_Partial_Data_Capability() completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, - - new CompletionRegistrationOptions() { - }); - }); + new CompletionRegistrationOptions() + ); + } + ); var item = await client.RequestCompletion(new CompletionParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -212,23 +241,27 @@ public async Task Should_Resolve_With_Partial_Data_Capability() [Fact] public async Task Should_Resolve_With_Data_CancellationToken() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion((completionParams, token) => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - })); + options.OnCompletion( + (completionParams, token) => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ) + ); }, (completionItem, token) => { completionItem.Data.Id.Should().NotBeEmpty(); @@ -237,10 +270,10 @@ public async Task Should_Resolve_With_Data_CancellationToken() completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, - - new CompletionRegistrationOptions() { - }); - }); + new CompletionRegistrationOptions() + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -253,23 +286,25 @@ public async Task Should_Resolve_With_Data_CancellationToken() [Fact] public async Task Should_Resolve_With_Partial_Data_CancellationToken() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion((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 Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue + options.OnCompletion( + (completionParams, observer, token) => { + var a = new CompletionList( + new CompletionItem { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Id = Guid.NewGuid(), - Name = "name" + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } } - }); + ); observer.OnNext(a); observer.OnCompleted(); @@ -281,10 +316,10 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, - - new CompletionRegistrationOptions() { - }); - }); + new CompletionRegistrationOptions() + ); + } + ); var item = await client.RequestCompletion(new CompletionParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -295,35 +330,39 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() [Fact] public async Task Should_Resolve_With_Data() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion((completionParams) => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - })); - }, - (completionItem) => { + options.OnCompletion( + completionParams => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ) + ); + }, + completionItem => { completionItem.Data.Id.Should().NotBeEmpty(); completionItem.Data.Child.Should().NotBeNull(); completionItem.Data.Name.Should().Be("name"); completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, - - new CompletionRegistrationOptions() { - }); - }); + new CompletionRegistrationOptions() + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -336,38 +375,40 @@ public async Task Should_Resolve_With_Data() [Fact] public async Task Should_Resolve_With_Partial_Data() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion((completionParams, observer) => { - var a = new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue + options.OnCompletion( + (completionParams, observer) => { + var a = new CompletionList( + new CompletionItem { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) }, - Id = Guid.NewGuid(), - Name = "name" + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } } - }); + ); observer.OnNext(a); observer.OnCompleted(); }, - (completionItem) => { + completionItem => { completionItem.Data.Id.Should().NotBeEmpty(); completionItem.Data.Child.Should().NotBeNull(); completionItem.Data.Name.Should().Be("name"); completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, - - new CompletionRegistrationOptions() { - }); - }); + new CompletionRegistrationOptions() + ); + } + ); var item = await client.RequestCompletion(new CompletionParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -379,24 +420,29 @@ public async Task Should_Resolve_With_Partial_Data() [Fact] public async Task Should_Resolve_Capability() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion((completionParams, capability, token) => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - } - })); + options.OnCompletion( + (completionParams, capability, token) => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + } + } + ) + ); }, (completionItem, capability, token) => { completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, - new CompletionRegistrationOptions() { - }); - }); + new CompletionRegistrationOptions() + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -409,28 +455,30 @@ public async Task Should_Resolve_Capability() [Fact] public async Task Should_Resolve_Partial_Capability() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion((completionParams, observer, capability, token) => { - var a = new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - }); + options.OnCompletion( + (completionParams, observer, capability, token) => { + var a = new CompletionList( + new CompletionItem { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + } + ); observer.OnNext(a); observer.OnCompleted(); }, - (completionItem, capability, token) => { completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, - new CompletionRegistrationOptions() { - }); - }); + new CompletionRegistrationOptions() + ); + } + ); var item = await client.RequestCompletion(new CompletionParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -441,25 +489,29 @@ public async Task Should_Resolve_Partial_Capability() [Fact] public async Task Should_Resolve_CancellationToken() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion((completionParams, token) => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - })); + options.OnCompletion( + (completionParams, token) => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + } + ) + ); }, (completionItem, token) => { completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, - - new CompletionRegistrationOptions() { - }); - }); + new CompletionRegistrationOptions() + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -472,16 +524,18 @@ public async Task Should_Resolve_CancellationToken() [Fact] public async Task Should_Resolve_Partial_CancellationToken() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion((completionParams, observer, token) => { - var a = new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - }); + options.OnCompletion( + (completionParams, observer, token) => { + var a = new CompletionList( + new CompletionItem { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + } + ); observer.OnNext(a); observer.OnCompleted(); @@ -490,10 +544,10 @@ public async Task Should_Resolve_Partial_CancellationToken() completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, - - new CompletionRegistrationOptions() { - }); - }); + new CompletionRegistrationOptions() + ); + } + ); var item = await client.RequestCompletion(new CompletionParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -504,25 +558,29 @@ public async Task Should_Resolve_Partial_CancellationToken() [Fact] public async Task Should_Resolve() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion((completionParams) => { - return Task.FromResult(new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - })); - }, - (completionItem) => { + options.OnCompletion( + completionParams => { + return Task.FromResult( + new CompletionList( + new CompletionItem { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + } + ) + ); + }, + completionItem => { completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, - - new CompletionRegistrationOptions() { - }); - }); + new CompletionRegistrationOptions() + ); + } + ); var items = await client.RequestCompletion(new CompletionParams()); @@ -535,28 +593,30 @@ public async Task Should_Resolve() [Fact] public async Task Should_Resolve_Partial() { - var (client, server) = await Initialize( options => { }, options => { - options.OnCompletion((completionParams, observer) => { - var a = new CompletionList(new CompletionItem() { - Command = new Command() { - Name = "execute-a", - Arguments = JArray.FromObject(new object[] { 1, "2", false }) - }, - }); + options.OnCompletion( + (completionParams, observer) => { + var a = new CompletionList( + new CompletionItem { + Command = new Command { + Name = "execute-a", + Arguments = JArray.FromObject(new object[] { 1, "2", false }) + }, + } + ); observer.OnNext(a); observer.OnCompleted(); }, - (completionItem) => { + completionItem => { completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, - - new CompletionRegistrationOptions() { - }); - }); + new CompletionRegistrationOptions() + ); + } + ); var item = await client.RequestCompletion(new CompletionParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -564,15 +624,14 @@ public async Task Should_Resolve_Partial() item.Detail.Should().Be("resolved"); } - class Data : HandlerIdentity + private class Data : HandlerIdentity { public string Name { get; set; } public Guid Id { get; set; } public Nested Child { get; set; } - } - class Nested : HandlerIdentity + private class Nested : HandlerIdentity { public DateTimeOffset Date { get; set; } } diff --git a/test/Lsp.Tests/Integration/TypedDocumentLinkTests.cs b/test/Lsp.Tests/Integration/TypedDocumentLinkTests.cs index df2ff8fcb..581bd93f6 100644 --- a/test/Lsp.Tests/Integration/TypedDocumentLinkTests.cs +++ b/test/Lsp.Tests/Integration/TypedDocumentLinkTests.cs @@ -1,11 +1,9 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using FluentAssertions; -using Newtonsoft.Json.Linq; using NSubstitute; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; @@ -19,8 +17,7 @@ namespace Lsp.Tests.Integration { public class TypedDocumentLinkTests : LanguageProtocolTestBase - { - + { public TypedDocumentLinkTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper, LogEventLevel.Verbose)) { } @@ -28,89 +25,112 @@ public TypedDocumentLinkTests(ITestOutputHelper outputHelper) : base(new JsonRpc [Fact] public async Task Should_Aggregate_With_All_Related_Handlers() { - var (client, server) = await Initialize( options => { }, options => { var identifier = Substitute.For(); identifier.GetTextDocumentAttributes(Arg.Any()).Returns( - call => new TextDocumentAttributes(call.ArgAt(0), "file", "csharp")); + call => new TextDocumentAttributes(call.ArgAt(0), "file", "csharp") + ); options.AddTextDocumentIdentifier(identifier); - options.OnDocumentLink((codeLensParams) => { - return Task.FromResult(new DocumentLinkContainer(new DocumentLink() { - Tooltip = "data-a", - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - })); + options.OnDocumentLink( + codeLensParams => { + return Task.FromResult( + new DocumentLinkContainer( + new DocumentLink { + Tooltip = "data-a", + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ) + ); }, - (codeLens) => { + codeLens => { codeLens.Tooltip = "resolved-a"; return Task.FromResult(codeLens); }, - - new DocumentLinkRegistrationOptions() { + new DocumentLinkRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") - }); - - options.OnDocumentLink((codeLensParams) => { - return Task.FromResult(new DocumentLinkContainer(new DocumentLink() { - Tooltip = "nested-b", - Data = new Nested() { - Date = DateTimeOffset.Now - } - })); + } + ); + + options.OnDocumentLink( + codeLensParams => { + return Task.FromResult( + new DocumentLinkContainer( + new DocumentLink { + Tooltip = "nested-b", + Data = new Nested { + Date = DateTimeOffset.Now + } + } + ) + ); }, - (codeLens) => { + codeLens => { codeLens.Tooltip = "resolved-b"; return Task.FromResult(codeLens); }, - - new DocumentLinkRegistrationOptions() { + new DocumentLinkRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") - }); - - options.OnDocumentLink((codeLensParams) => { - return Task.FromResult(new DocumentLinkContainer(new DocumentLink() { - Tooltip = "no-data-c", - })); + } + ); + + options.OnDocumentLink( + codeLensParams => { + return Task.FromResult( + new DocumentLinkContainer( + new DocumentLink { + Tooltip = "no-data-c", + } + ) + ); }, - (codeLens) => { + codeLens => { codeLens.Tooltip = "resolved-c"; return Task.FromResult(codeLens); }, - - new DocumentLinkRegistrationOptions() { + new DocumentLinkRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") - }); - - options.OnDocumentLink((codeLensParams) => { - return Task.FromResult(new DocumentLinkContainer(new DocumentLink() { - Tooltip = "not-included", - })); + } + ); + + options.OnDocumentLink( + codeLensParams => { + return Task.FromResult( + new DocumentLinkContainer( + new DocumentLink { + Tooltip = "not-included", + } + ) + ); }, - (codeLens) => { + codeLens => { codeLens.Tooltip = "resolved-d"; return Task.FromResult(codeLens); }, - - new DocumentLinkRegistrationOptions() { + new DocumentLinkRegistrationOptions { DocumentSelector = DocumentSelector.ForLanguage("vb") - }); - }); + } + ); + } + ); - var codeLens = await client.RequestDocumentLink(new DocumentLinkParams() { - TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), - }); + var codeLens = await client.RequestDocumentLink( + new DocumentLinkParams { + TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), + } + ); var lens = codeLens.ToArray(); var responses = await Task.WhenAll(lens.Select(z => client.ResolveDocumentLink(z))); - responses.Select(z => z.Tooltip).Should().Contain(new [] { "resolved-a", "resolved-b", "resolved-c" }); + responses.Select(z => z.Tooltip).Should().Contain(new[] { "resolved-a", "resolved-b", "resolved-c" }); responses.Select(z => z.Tooltip).Should().NotContain("resolved-d"); lens.Length.Should().Be(3); } @@ -118,21 +138,25 @@ public async Task Should_Aggregate_With_All_Related_Handlers() [Fact] public async Task Should_Resolve_With_Data_Capability() { - var (client, server) = await Initialize( options => { }, options => { - options.OnDocumentLink((documentLinkParams, capability, token) => { - return Task.FromResult(new DocumentLinkContainer(new DocumentLink() { - Tooltip = "execute-a", - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - })); - }, + options.OnDocumentLink( + (documentLinkParams, capability, token) => { + return Task.FromResult( + new DocumentLinkContainer( + new DocumentLink { + Tooltip = "execute-a", + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ) + ); + }, (documentLink, capability, token) => { documentLink.Data.Id.Should().NotBeEmpty(); documentLink.Data.Child.Should().NotBeNull(); @@ -140,10 +164,10 @@ public async Task Should_Resolve_With_Data_Capability() documentLink.Tooltip = "resolved"; return Task.FromResult(documentLink); }, - - new DocumentLinkRegistrationOptions() { - }); - }); + new DocumentLinkRegistrationOptions() + ); + } + ); var items = await client.RequestDocumentLink(new DocumentLinkParams()); @@ -156,24 +180,26 @@ public async Task Should_Resolve_With_Data_Capability() [Fact] public async Task Should_Resolve_With_Partial_Data_Capability() { - var (client, server) = await Initialize( options => { }, options => { - options.OnDocumentLink((documentLinkParams, observer, capability, token) => { - var a = new DocumentLinkContainer(new DocumentLink() { - Tooltip = "execute-a", - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - }); - - observer.OnNext(a); - observer.OnCompleted(); - }, + options.OnDocumentLink( + (documentLinkParams, observer, capability, token) => { + var a = new DocumentLinkContainer( + new DocumentLink { + Tooltip = "execute-a", + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ); + + observer.OnNext(a); + observer.OnCompleted(); + }, (documentLink, capability, token) => { documentLink.Data.Id.Should().NotBeEmpty(); documentLink.Data.Child.Should().NotBeNull(); @@ -181,10 +207,10 @@ public async Task Should_Resolve_With_Partial_Data_Capability() documentLink.Tooltip = "resolved"; return Task.FromResult(documentLink); }, - - new DocumentLinkRegistrationOptions() { - }); - }); + new DocumentLinkRegistrationOptions() + ); + } + ); var item = await client.RequestDocumentLink(new DocumentLinkParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -195,21 +221,25 @@ public async Task Should_Resolve_With_Partial_Data_Capability() [Fact] public async Task Should_Resolve_With_Data_CancellationToken() { - var (client, server) = await Initialize( options => { }, options => { - options.OnDocumentLink((documentLinkParams, token) => { - return Task.FromResult(new DocumentLinkContainer(new DocumentLink() { - Tooltip = "execute-a", - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - })); - }, + options.OnDocumentLink( + (documentLinkParams, token) => { + return Task.FromResult( + new DocumentLinkContainer( + new DocumentLink { + Tooltip = "execute-a", + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ) + ); + }, (documentLink, token) => { documentLink.Data.Id.Should().NotBeEmpty(); documentLink.Data.Child.Should().NotBeNull(); @@ -217,10 +247,10 @@ public async Task Should_Resolve_With_Data_CancellationToken() documentLink.Tooltip = "resolved"; return Task.FromResult(documentLink); }, - - new DocumentLinkRegistrationOptions() { - }); - }); + new DocumentLinkRegistrationOptions() + ); + } + ); var items = await client.RequestDocumentLink(new DocumentLinkParams()); @@ -233,24 +263,26 @@ public async Task Should_Resolve_With_Data_CancellationToken() [Fact] public async Task Should_Resolve_With_Partial_Data_CancellationToken() { - var (client, server) = await Initialize( options => { }, options => { - options.OnDocumentLink((documentLinkParams, observer, token) => { - var a = new DocumentLinkContainer(new DocumentLink() { - Tooltip = "execute-a", - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - }); - - observer.OnNext(a); - observer.OnCompleted(); - }, + options.OnDocumentLink( + (documentLinkParams, observer, token) => { + var a = new DocumentLinkContainer( + new DocumentLink { + Tooltip = "execute-a", + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ); + + observer.OnNext(a); + observer.OnCompleted(); + }, (documentLink, token) => { documentLink.Data.Id.Should().NotBeEmpty(); documentLink.Data.Child.Should().NotBeNull(); @@ -258,10 +290,10 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() documentLink.Tooltip = "resolved"; return Task.FromResult(documentLink); }, - - new DocumentLinkRegistrationOptions() { - }); - }); + new DocumentLinkRegistrationOptions() + ); + } + ); var item = await client.RequestDocumentLink(new DocumentLinkParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -272,32 +304,36 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() [Fact] public async Task Should_Resolve_With_Data() { - var (client, server) = await Initialize( options => { }, options => { - options.OnDocumentLink((documentLinkParams) => { - return Task.FromResult(new DocumentLinkContainer(new DocumentLink() { - Tooltip = "execute-a", - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - })); - }, - (documentLink) => { + options.OnDocumentLink( + documentLinkParams => { + return Task.FromResult( + new DocumentLinkContainer( + new DocumentLink { + Tooltip = "execute-a", + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ) + ); + }, + documentLink => { documentLink.Data.Id.Should().NotBeEmpty(); documentLink.Data.Child.Should().NotBeNull(); documentLink.Data.Name.Should().Be("name"); documentLink.Tooltip = "resolved"; return Task.FromResult(documentLink); }, - - new DocumentLinkRegistrationOptions() { - }); - }); + new DocumentLinkRegistrationOptions() + ); + } + ); var items = await client.RequestDocumentLink(new DocumentLinkParams()); @@ -310,35 +346,37 @@ public async Task Should_Resolve_With_Data() [Fact] public async Task Should_Resolve_With_Partial_Data() { - var (client, server) = await Initialize( options => { }, options => { - options.OnDocumentLink((documentLinkParams, observer) => { - var a = new DocumentLinkContainer(new DocumentLink() { - Tooltip = "execute-a", - Data = new Data() { - Child = new Nested() { - Date = DateTimeOffset.MinValue - }, - Id = Guid.NewGuid(), - Name = "name" - } - }); - - observer.OnNext(a); - observer.OnCompleted(); - }, - (documentLink) => { + options.OnDocumentLink( + (documentLinkParams, observer) => { + var a = new DocumentLinkContainer( + new DocumentLink { + Tooltip = "execute-a", + Data = new Data { + Child = new Nested { + Date = DateTimeOffset.MinValue + }, + Id = Guid.NewGuid(), + Name = "name" + } + } + ); + + observer.OnNext(a); + observer.OnCompleted(); + }, + documentLink => { documentLink.Data.Id.Should().NotBeEmpty(); documentLink.Data.Child.Should().NotBeNull(); documentLink.Data.Name.Should().Be("name"); documentLink.Tooltip = "resolved"; return Task.FromResult(documentLink); }, - - new DocumentLinkRegistrationOptions() { - }); - }); + new DocumentLinkRegistrationOptions() + ); + } + ); var item = await client.RequestDocumentLink(new DocumentLinkParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -350,21 +388,26 @@ public async Task Should_Resolve_With_Partial_Data() [Fact] public async Task Should_Resolve_Capability() { - var (client, server) = await Initialize( options => { }, options => { - options.OnDocumentLink((documentLinkParams, capability, token) => { - return Task.FromResult(new DocumentLinkContainer(new DocumentLink() { - Tooltip = "execute-a", - })); - }, + options.OnDocumentLink( + (documentLinkParams, capability, token) => { + return Task.FromResult( + new DocumentLinkContainer( + new DocumentLink { + Tooltip = "execute-a", + } + ) + ); + }, (documentLink, capability, token) => { documentLink.Tooltip = "resolved"; return Task.FromResult(documentLink); }, - new DocumentLinkRegistrationOptions() { - }); - }); + new DocumentLinkRegistrationOptions() + ); + } + ); var items = await client.RequestDocumentLink(new DocumentLinkParams()); @@ -377,25 +420,27 @@ public async Task Should_Resolve_Capability() [Fact] public async Task Should_Resolve_Partial_Capability() { - var (client, server) = await Initialize( options => { }, options => { - options.OnDocumentLink((documentLinkParams, observer, capability, token) => { - var a = new DocumentLinkContainer(new DocumentLink() { - Tooltip = "execute-a", - }); - - observer.OnNext(a); - observer.OnCompleted(); - }, + options.OnDocumentLink( + (documentLinkParams, observer, capability, token) => { + var a = new DocumentLinkContainer( + new DocumentLink { + Tooltip = "execute-a", + } + ); + observer.OnNext(a); + observer.OnCompleted(); + }, (documentLink, capability, token) => { documentLink.Tooltip = "resolved"; return Task.FromResult(documentLink); }, - new DocumentLinkRegistrationOptions() { - }); - }); + new DocumentLinkRegistrationOptions() + ); + } + ); var item = await client.RequestDocumentLink(new DocumentLinkParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -406,22 +451,26 @@ public async Task Should_Resolve_Partial_Capability() [Fact] public async Task Should_Resolve_CancellationToken() { - var (client, server) = await Initialize( options => { }, options => { - options.OnDocumentLink((documentLinkParams, token) => { - return Task.FromResult(new DocumentLinkContainer(new DocumentLink() { - Tooltip = "execute-a", - })); - }, + options.OnDocumentLink( + (documentLinkParams, token) => { + return Task.FromResult( + new DocumentLinkContainer( + new DocumentLink { + Tooltip = "execute-a", + } + ) + ); + }, (documentLink, token) => { documentLink.Tooltip = "resolved"; return Task.FromResult(documentLink); }, - - new DocumentLinkRegistrationOptions() { - }); - }); + new DocumentLinkRegistrationOptions() + ); + } + ); var items = await client.RequestDocumentLink(new DocumentLinkParams()); @@ -434,25 +483,27 @@ public async Task Should_Resolve_CancellationToken() [Fact] public async Task Should_Resolve_Partial_CancellationToken() { - var (client, server) = await Initialize( options => { }, options => { - options.OnDocumentLink((documentLinkParams, observer, token) => { - var a = new DocumentLinkContainer(new DocumentLink() { - Tooltip = "execute-a", - }); - - observer.OnNext(a); - observer.OnCompleted(); - }, + options.OnDocumentLink( + (documentLinkParams, observer, token) => { + var a = new DocumentLinkContainer( + new DocumentLink { + Tooltip = "execute-a", + } + ); + + observer.OnNext(a); + observer.OnCompleted(); + }, (documentLink, token) => { documentLink.Tooltip = "resolved"; return Task.FromResult(documentLink); }, - - new DocumentLinkRegistrationOptions() { - }); - }); + new DocumentLinkRegistrationOptions() + ); + } + ); var item = await client.RequestDocumentLink(new DocumentLinkParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -463,22 +514,26 @@ public async Task Should_Resolve_Partial_CancellationToken() [Fact] public async Task Should_Resolve() { - var (client, server) = await Initialize( options => { }, options => { - options.OnDocumentLink((documentLinkParams) => { - return Task.FromResult(new DocumentLinkContainer(new DocumentLink() { - Tooltip = "execute-a", - })); - }, - (documentLink) => { + options.OnDocumentLink( + documentLinkParams => { + return Task.FromResult( + new DocumentLinkContainer( + new DocumentLink { + Tooltip = "execute-a", + } + ) + ); + }, + documentLink => { documentLink.Tooltip = "resolved"; return Task.FromResult(documentLink); }, - - new DocumentLinkRegistrationOptions() { - }); - }); + new DocumentLinkRegistrationOptions() + ); + } + ); var items = await client.RequestDocumentLink(new DocumentLinkParams()); @@ -491,25 +546,27 @@ public async Task Should_Resolve() [Fact] public async Task Should_Resolve_Partial() { - var (client, server) = await Initialize( options => { }, options => { - options.OnDocumentLink((documentLinkParams, observer) => { - var a = new DocumentLinkContainer(new DocumentLink() { - Tooltip = "execute-a", - }); - - observer.OnNext(a); - observer.OnCompleted(); - }, - (documentLink) => { + options.OnDocumentLink( + (documentLinkParams, observer) => { + var a = new DocumentLinkContainer( + new DocumentLink { + Tooltip = "execute-a", + } + ); + + observer.OnNext(a); + observer.OnCompleted(); + }, + documentLink => { documentLink.Tooltip = "resolved"; return Task.FromResult(documentLink); }, - - new DocumentLinkRegistrationOptions() { - }); - }); + new DocumentLinkRegistrationOptions() + ); + } + ); var item = await client.RequestDocumentLink(new DocumentLinkParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); @@ -517,15 +574,14 @@ public async Task Should_Resolve_Partial() item.Tooltip.Should().Be("resolved"); } - class Data : HandlerIdentity + private class Data : HandlerIdentity { public string Name { get; set; } public Guid Id { get; set; } public Nested Child { get; set; } - } - class Nested : HandlerIdentity + private class Nested : HandlerIdentity { public DateTimeOffset Date { get; set; } } diff --git a/test/Lsp.Tests/Integration/WorkspaceFolderTests.cs b/test/Lsp.Tests/Integration/WorkspaceFolderTests.cs index cebfdc997..f9c7f9564 100644 --- a/test/Lsp.Tests/Integration/WorkspaceFolderTests.cs +++ b/test/Lsp.Tests/Integration/WorkspaceFolderTests.cs @@ -5,18 +5,12 @@ using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using FluentAssertions; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Reactive.Testing; -using Newtonsoft.Json; using NSubstitute; 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.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Window; using OmniSharp.Extensions.LanguageServer.Server; using Serilog.Events; using Xunit; @@ -26,10 +20,11 @@ namespace Lsp.Tests.Integration { public class WorkspaceFolderTests : LanguageProtocolTestBase { - public WorkspaceFolderTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions() - .ConfigureForXUnit(outputHelper, LogEventLevel.Verbose) - .WithSettleTimeSpan(TimeSpan.FromSeconds(1)) - .WithSettleTimeout(TimeSpan.FromSeconds(2)) + public WorkspaceFolderTests(ITestOutputHelper outputHelper) : base( + new JsonRpcTestOptions() + .ConfigureForXUnit(outputHelper, LogEventLevel.Verbose) + .WithSettleTimeSpan(TimeSpan.FromSeconds(1)) + .WithSettleTimeout(TimeSpan.FromSeconds(2)) ) { } @@ -37,12 +32,12 @@ public WorkspaceFolderTests(ITestOutputHelper outputHelper) : base(new JsonRpcTe [Fact] public async Task Should_Disable_If_Not_Supported() { - var (client, server) = await Initialize(options => { - options.DisableAllCapabilities(); - options.OnInitialize(async (languageClient, request, token) => { - request.Capabilities.Workspace.WorkspaceFolders = false; - }); - }, ConfigureServer); + var (client, server) = await Initialize( + options => { + options.DisableAllCapabilities(); + options.OnInitialize(async (languageClient, request, token) => { request.Capabilities.Workspace.WorkspaceFolders = false; }); + }, ConfigureServer + ); server.WorkspaceFolderManager.IsSupported.Should().Be(false); var folders = await server.WorkspaceFolderManager.Refresh().ToArray().ToTask(); folders.Should().BeEmpty(); @@ -85,9 +80,7 @@ public async Task Should_Have_Workspace_Folder_At_Startup() [Fact(Skip = "Test fails periodically on CI but not locally")] 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)); @@ -108,9 +101,7 @@ public async Task Should_Remove_Workspace_Folder_by_name() [Fact(Skip = "Test fails periodically on CI but not locally")] 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)); @@ -128,14 +119,14 @@ public async Task Should_Remove_Workspace_Folder_by_uri() folders[0].Folder.Name.Should().Be(nameof(Should_Remove_Workspace_Folder_by_uri)); } - private void ConfigureClient(LanguageClientOptions options) - { - options.WithClientCapabilities(new ClientCapabilities() { - Workspace = new WorkspaceClientCapabilities() { - WorkspaceFolders = true + private void ConfigureClient(LanguageClientOptions options) => + options.WithClientCapabilities( + new ClientCapabilities { + Workspace = new WorkspaceClientCapabilities { + WorkspaceFolders = true + } } - }); - } + ); private void ConfigureServer(LanguageServerOptions options) { diff --git a/test/Lsp.Tests/JsonFixtureAttribute.cs b/test/Lsp.Tests/JsonFixtureAttribute.cs index 4b4e4003d..a95f88fc3 100644 --- a/test/Lsp.Tests/JsonFixtureAttribute.cs +++ b/test/Lsp.Tests/JsonFixtureAttribute.cs @@ -6,9 +6,10 @@ namespace Lsp.Tests { - class JsonFixtureAttribute : DataAttribute + internal class JsonFixtureAttribute : DataAttribute { public Assembly Resources = typeof(JsonFixtureAttribute).GetTypeInfo().Assembly; + public override IEnumerable GetData(MethodInfo testMethod) { var fileName = $"{testMethod.DeclaringType.FullName}_${testMethod.Name}.json"; diff --git a/test/Lsp.Tests/JsonRpcIntegrationTests.cs b/test/Lsp.Tests/JsonRpcIntegrationTests.cs index 31d3880f0..cf362e30e 100644 --- a/test/Lsp.Tests/JsonRpcIntegrationTests.cs +++ b/test/Lsp.Tests/JsonRpcIntegrationTests.cs @@ -245,3 +245,6 @@ // } // } // } + + + diff --git a/test/Lsp.Tests/JsonRpcTestContainer.cs b/test/Lsp.Tests/JsonRpcTestContainer.cs index 50891e2d1..47bdff36d 100644 --- a/test/Lsp.Tests/JsonRpcTestContainer.cs +++ b/test/Lsp.Tests/JsonRpcTestContainer.cs @@ -2,11 +2,9 @@ using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.JsonRpc.Serialization; -using Xunit.Abstractions; -using NSubstitute.Internals; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; +using Xunit.Abstractions; namespace JsonRpc.Tests { @@ -15,12 +13,13 @@ internal static class LspTestContainer public static IContainer Create(ITestOutputHelper testOutputHelper) { var container = JsonRpcServerContainer.Create(null) - .AddJsonRpcMediatR() - .With(rules => rules - .WithTestLoggerResolver((request, loggerType) => ActivatorUtilities.CreateInstance(request.Container, loggerType)) - .WithUndefinedTestDependenciesResolver(request => Substitute.For(new[] { request.ServiceType }, null)) - .WithConcreteTypeDynamicRegistrations((type, o) => true, Reuse.Transient) - ); + .AddJsonRpcMediatR() + .With( + rules => rules + .WithTestLoggerResolver((request, loggerType) => ActivatorUtilities.CreateInstance(request.Container, loggerType)) + .WithUndefinedTestDependenciesResolver(request => Substitute.For(new[] { request.ServiceType }, null)) + .WithConcreteTypeDynamicRegistrations((type, o) => true, Reuse.Transient) + ); container.RegisterInstanceMany(new Serializer(ClientVersion.Lsp3)); return container; } diff --git a/test/Lsp.Tests/LanguageClientServiceCollectionSupportTests.cs b/test/Lsp.Tests/LanguageClientServiceCollectionSupportTests.cs index 094031848..9de191bc1 100644 --- a/test/Lsp.Tests/LanguageClientServiceCollectionSupportTests.cs +++ b/test/Lsp.Tests/LanguageClientServiceCollectionSupportTests.cs @@ -18,10 +18,7 @@ public class LanguageClientServiceCollectionSupportTests { private readonly ITestOutputHelper _testOutputHelper; - public LanguageClientServiceCollectionSupportTests(ITestOutputHelper testOutputHelper) - { - _testOutputHelper = testOutputHelper; - } + public LanguageClientServiceCollectionSupportTests(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper; [Fact] public void Inner_Services_Should_Override_Outer_Services() @@ -29,17 +26,19 @@ public void Inner_Services_Should_Override_Outer_Services() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddLanguageClient(options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .WithServices(s => s.AddSingleton(new OutsideService("override"))) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddSingleton(new OutsideService("servername")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddLanguageClient( + options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .WithServices(s => s.AddSingleton(new OutsideService("override"))) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddSingleton(new OutsideService("servername")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); using var server = services.GetRequiredService(); server.GetRequiredService().Value.Should().Be("override"); @@ -51,18 +50,21 @@ public void Handlers_Can_Be_Added_From_The_Service_Collection() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddLanguageClient(options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .WithServices(services => - services.AddJsonRpcHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}) - ); - }) - .AddSingleton(new OutsideService("servername")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddLanguageClient( + options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .WithServices( + services => + services.AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + ); + } + ) + .AddSingleton(new OutsideService("servername")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); using var server = services.GetRequiredService(); server.HandlersManager.Descriptors.Should().Contain(z => z.Handler.GetType() == typeof(Handler)); @@ -74,23 +76,27 @@ public void Should_Bootstrap_Multiple_Servers_Through_Service_Collection() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddLanguageClient("serial", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddLanguageClient("parallel", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Parallel}); - }) - .AddSingleton(new OutsideService("outside")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddLanguageClient( + "serial", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddLanguageClient( + "parallel", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel }); + } + ) + .AddSingleton(new OutsideService("outside")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); var resolver = services.GetRequiredService(); var serialServer = resolver.Get("serial").Should().NotBeNull().And.Subject; @@ -108,65 +114,57 @@ public void Should_Throw_When_Multiple_Servers_Are_Added_And_Attempt_To_Resolve_ cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddLanguageClient("serial", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddLanguageClient("parallel", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Parallel}); - }) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddLanguageClient( + "serial", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddLanguageClient( + "parallel", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel }); + } + ) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); Action a = () => services.GetRequiredService(); a.Should().Throw(); } [Method("outside")] - class Request : IRequest + private class Request : IRequest { } - class Response + private class Response { public string Value { get; } - public Response(string value) - { - Value = value; - } + public Response(string value) => Value = value; } - class Handler : IJsonRpcRequestHandler + private class Handler : IJsonRpcRequestHandler { private readonly OutsideService _outsideService; - public Handler(OutsideService outsideService) - { - _outsideService = outsideService; - } + public Handler(OutsideService outsideService) => _outsideService = outsideService; - public Task Handle(Request request, CancellationToken cancellationToken) - { - return Task.FromResult(new Response(_outsideService.Value)); - } + public Task Handle(Request request, CancellationToken cancellationToken) => Task.FromResult(new Response(_outsideService.Value)); } - class OutsideService + private class OutsideService { - public OutsideService(string value) - { - Value = value; - } + public OutsideService(string value) => Value = value; public string Value { get; } } } -} \ No newline at end of file +} diff --git a/test/Lsp.Tests/LanguageServerServiceCollectionSupportTests.cs b/test/Lsp.Tests/LanguageServerServiceCollectionSupportTests.cs index aef08076e..ae46059a6 100644 --- a/test/Lsp.Tests/LanguageServerServiceCollectionSupportTests.cs +++ b/test/Lsp.Tests/LanguageServerServiceCollectionSupportTests.cs @@ -18,10 +18,7 @@ public class LanguageServerServiceCollectionSupportTests { private readonly ITestOutputHelper _testOutputHelper; - public LanguageServerServiceCollectionSupportTests(ITestOutputHelper testOutputHelper) - { - _testOutputHelper = testOutputHelper; - } + public LanguageServerServiceCollectionSupportTests(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper; [Fact] public void Inner_Services_Should_Override_Outer_Services() @@ -29,17 +26,19 @@ public void Inner_Services_Should_Override_Outer_Services() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddLanguageServer(options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .WithServices(s => s.AddSingleton(new OutsideService("override"))) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddSingleton(new OutsideService("servername")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddLanguageServer( + options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .WithServices(s => s.AddSingleton(new OutsideService("override"))) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddSingleton(new OutsideService("servername")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); using var server = services.GetRequiredService(); server.GetRequiredService().Value.Should().Be("override"); @@ -51,18 +50,21 @@ public void Handlers_Can_Be_Added_From_The_Service_Collection() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddLanguageServer(options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .WithServices(services => - services.AddJsonRpcHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}) - ); - }) - .AddSingleton(new OutsideService("servername")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddLanguageServer( + options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .WithServices( + services => + services.AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + ); + } + ) + .AddSingleton(new OutsideService("servername")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); using var server = services.GetRequiredService(); server.HandlersManager.Descriptors.Should().Contain(z => z.Handler.GetType() == typeof(Handler)); @@ -74,23 +76,27 @@ public void Should_Bootstrap_Multiple_Servers_Through_Service_Collection() var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddLanguageServer("serial", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddLanguageServer("parallel", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Parallel}); - }) - .AddSingleton(new OutsideService("outside")) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddLanguageServer( + "serial", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddLanguageServer( + "parallel", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel }); + } + ) + .AddSingleton(new OutsideService("outside")) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); var resolver = services.GetRequiredService(); var serialServer = resolver.Get("serial").Should().NotBeNull().And.Subject; @@ -108,63 +114,55 @@ public void Should_Throw_When_Multiple_Servers_Are_Added_And_Attempt_To_Resolve_ cts.CancelAfter(TimeSpan.FromSeconds(30)); var services = new ServiceCollection() - .AddLanguageServer("serial", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Serial}); - }) - .AddLanguageServer("parallel", options => { - var pipe = new Pipe(); - options - .WithInput(pipe.Reader) - .WithOutput(pipe.Writer) - .AddHandler(new JsonRpcHandlerOptions() {RequestProcessType = RequestProcessType.Parallel}); - }) - .AddSingleton(new TestLoggerFactory(_testOutputHelper)) - .BuildServiceProvider(); + .AddLanguageServer( + "serial", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }); + } + ) + .AddLanguageServer( + "parallel", options => { + var pipe = new Pipe(); + options + .WithInput(pipe.Reader) + .WithOutput(pipe.Writer) + .AddHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel }); + } + ) + .AddSingleton(new TestLoggerFactory(_testOutputHelper)) + .BuildServiceProvider(); Action a = () => services.GetRequiredService(); a.Should().Throw(); } [Method("outside")] - class Request : IRequest + private class Request : IRequest { } - class Response + private class Response { public string Value { get; } - public Response(string value) - { - Value = value; - } + public Response(string value) => Value = value; } - class Handler : IJsonRpcRequestHandler + private class Handler : IJsonRpcRequestHandler { private readonly OutsideService _outsideService; - public Handler(OutsideService outsideService) - { - _outsideService = outsideService; - } + public Handler(OutsideService outsideService) => _outsideService = outsideService; - public Task Handle(Request request, CancellationToken cancellationToken) - { - return Task.FromResult(new Response(_outsideService.Value)); - } + public Task Handle(Request request, CancellationToken cancellationToken) => Task.FromResult(new Response(_outsideService.Value)); } - class OutsideService + private class OutsideService { - public OutsideService(string value) - { - Value = value; - } + public OutsideService(string value) => Value = value; public string Value { get; } } diff --git a/test/Lsp.Tests/LspRequestRouterTests.cs b/test/Lsp.Tests/LspRequestRouterTests.cs index 3eb25e58b..8eb438b1b 100644 --- a/test/Lsp.Tests/LspRequestRouterTests.cs +++ b/test/Lsp.Tests/LspRequestRouterTests.cs @@ -2,41 +2,40 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using DryIoc; +using JsonRpc.Tests; using MediatR; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NSubstitute; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Server; using OmniSharp.Extensions.LanguageServer.Protocol; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Server.Matchers; -using Xunit; -using Xunit.Abstractions; -using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; -using Serializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Serializer; -using System.Reactive.Disposables; -using DryIoc; -using JsonRpc.Tests; -using Microsoft.Extensions.Logging; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.General; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; +using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server; using OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; +using OmniSharp.Extensions.LanguageServer.Server.Matchers; using OmniSharp.Extensions.LanguageServer.Shared; +using Xunit; +using Xunit.Abstractions; using Arg = NSubstitute.Arg; +using ISerializer = OmniSharp.Extensions.JsonRpc.ISerializer; using Request = OmniSharp.Extensions.JsonRpc.Server.Request; namespace Lsp.Tests { - public class TestLanguageServerRegistry : JsonRpcOptionsRegistryBase, ILanguageServerRegistry + public class TestLanguageServerRegistry : JsonRpcOptionsRegistryBase, ILanguageServerRegistry { internal List Handlers = new List(); - public OmniSharp.Extensions.JsonRpc.ISerializer Serializer => new Serializer(); + public ISerializer Serializer => new Serializer(); public ILanguageServerRegistry AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions options = null) { @@ -44,15 +43,9 @@ public ILanguageServerRegistry AddHandler(string method, IJsonRpcHandler handler return this; } - public ILanguageServerRegistry AddHandler(JsonRpcHandlerOptions options = null) where T : IJsonRpcHandler - { - return this; - } + public ILanguageServerRegistry AddHandler(JsonRpcHandlerOptions options = null) where T : IJsonRpcHandler => this; - public ILanguageServerRegistry AddHandler(string method, Func handlerFunc, JsonRpcHandlerOptions options = null) - { - return this; - } + public ILanguageServerRegistry AddHandler(string method, Func handlerFunc, JsonRpcHandlerOptions options = null) => this; public ILanguageServerRegistry AddHandlers(params IJsonRpcHandler[] handlers) { @@ -60,25 +53,21 @@ public ILanguageServerRegistry AddHandlers(params IJsonRpcHandler[] handlers) return this; } - public ILanguageServerRegistry AddTextDocumentIdentifier(params ITextDocumentIdentifier[] handlers) - { - return this; - } + public ILanguageServerRegistry AddTextDocumentIdentifier(params ITextDocumentIdentifier[] handlers) => this; - public ILanguageServerRegistry AddTextDocumentIdentifier() where T : ITextDocumentIdentifier - { - return this; - } + public ILanguageServerRegistry AddTextDocumentIdentifier() where T : ITextDocumentIdentifier => this; public ILanguageServerRegistry AddHandler(Func handlerFunc, JsonRpcHandlerOptions options = null) where T : IJsonRpcHandler { var sp = new ServiceCollection() - .AddSingleton(Substitute - .For>>()) - .AddSingleton(Substitute.For()) - .AddSingleton(Substitute.For>()) - .AddSingleton(new CodeActionRegistrationOptions()) - .BuildServiceProvider(); + .AddSingleton( + Substitute + .For>>() + ) + .AddSingleton(Substitute.For()) + .AddSingleton(Substitute.For>()) + .AddSingleton(new CodeActionRegistrationOptions()) + .BuildServiceProvider(); Handlers.Add(handlerFunc(sp)); return this; } @@ -89,7 +78,7 @@ public class LspRequestRouterTests : AutoTestBase public LspRequestRouterTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { Container = LspTestContainer.Create(testOutputHelper); - Registrator.RegisterMany(Container, nonPublicServiceTypes: true); + Container.RegisterMany(nonPublicServiceTypes: true); } [Fact] @@ -98,26 +87,28 @@ public async Task ShouldRouteToCorrect_Notification() var textDocumentSyncHandler = TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp"); textDocumentSyncHandler.Handle(Arg.Any(), Arg.Any()) - .Returns(Unit.Value); + .Returns(Unit.Value); var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()) - {textDocumentSyncHandler}; + { textDocumentSyncHandler }; AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var mediator = AutoSubstitute.Resolve(); - var @params = new DidSaveTextDocumentParams() { + var @params = new DidSaveTextDocumentParams { TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cs")) }; - var request = new Notification(TextDocumentNames.DidSave, - JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings))); + var request = new Notification( + TextDocumentNames.DidSave, + JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings)) + ); await mediator.RouteNotification(mediator.GetDescriptors(request), request, CancellationToken.None); await textDocumentSyncHandler.Received(1) - .Handle(Arg.Any(), Arg.Any()); + .Handle(Arg.Any(), Arg.Any()); } [Fact] @@ -128,33 +119,35 @@ public async Task ShouldRouteToCorrect_Notification_WithManyHandlers() var textDocumentSyncHandler2 = TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cake"), "csharp"); textDocumentSyncHandler.Handle(Arg.Any(), Arg.Any()) - .Returns(Unit.Value); + .Returns(Unit.Value); textDocumentSyncHandler2.Handle(Arg.Any(), Arg.Any()) - .Returns(Unit.Value); + .Returns(Unit.Value); var textDocumentIdentifiers = new TextDocumentIdentifiers(); AutoSubstitute.Provide(textDocumentIdentifiers); var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) - {textDocumentSyncHandler, textDocumentSyncHandler2}; + { textDocumentSyncHandler, textDocumentSyncHandler2 }; AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); AutoSubstitute.Provide(new TextDocumentMatcher(LoggerFactory.CreateLogger(), textDocumentIdentifiers)); var mediator = AutoSubstitute.Resolve(); - var @params = new DidSaveTextDocumentParams() { + var @params = new DidSaveTextDocumentParams { TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cake")) }; - var request = new Notification(TextDocumentNames.DidSave, - JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings))); + var request = new Notification( + TextDocumentNames.DidSave, + JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings)) + ); await mediator.RouteNotification(mediator.GetDescriptors(request), request, CancellationToken.None); await textDocumentSyncHandler.Received(0) - .Handle(Arg.Any(), Arg.Any()); + .Handle(Arg.Any(), Arg.Any()); await textDocumentSyncHandler2.Received(1) - .Handle(Arg.Any(), Arg.Any()); + .Handle(Arg.Any(), Arg.Any()); } [Fact] @@ -163,29 +156,30 @@ public async Task ShouldRouteToCorrect_Request() var textDocumentSyncHandler = TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp"); textDocumentSyncHandler.Handle(Arg.Any(), Arg.Any()) - .Returns(Unit.Value); + .Returns(Unit.Value); var codeActionHandler = Substitute.For(); - codeActionHandler.GetRegistrationOptions().Returns(new CodeActionRegistrationOptions() - {DocumentSelector = DocumentSelector.ForPattern("**/*.cs")}); + codeActionHandler.GetRegistrationOptions().Returns(new CodeActionRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") }); codeActionHandler - .Handle(Arg.Any(), Arg.Any()) - .Returns(new CommandOrCodeActionContainer()); + .Handle(Arg.Any(), Arg.Any()) + .Returns(new CommandOrCodeActionContainer()); var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()) - {textDocumentSyncHandler, codeActionHandler}; + { textDocumentSyncHandler, codeActionHandler }; AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var mediator = AutoSubstitute.Resolve(); var id = Guid.NewGuid().ToString(); - var @params = new DidSaveTextDocumentParams() { + var @params = new DidSaveTextDocumentParams { TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cs")) }; - var request = new Request(id, TextDocumentNames.CodeAction, - JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings))); + var request = new Request( + id, TextDocumentNames.CodeAction, + JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings)) + ); await mediator.RouteRequest(mediator.GetDescriptors(request), request, CancellationToken.None); @@ -200,32 +194,31 @@ public async Task ShouldRouteToCorrect_Request_WithManyHandlers() var textDocumentSyncHandler2 = TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cake"), "csharp"); textDocumentSyncHandler.Handle(Arg.Any(), Arg.Any()) - .Returns(Unit.Value); + .Returns(Unit.Value); textDocumentSyncHandler2.Handle(Arg.Any(), Arg.Any()) - .Returns(Unit.Value); + .Returns(Unit.Value); var codeActionHandler = Substitute.For(); - codeActionHandler.GetRegistrationOptions().Returns(new CodeActionRegistrationOptions() - {DocumentSelector = DocumentSelector.ForPattern("**/*.cs")}); + codeActionHandler.GetRegistrationOptions().Returns(new CodeActionRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") }); codeActionHandler - .Handle(Arg.Any(), Arg.Any()) - .Returns(new CommandOrCodeActionContainer()); + .Handle(Arg.Any(), Arg.Any()) + .Returns(new CommandOrCodeActionContainer()); var registry = new TestLanguageServerRegistry(); var codeActionDelegate = Substitute.For>>(); codeActionDelegate.Invoke(Arg.Any(), Arg.Any()) - .Returns(new CommandOrCodeActionContainer()); + .Returns(new CommandOrCodeActionContainer()); registry.OnCodeAction( codeActionDelegate, - new CodeActionRegistrationOptions() {DocumentSelector = DocumentSelector.ForPattern("**/*.cake")} + new CodeActionRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cake") } ); var textDocumentIdentifiers = new TextDocumentIdentifiers(); AutoSubstitute.Provide(textDocumentIdentifiers); var handlerCollection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) - {textDocumentSyncHandler, textDocumentSyncHandler2, codeActionHandler}; + { textDocumentSyncHandler, textDocumentSyncHandler2, codeActionHandler }; handlerCollection.Add(registry.Handlers); AutoSubstitute.Provide(handlerCollection); AutoSubstitute.Provide>(handlerCollection); @@ -233,12 +226,14 @@ public async Task ShouldRouteToCorrect_Request_WithManyHandlers() var mediator = AutoSubstitute.Resolve(); var id = Guid.NewGuid().ToString(); - var @params = new CodeActionParams() { + var @params = new CodeActionParams { TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cake")) }; - var request = new Request(id, TextDocumentNames.CodeAction, - JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings))); + var request = new Request( + id, TextDocumentNames.CodeAction, + JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings)) + ); await mediator.RouteRequest(mediator.GetDescriptors(request), request, CancellationToken.None); @@ -254,40 +249,40 @@ public async Task ShouldRouteToCorrect_Request_WithManyHandlers_CodeLensHandler( var textDocumentSyncHandler2 = TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cake"), "csharp"); textDocumentSyncHandler.Handle(Arg.Any(), Arg.Any()) - .Returns(Unit.Value); + .Returns(Unit.Value); textDocumentSyncHandler2.Handle(Arg.Any(), Arg.Any()) - .Returns(Unit.Value); + .Returns(Unit.Value); var codeActionHandler = Substitute.For(); - codeActionHandler.GetRegistrationOptions().Returns(new CodeLensRegistrationOptions() - {DocumentSelector = DocumentSelector.ForPattern("**/*.cs")}); + codeActionHandler.GetRegistrationOptions().Returns(new CodeLensRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") }); codeActionHandler - .Handle(Arg.Any(), Arg.Any()) - .Returns(new CodeLensContainer()); + .Handle(Arg.Any(), Arg.Any()) + .Returns(new CodeLensContainer()); var codeActionHandler2 = Substitute.For(); - codeActionHandler2.GetRegistrationOptions().Returns(new CodeLensRegistrationOptions() - {DocumentSelector = DocumentSelector.ForPattern("**/*.cake")}); + codeActionHandler2.GetRegistrationOptions().Returns(new CodeLensRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cake") }); codeActionHandler2 - .Handle(Arg.Any(), Arg.Any()) - .Returns(new CodeLensContainer()); + .Handle(Arg.Any(), Arg.Any()) + .Returns(new CodeLensContainer()); var tdi = new TextDocumentIdentifiers(); var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, tdi, new ServiceCollection().BuildServiceProvider()) - {textDocumentSyncHandler, textDocumentSyncHandler2, codeActionHandler, codeActionHandler2}; + { textDocumentSyncHandler, textDocumentSyncHandler2, codeActionHandler, codeActionHandler2 }; AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); AutoSubstitute.Provide(new TextDocumentMatcher(LoggerFactory.CreateLogger(), tdi)); var mediator = AutoSubstitute.Resolve(); var id = Guid.NewGuid().ToString(); - var @params = new CodeLensParams() { + var @params = new CodeLensParams { TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cs")) }; - var request = new Request(id, TextDocumentNames.CodeLens, - JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings))); + var request = new Request( + id, TextDocumentNames.CodeLens, + JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings)) + ); await mediator.RouteRequest(mediator.GetDescriptors(request), request, CancellationToken.None); @@ -300,12 +295,12 @@ public async Task ShouldRouteTo_CorrectRequestWhenGivenNullParams() { var handler = Substitute.For(); handler - .Handle(Arg.Any(), Arg.Any()) - .Returns(Unit.Value); + .Handle(Arg.Any(), Arg.Any()) + .Returns(Unit.Value); var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()) - {handler}; + { handler }; AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var mediator = AutoSubstitute.Resolve(); diff --git a/test/Lsp.Tests/Matchers/ExecuteCommandHandlerMatcherTests.cs b/test/Lsp.Tests/Matchers/ExecuteCommandHandlerMatcherTests.cs index 13ded6b42..a8dbc49ec 100644 --- a/test/Lsp.Tests/Matchers/ExecuteCommandHandlerMatcherTests.cs +++ b/test/Lsp.Tests/Matchers/ExecuteCommandHandlerMatcherTests.cs @@ -52,15 +52,16 @@ public void Should_Return_Handler_Descriptor() // Given var handlerMatcher = AutoSubstitute.Resolve(); var executeCommandHandler = Substitute.For().With(new Container("Command")); - var registrationsOptions = new ExecuteCommandRegistrationOptions() - { + var registrationsOptions = new ExecuteCommandRegistrationOptions { Commands = new Container("Command") }; // When - var result = handlerMatcher.FindHandler(new ExecuteCommandParams { Command = "Command" }, + var result = handlerMatcher.FindHandler( + new ExecuteCommandParams { Command = "Command" }, new List { - new LspHandlerDescriptor("workspace/executeCommand", + new LspHandlerDescriptor( + "workspace/executeCommand", "Key", executeCommandHandler, executeCommandHandler.GetType(), @@ -71,8 +72,10 @@ public void Should_Return_Handler_Descriptor() typeof(ExecuteCommandCapability), null, () => { }, - Substitute.For()) - }); + Substitute.For() + ) + } + ); // Then result.Should().NotBeNullOrEmpty(); diff --git a/test/Lsp.Tests/Matchers/ResolveCommandMatcherTests.cs b/test/Lsp.Tests/Matchers/ResolveCommandMatcherTests.cs index be7cfafd4..03c6b3918 100644 --- a/test/Lsp.Tests/Matchers/ResolveCommandMatcherTests.cs +++ b/test/Lsp.Tests/Matchers/ResolveCommandMatcherTests.cs @@ -8,9 +8,9 @@ using Newtonsoft.Json.Linq; using NSubstitute; using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Document; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; using OmniSharp.Extensions.LanguageServer.Server.Matchers; using OmniSharp.Extensions.LanguageServer.Server.Pipelines; @@ -23,6 +23,7 @@ public class ResolveCommandMatcherTests : AutoTestBase { private readonly Guid TrueId = Guid.NewGuid(); private readonly Guid FalseId = Guid.NewGuid(); + public ResolveCommandMatcherTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } @@ -72,10 +73,12 @@ public void Should_Not_Throw_Given_Another_Descriptor() null, null, () => { }, - Substitute.For()); + Substitute.For() + ); var handlerMatcher = new ResolveCommandPipeline( - new RequestContext() {Descriptor = handlerDescriptor}, - LoggerFactory.CreateLogger>()); + new RequestContext { Descriptor = handlerDescriptor }, + LoggerFactory.CreateLogger>() + ); // When Func a = async () => await handlerMatcher.Handle(new CodeLensParams(), CancellationToken.None, () => Task.FromResult(new CodeLensContainer())); @@ -87,42 +90,48 @@ public void Should_Return_CodeLensResolve_Descriptor() { // Given var handlerMatcher = AutoSubstitute.Resolve(); - var resolveHandler = Substitute.For(new [] { typeof(ICodeLensResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()) as ICodeLensResolveHandler; - var resolveHandler2 = Substitute.For(new [] { typeof(ICodeLensResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()) as ICodeLensResolveHandler; - ((ICanBeIdentifiedHandler)resolveHandler)?.Id.Returns(FalseId); - ((ICanBeIdentifiedHandler)resolveHandler2)?.Id.Returns(TrueId); + var resolveHandler = Substitute.For(new[] { typeof(ICodeLensResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()) as ICodeLensResolveHandler; + var resolveHandler2 = Substitute.For(new[] { typeof(ICodeLensResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()) as ICodeLensResolveHandler; + ( (ICanBeIdentifiedHandler) resolveHandler )?.Id.Returns(FalseId); + ( (ICanBeIdentifiedHandler) resolveHandler2 )?.Id.Returns(TrueId); // When - var result = handlerMatcher.FindHandler(new CodeLens() { - Data = JObject.FromObject(new Dictionary() { [Constants.PrivateHandlerId] = TrueId, ["a"] = 1}) - }, - new List { - new LspHandlerDescriptor(TextDocumentNames.CodeLensResolve, - "Key", - resolveHandler, - resolveHandler.GetType(), - typeof(CodeLens), - null, - null, - () => false, - null, - null, - () => { }, - Substitute.For()), - new LspHandlerDescriptor(TextDocumentNames.CodeLensResolve, - "Key2", - resolveHandler2, - typeof(ICodeLensResolveHandler), - typeof(CodeLens), - null, - null, - () => false, - null, - null, - () => { }, - Substitute.For()), - }) - .ToArray(); + var result = handlerMatcher.FindHandler( + new CodeLens { + Data = JObject.FromObject(new Dictionary { [Constants.PrivateHandlerId] = TrueId, ["a"] = 1 }) + }, + new List { + new LspHandlerDescriptor( + TextDocumentNames.CodeLensResolve, + "Key", + resolveHandler, + resolveHandler.GetType(), + typeof(CodeLens), + null, + null, + () => false, + null, + null, + () => { }, + Substitute.For() + ), + new LspHandlerDescriptor( + TextDocumentNames.CodeLensResolve, + "Key2", + resolveHandler2, + typeof(ICodeLensResolveHandler), + typeof(CodeLens), + null, + null, + () => false, + null, + null, + () => { }, + Substitute.For() + ), + } + ) + .ToArray(); // Then result.Should().NotBeNullOrEmpty(); @@ -137,22 +146,26 @@ public void Should_Handle_Null_Data() var resolveHandler = Substitute.For(); // When - var result = handlerMatcher.FindHandler(new CompletionItem() { }, - new List { - new LspHandlerDescriptor(TextDocumentNames.CompletionResolve, - "Key", - resolveHandler, - resolveHandler.GetType(), - typeof(CompletionItem), - null, - null, - () => false, - null, - null, - () => { }, - Substitute.For()), - }) - .ToArray(); + var result = handlerMatcher.FindHandler( + new CompletionItem(), + new List { + new LspHandlerDescriptor( + TextDocumentNames.CompletionResolve, + "Key", + resolveHandler, + resolveHandler.GetType(), + typeof(CompletionItem), + null, + null, + () => false, + null, + null, + () => { }, + Substitute.For() + ), + } + ) + .ToArray(); // Then result.Should().BeNullOrEmpty(); @@ -163,42 +176,48 @@ public void Should_Return_CompletionResolve_Descriptor() { // Given var handlerMatcher = AutoSubstitute.Resolve(); - var resolveHandler = Substitute.For(new [] { typeof(ICompletionResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()) as ICompletionResolveHandler; - var resolveHandler2 = Substitute.For(new [] { typeof(ICompletionResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()) as ICompletionResolveHandler; - ((ICanBeIdentifiedHandler)resolveHandler)?.Id.Returns(FalseId); - ((ICanBeIdentifiedHandler)resolveHandler2)?.Id.Returns(TrueId); + var resolveHandler = Substitute.For(new[] { typeof(ICompletionResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()) as ICompletionResolveHandler; + var resolveHandler2 = Substitute.For(new[] { typeof(ICompletionResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()) as ICompletionResolveHandler; + ( (ICanBeIdentifiedHandler) resolveHandler )?.Id.Returns(FalseId); + ( (ICanBeIdentifiedHandler) resolveHandler2 )?.Id.Returns(TrueId); // When - var result = handlerMatcher.FindHandler(new CompletionItem() { - Data = JObject.FromObject(new Dictionary() { [Constants.PrivateHandlerId] = TrueId, ["a"] = 1}) - }, - new List { - new LspHandlerDescriptor(TextDocumentNames.CompletionResolve, - "Key", - resolveHandler, - resolveHandler.GetType(), - typeof(CompletionItem), - null, - null, - () => false, - null, - null, - () => { }, - Substitute.For()), - new LspHandlerDescriptor(TextDocumentNames.CompletionResolve, - "Key2", - resolveHandler2, - typeof(ICompletionResolveHandler), - typeof(CompletionItem), - null, - null, - () => false, - null, - null, - () => { }, - Substitute.For()), - }) - .ToArray(); + var result = handlerMatcher.FindHandler( + new CompletionItem { + Data = JObject.FromObject(new Dictionary { [Constants.PrivateHandlerId] = TrueId, ["a"] = 1 }) + }, + new List { + new LspHandlerDescriptor( + TextDocumentNames.CompletionResolve, + "Key", + resolveHandler, + resolveHandler.GetType(), + typeof(CompletionItem), + null, + null, + () => false, + null, + null, + () => { }, + Substitute.For() + ), + new LspHandlerDescriptor( + TextDocumentNames.CompletionResolve, + "Key2", + resolveHandler2, + typeof(ICompletionResolveHandler), + typeof(CompletionItem), + null, + null, + () => false, + null, + null, + () => { }, + Substitute.For() + ), + } + ) + .ToArray(); // Then result.Should().NotBeNullOrEmpty(); @@ -209,12 +228,14 @@ public void Should_Return_CompletionResolve_Descriptor() public async Task Should_Update_CompletionItems_With_HandlerType() { // Given - var resolveHandler = Substitute.For(new Type[] { - typeof(ICompletionHandler), - typeof(ICompletionResolveHandler), - typeof(ICanBeIdentifiedHandler) - }, new object[0]); - (resolveHandler as ICanBeIdentifiedHandler)?.Id.Returns(TrueId); + var resolveHandler = Substitute.For( + new[] { + typeof(ICompletionHandler), + typeof(ICompletionResolveHandler), + typeof(ICanBeIdentifiedHandler) + }, new object[0] + ); + ( resolveHandler as ICanBeIdentifiedHandler )?.Id.Returns(TrueId); var descriptor = new LspHandlerDescriptor( TextDocumentNames.Completion, "Key", @@ -227,25 +248,27 @@ public async Task Should_Update_CompletionItems_With_HandlerType() null, null, () => { }, - Substitute.For()); + Substitute.For() + ); var handlerMatcher = new ResolveCommandPipeline( - new RequestContext() {Descriptor = descriptor}, - Substitute.For>>()); + new RequestContext { Descriptor = descriptor }, + Substitute.For>>() + ); - var item = new CompletionItem() { - Data = JObject.FromObject(new {hello = "world"}) + var item = new CompletionItem { + Data = JObject.FromObject(new { hello = "world" }) }; - var list = new CompletionList(new[] {item}); + var list = new CompletionList(item); - (list is IEnumerable).Should().BeTrue(); + ( list is IEnumerable ).Should().BeTrue(); // When var response = await handlerMatcher.Handle(new CompletionParams(), CancellationToken.None, () => Task.FromResult(list)); // Then response.Should().BeEquivalentTo(list); - (response as CompletionList).Items.Should().Contain(item); - var responseItem = (response as CompletionList).Items.First(); + response.Items.Should().Contain(item); + var responseItem = response.Items.First(); responseItem.Data[Constants.PrivateHandlerId].Value().Should().Be(TrueId); responseItem.Data["hello"].Value().Should().Be("world"); } @@ -254,12 +277,14 @@ public async Task Should_Update_CompletionItems_With_HandlerType() public async Task Should_Update_CodeLensContainer_With_HandlerType() { // Given - var resolveHandler = Substitute.For(new Type[] { - typeof(ICodeLensHandler), - typeof(ICodeLensResolveHandler), - typeof(ICanBeIdentifiedHandler) - }, new object[0]); - (resolveHandler as ICanBeIdentifiedHandler)?.Id.Returns(TrueId); + var resolveHandler = Substitute.For( + new[] { + typeof(ICodeLensHandler), + typeof(ICodeLensResolveHandler), + typeof(ICanBeIdentifiedHandler) + }, new object[0] + ); + ( resolveHandler as ICanBeIdentifiedHandler )?.Id.Returns(TrueId); var descriptor = new LspHandlerDescriptor( TextDocumentNames.CodeLens, "Key", @@ -272,25 +297,27 @@ public async Task Should_Update_CodeLensContainer_With_HandlerType() null, null, () => { }, - Substitute.For()); + Substitute.For() + ); var handlerMatcher = new ResolveCommandPipeline( - new RequestContext() {Descriptor = descriptor}, - Substitute.For>>()); + new RequestContext { Descriptor = descriptor }, + Substitute.For>>() + ); - var item = new CodeLens() { - Data = JObject.FromObject(new {hello = "world"}) + var item = new CodeLens { + Data = JObject.FromObject(new { hello = "world" }) }; - var list = new CodeLensContainer(new[] {item}); + var list = new CodeLensContainer(item); - (list is IEnumerable).Should().BeTrue(); + ( list is IEnumerable ).Should().BeTrue(); // When var response = await handlerMatcher.Handle(new CodeLensParams(), CancellationToken.None, () => Task.FromResult(list)); // Then response.Should().BeEquivalentTo(list); - (response as CodeLensContainer).Should().Contain(item); - var responseItem = (response as CodeLensContainer).First(); + response.Should().Contain(item); + var responseItem = response.First(); responseItem.Data[Constants.PrivateHandlerId].Value().Should().Be(TrueId); responseItem.Data["hello"].Value().Should().Be("world"); } @@ -299,12 +326,14 @@ public async Task Should_Update_CodeLensContainer_With_HandlerType() public async Task Should_Update_CodeLens_Removing_HandlerType() { // Given - var resolveHandler = Substitute.For(new Type[] { - typeof(ICodeLensHandler), - typeof(ICodeLensResolveHandler), - typeof(ICanBeIdentifiedHandler) - }, new object[0]); - (resolveHandler as ICanBeIdentifiedHandler)?.Id.Returns(TrueId); + var resolveHandler = Substitute.For( + new[] { + typeof(ICodeLensHandler), + typeof(ICodeLensResolveHandler), + typeof(ICanBeIdentifiedHandler) + }, new object[0] + ); + ( resolveHandler as ICanBeIdentifiedHandler )?.Id.Returns(TrueId); var descriptor = new LspHandlerDescriptor( TextDocumentNames.CodeLensResolve, "Key", @@ -317,13 +346,15 @@ public async Task Should_Update_CodeLens_Removing_HandlerType() null, null, () => { }, - Substitute.For()); + Substitute.For() + ); var handlerMatcher = new ResolveCommandPipeline( - new RequestContext() {Descriptor = descriptor}, - Substitute.For>>()); + new RequestContext { Descriptor = descriptor }, + Substitute.For>>() + ); - var item = new CodeLens() { - Data = JObject.FromObject(new {hello = "world"}) + var item = new CodeLens { + Data = JObject.FromObject(new { hello = "world" }) }; item.Data[Constants.PrivateHandlerId] = Guid.Empty; diff --git a/test/Lsp.Tests/Matchers/TextDocumentMatcherTests.cs b/test/Lsp.Tests/Matchers/TextDocumentMatcherTests.cs index 24b90232d..fe6e6e447 100644 --- a/test/Lsp.Tests/Matchers/TextDocumentMatcherTests.cs +++ b/test/Lsp.Tests/Matchers/TextDocumentMatcherTests.cs @@ -4,12 +4,10 @@ using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using NSubstitute; -using OmniSharp.Extensions.JsonRpc; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Document; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; -using OmniSharp.Extensions.LanguageServer.Server; using OmniSharp.Extensions.LanguageServer.Server.Matchers; using OmniSharp.Extensions.LanguageServer.Shared; using Xunit; @@ -60,20 +58,21 @@ public void Should_Return_Did_Open_Text_Document_Handler_Descriptor() TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp"); var textDocumentIdentifiers = new TextDocumentIdentifiers(); AutoSubstitute.Provide(textDocumentIdentifiers); - var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) { textDocumentSyncHandler }; + var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) + { textDocumentSyncHandler }; AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var handlerMatcher = AutoSubstitute.Resolve(); // When - var result = handlerMatcher.FindHandler(new DidOpenTextDocumentParams() - { - TextDocument = new TextDocumentItem - { - Uri = new Uri("file:///abc/123/d.cs") - } - }, - collection.Where(x => x.Method == TextDocumentNames.DidOpen)); + var result = handlerMatcher.FindHandler( + new DidOpenTextDocumentParams { + TextDocument = new TextDocumentItem { + Uri = new Uri("file:///abc/123/d.cs") + } + }, + collection.Where(x => x.Method == TextDocumentNames.DidOpen) + ); // Then result.Should().NotBeNullOrEmpty(); @@ -88,20 +87,21 @@ public void Should_Return_Did_Open_Text_Document_Handler_Descriptor_With_Sepcial TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cshtml"), "csharp"); var textDocumentIdentifiers = new TextDocumentIdentifiers(); AutoSubstitute.Provide(textDocumentIdentifiers); - var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) { textDocumentSyncHandler }; + var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) + { textDocumentSyncHandler }; AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var handlerMatcher = AutoSubstitute.Resolve(); // When - var result = handlerMatcher.FindHandler(new DidOpenTextDocumentParams() - { - TextDocument = new TextDocumentItem - { - Uri = new Uri("file://c:/users/myøasdf/d.cshtml") - } - }, - collection.Where(x => x.Method == TextDocumentNames.DidOpen)); + var result = handlerMatcher.FindHandler( + new DidOpenTextDocumentParams { + TextDocument = new TextDocumentItem { + Uri = new Uri("file://c:/users/myøasdf/d.cshtml") + } + }, + collection.Where(x => x.Method == TextDocumentNames.DidOpen) + ); // Then result.Should().NotBeNullOrEmpty(); @@ -116,17 +116,19 @@ public void Should_Return_Did_Change_Text_Document_Descriptor() TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp"); var textDocumentIdentifiers = new TextDocumentIdentifiers(); AutoSubstitute.Provide(textDocumentIdentifiers); - var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) { textDocumentSyncHandler }; + var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) + { textDocumentSyncHandler }; AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var handlerMatcher = AutoSubstitute.Resolve(); // When - var result = handlerMatcher.FindHandler(new DidChangeTextDocumentParams() - { - TextDocument = new VersionedTextDocumentIdentifier { Uri = new Uri("file:///abc/123/d.cs"), Version = 1 } - }, - collection.Where(x => x.Method == TextDocumentNames.DidChange)); + var result = handlerMatcher.FindHandler( + new DidChangeTextDocumentParams { + TextDocument = new VersionedTextDocumentIdentifier { Uri = new Uri("file:///abc/123/d.cs"), Version = 1 } + }, + collection.Where(x => x.Method == TextDocumentNames.DidChange) + ); // Then result.Should().NotBeNullOrEmpty(); @@ -141,17 +143,19 @@ public void Should_Return_Did_Save_Text_Document_Descriptor() TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp"); var textDocumentIdentifiers = new TextDocumentIdentifiers(); AutoSubstitute.Provide(textDocumentIdentifiers); - var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) { textDocumentSyncHandler }; + var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) + { textDocumentSyncHandler }; AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var handlerMatcher = AutoSubstitute.Resolve(); // When - var result = handlerMatcher.FindHandler(new DidChangeTextDocumentParams() - { - TextDocument = new VersionedTextDocumentIdentifier { Uri = new Uri("file:///abc/123/d.cs"), Version = 1 } - }, - collection.Where(x => x.Method == TextDocumentNames.DidSave)); + var result = handlerMatcher.FindHandler( + new DidChangeTextDocumentParams { + TextDocument = new VersionedTextDocumentIdentifier { Uri = new Uri("file:///abc/123/d.cs"), Version = 1 } + }, + collection.Where(x => x.Method == TextDocumentNames.DidSave) + ); // Then result.Should().NotBeNullOrEmpty(); @@ -166,17 +170,19 @@ public void Should_Return_Did_Close_Text_Document_Descriptor() TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp"); var textDocumentIdentifiers = new TextDocumentIdentifiers(); AutoSubstitute.Provide(textDocumentIdentifiers); - var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) { textDocumentSyncHandler }; + var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) + { textDocumentSyncHandler }; AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var handlerMatcher = AutoSubstitute.Resolve(); // When - var result = handlerMatcher.FindHandler(new DidCloseTextDocumentParams() - { - TextDocument = new VersionedTextDocumentIdentifier { Uri = new Uri("file:///abc/123/d.cs"), Version = 1 } - }, - collection.Where(x => x.Method == TextDocumentNames.DidClose)); + var result = handlerMatcher.FindHandler( + new DidCloseTextDocumentParams { + TextDocument = new VersionedTextDocumentIdentifier { Uri = new Uri("file:///abc/123/d.cs"), Version = 1 } + }, + collection.Where(x => x.Method == TextDocumentNames.DidClose) + ); // Then result.Should().NotBeNullOrEmpty(); @@ -191,37 +197,41 @@ public void Should_Return_Code_Lens_Descriptor() TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp"); var textDocumentIdentifiers = new TextDocumentIdentifiers(); AutoSubstitute.Provide(textDocumentIdentifiers); - var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) { textDocumentSyncHandler }; + var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) + { textDocumentSyncHandler }; AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var handlerMatcher = AutoSubstitute.Resolve(); - var codeLensHandler = Substitute.For(new Type[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]) as ICodeLensHandler; + var codeLensHandler = Substitute.For(new[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]) as ICodeLensHandler; codeLensHandler.GetRegistrationOptions() - .Returns(new CodeLensRegistrationOptions() - { - DocumentSelector = new DocumentSelector(new DocumentFilter { Pattern = "**/*.cs" }) - }); + .Returns( + new CodeLensRegistrationOptions { + DocumentSelector = new DocumentSelector(new DocumentFilter { Pattern = "**/*.cs" }) + } + ); - var codeLensHandler2 = Substitute.For(new Type[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]) as ICodeLensHandler; + var codeLensHandler2 = Substitute.For(new[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]) as ICodeLensHandler; codeLensHandler2.GetRegistrationOptions() - .Returns(new CodeLensRegistrationOptions() - { - DocumentSelector = new DocumentSelector(new DocumentFilter { Pattern = "**/*.cake" }) - }); + .Returns( + new CodeLensRegistrationOptions { + DocumentSelector = new DocumentSelector(new DocumentFilter { Pattern = "**/*.cake" }) + } + ); collection.Add(codeLensHandler, codeLensHandler2); // When - var result = handlerMatcher.FindHandler(new CodeLensParams() - { - TextDocument = new VersionedTextDocumentIdentifier { Uri = new Uri("file:///abc/123/d.cs"), Version = 1 } - }, - collection.Where(x => x.Method == TextDocumentNames.CodeLens)); + var result = handlerMatcher.FindHandler( + new CodeLensParams { + TextDocument = new VersionedTextDocumentIdentifier { Uri = new Uri("file:///abc/123/d.cs"), Version = 1 } + }, + collection.Where(x => x.Method == TextDocumentNames.CodeLens) + ); // Then result.Should().NotBeNullOrEmpty(); result.Should().Contain(x => x.Method == TextDocumentNames.CodeLens); - result.Should().Contain(x => ((LspHandlerDescriptor)x).Key == "[**/*.cs]"); + result.Should().Contain(x => ( (LspHandlerDescriptor) x ).Key == "[**/*.cs]"); } } @@ -238,31 +248,32 @@ public void Should_Return_Did_Folding_Range_handler() var textDocumentSyncHandler = TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.ps*1"), "powershell"); var handler = Substitute.For(); - handler.GetRegistrationOptions().Returns(new FoldingRangeRegistrationOptions() - { - DocumentSelector = new DocumentSelector(new DocumentFilter() { Pattern = "**/*.ps*1" }) - }); + handler.GetRegistrationOptions().Returns( + new FoldingRangeRegistrationOptions { + DocumentSelector = new DocumentSelector(new DocumentFilter { Pattern = "**/*.ps*1" }) + } + ); var textDocumentIdentifiers = new TextDocumentIdentifiers(); AutoSubstitute.Provide(textDocumentIdentifiers); - var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) { textDocumentSyncHandler, handler }; + var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, new ServiceCollection().BuildServiceProvider()) + { textDocumentSyncHandler, handler }; AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var handlerMatcher = AutoSubstitute.Resolve(); // When - var result = handlerMatcher.FindHandler(new FoldingRangeRequestParam() - { - TextDocument = new TextDocumentItem - { - Uri = new Uri("file:///abc/123/d.ps1") - } - }, - collection.Where(x => x.Method == TextDocumentNames.DidOpen)); + var result = handlerMatcher.FindHandler( + new FoldingRangeRequestParam { + TextDocument = new TextDocumentItem { + Uri = new Uri("file:///abc/123/d.ps1") + } + }, + collection.Where(x => x.Method == TextDocumentNames.DidOpen) + ); // Then result.Should().NotBeNullOrEmpty(); result.Should().Contain(x => x.Method == TextDocumentNames.DidOpen); } - } } diff --git a/test/Lsp.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs b/test/Lsp.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs index 43af3a89b..806a98ebd 100644 --- a/test/Lsp.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs +++ b/test/Lsp.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs @@ -14,23 +14,19 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; +using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; +using OmniSharp.Extensions.LanguageServer.Shared; using Xunit; using Xunit.Abstractions; using Xunit.Sdk; -using OmniSharp.Extensions.LanguageServer.Shared; -using ISerializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.ISerializer; -using Serializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Serializer; using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; namespace Lsp.Tests { public class MediatorTestsRequestHandlerOfTRequestTResponse : AutoTestBase { - public MediatorTestsRequestHandlerOfTRequestTResponse(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - Container = LspTestContainer.Create(testOutputHelper); - } + public MediatorTestsRequestHandlerOfTRequestTResponse(ITestOutputHelper testOutputHelper) : base(testOutputHelper) => Container = LspTestContainer.Create(testOutputHelper); [Fact] public async Task RequestsCancellation() @@ -39,28 +35,28 @@ public async Task RequestsCancellation() textDocumentSyncHandler.Handle(Arg.Any(), Arg.Any()).Returns(Unit.Value); var codeActionHandler = Substitute.For(); - codeActionHandler.GetRegistrationOptions().Returns(new CodeActionRegistrationOptions() { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") }); + codeActionHandler.GetRegistrationOptions().Returns(new CodeActionRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") }); codeActionHandler - .Handle(Arg.Any(), Arg.Any()) - .Returns(async (c) => - { - await Task.Delay(1000, c.Arg()); - throw new XunitException("Task was not cancelled in time!"); - return new CommandOrCodeActionContainer(); - }); + .Handle(Arg.Any(), Arg.Any()) + .Returns( + async c => { + await Task.Delay(1000, c.Arg()); + throw new XunitException("Task was not cancelled in time!"); + return new CommandOrCodeActionContainer(); + } + ); - var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()) { textDocumentSyncHandler, codeActionHandler }; + var collection = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), new ServiceCollection().BuildServiceProvider()) + { textDocumentSyncHandler, codeActionHandler }; AutoSubstitute.Provide(collection); AutoSubstitute.Provide>(collection); var mediator = AutoSubstitute.Resolve(); var id = Guid.NewGuid().ToString(); - var @params = new CodeActionParams() - { + var @params = new CodeActionParams { TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cs")), Range = new Range(new Position(1, 1), new Position(2, 2)), - Context = new CodeActionContext() - { + Context = new CodeActionContext { Diagnostics = new Container() } }; @@ -69,8 +65,8 @@ public async Task RequestsCancellation() var cts = new CancellationTokenSource(); cts.Cancel(); - var response = ((IRequestRouter)mediator).RouteRequest(mediator.GetDescriptors(request), request, cts.Token); - Func action = () => ((IRequestRouter) mediator).RouteRequest(mediator.GetDescriptors(request), request, cts.Token); + var response = ( (IRequestRouter) mediator ).RouteRequest(mediator.GetDescriptors(request), request, cts.Token); + Func action = () => ( (IRequestRouter) mediator ).RouteRequest(mediator.GetDescriptors(request), request, cts.Token); await action.Should().ThrowAsync(); } } diff --git a/test/Lsp.Tests/Messages/ServerNotInitializedTests.cs b/test/Lsp.Tests/Messages/ServerNotInitializedTests.cs index 61a6eb536..e85ebb061 100644 --- a/test/Lsp.Tests/Messages/ServerNotInitializedTests.cs +++ b/test/Lsp.Tests/Messages/ServerNotInitializedTests.cs @@ -1,15 +1,16 @@ using FluentAssertions; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; +using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Server.Messages; -using Serializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Serializer; using Xunit; namespace Lsp.Tests.Messages { public class ServerNotInitializedTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new ServerNotInitialized(""); diff --git a/test/Lsp.Tests/Messages/UnknownErrorCodeTests.cs b/test/Lsp.Tests/Messages/UnknownErrorCodeTests.cs index ddd9beb6e..d273cb87b 100644 --- a/test/Lsp.Tests/Messages/UnknownErrorCodeTests.cs +++ b/test/Lsp.Tests/Messages/UnknownErrorCodeTests.cs @@ -1,15 +1,16 @@ using FluentAssertions; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; +using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Server.Messages; -using Serializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Serializer; using Xunit; namespace Lsp.Tests.Messages { public class UnknownErrorCodeTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new UnknownErrorCode(""); diff --git a/test/Lsp.Tests/Minimatch/BasicTests.cs b/test/Lsp.Tests/Minimatch/BasicTests.cs index b18e3b63a..ca4b5ec5e 100644 --- a/test/Lsp.Tests/Minimatch/BasicTests.cs +++ b/test/Lsp.Tests/Minimatch/BasicTests.cs @@ -33,9 +33,9 @@ namespace Minimatch.Tests { public class BasicTests { - static readonly List> actualRegexes = new List>(); + private static readonly List> actualRegexes = new List>(); - static void TestCase(string pattern, IList expected, Options options = null, IEnumerable input = null) + private static void TestCase(string pattern, IList expected, Options options = null, IEnumerable input = null) { input ??= files; @@ -45,30 +45,35 @@ static void TestCase(string pattern, IList expected, Options options = n ); var regex = Minimatcher.CreateRegex(pattern, options); - actualRegexes.Add(Tuple.Create(pattern, regex == null ? "false" : "/" + regex.ToString() + "/" + (regex.Options == RegexOptions.IgnoreCase ? "i" : ""))); + actualRegexes.Add(Tuple.Create(pattern, regex == null ? "false" : "/" + regex + "/" + ( regex.Options == RegexOptions.IgnoreCase ? "i" : "" ))); } - static void AssertRegexes(params string[] expectedRegexes) + private static void AssertRegexes(params string[] expectedRegexes) { Assert.Equal(expectedRegexes.Length, actualRegexes.Count); - for (int i = 0; i < actualRegexes.Count; i++) + for (var i = 0; i < actualRegexes.Count; i++) { Assert.Equal(expectedRegexes[i], actualRegexes[i].Item2); } } - static void AddFiles(params string[] entries) { files.AddRange(entries); } - static void ReplaceFiles(params string[] entries) { files.Clear(); files.AddRange(entries); } + private static void AddFiles(params string[] entries) => files.AddRange(entries); - static readonly List files = new List(); + private static void ReplaceFiles(params string[] entries) + { + files.Clear(); + files.AddRange(entries); + } + + private static readonly List files = new List(); public BasicTests() { ReplaceFiles( "a", "b", "c", "d", "abc" - , "abd", "abe", "bb", "bcd" - , "ca", "cb", "dd", "de" - , "bdir/", "bdir/cfile" + , "abd", "abe", "bb", "bcd" + , "ca", "cb", "dd", "de" + , "bdir/", "bdir/cfile" ); actualRegexes.Clear(); } @@ -76,7 +81,6 @@ public BasicTests() [Fact] public void BashCookBook() { - //"http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test" TestCase("a*", new[] { "a", "abc", "abd", "abe" }); TestCase("X*", new[] { "X*" }, new Options { NoNull = true }); @@ -112,25 +116,35 @@ public void BashCookBook() "/^(?:s\\/(?=.)\\.\\.[^/]*?\\/)$/" ); } + [Fact] public void LegendaryLarryCrashesBashes() { - TestCase("/^root:/{s/^[^:]*:[^:]*:([^:]*).*$/\\1/" - , new[] { "/^root:/{s/^[^:]*:[^:]*:([^:]*).*$/\\1/" }, new Options { NoNull = true }); - TestCase("/^root:/{s/^[^:]*:[^:]*:([^:]*).*$/\u0001/" - , new[] { "/^root:/{s/^[^:]*:[^:]*:([^:]*).*$/\u0001/" }, new Options { NoNull = true }); + TestCase( + "/^root:/{s/^[^:]*:[^:]*:([^:]*).*$/\\1/" + , new[] { "/^root:/{s/^[^:]*:[^:]*:([^:]*).*$/\\1/" }, new Options { NoNull = true } + ); + TestCase( + "/^root:/{s/^[^:]*:[^:]*:([^:]*).*$/\u0001/" + , new[] { "/^root:/{s/^[^:]*:[^:]*:([^:]*).*$/\u0001/" }, new Options { NoNull = true } + ); AssertRegexes( "/^(?:\\/\\^root:\\/\\{s\\/(?=.)\\^[^:][^/]*?:[^:][^/]*?:\\([^:]\\)[^/]*?\\.[^/]*?\\$\\/1\\/)$/", "/^(?:\\/\\^root:\\/\\{s\\/(?=.)\\^[^:][^/]*?:[^:][^/]*?:\\([^:]\\)[^/]*?\\.[^/]*?\\$\\/\u0001\\/)$/" ); } + [Fact] public void CharacterClasses() { TestCase("[a-c]b*", new[] { "abc", "abd", "abe", "bb", "cb" }); - TestCase("[a-y]*[^c]", new[] { "abd", "abe", "bb", "bcd", - "bdir/", "ca", "cb", "dd", "de" }); + TestCase( + "[a-y]*[^c]", new[] { + "abd", "abe", "bb", "bcd", + "bdir/", "ca", "cb", "dd", "de" + } + ); TestCase("a*[^c]", new[] { "abd", "abe" }); AddFiles("a-b", "aXb"); TestCase("a[X-]b", new[] { "a-b", "aXb" }); @@ -139,14 +153,14 @@ public void CharacterClasses() AddFiles("a*b/", "a*b/ooo"); TestCase("a\\*b/*", new[] { "a*b/ooo" }); TestCase("a\\*?/*", new[] { "a*b/ooo" }); - TestCase("*\\\\!*", new string[0], new Options { /*null = true*/ }, new[] { "echo !7" }); + TestCase("*\\\\!*", new string[0], new Options(), new[] { "echo !7" }); TestCase("*\\!*", new[] { "echo !7" }, null, new[] { "echo !7" }); TestCase("*.\\*", new[] { "r.*" }, null, new[] { "r.*" }); TestCase("a[b]c", new[] { "abc" }); TestCase("a[\\b]c", new[] { "abc" }); TestCase("a?c", new[] { "abc" }); - TestCase("a\\*c", new string[0], new Options { /*null = true*/ }, new[] { "abc" }); - TestCase("", new[] { "" }, new Options { /*null = true*/ }, new[] { "" }); + TestCase("a\\*c", new string[0], new Options(), new[] { "abc" }); + TestCase("", new[] { "" }, new Options(), new[] { "" }); AssertRegexes( "/^(?:(?!\\.)(?=.)[a-c]b[^/]*?)$/", @@ -166,6 +180,7 @@ public void CharacterClasses() "false" ); } + [Fact] public void AppleBash() { @@ -208,14 +223,14 @@ public void AppleBash() TestCase("[]]", new[] { "]" }, null, new[] { "]" }); TestCase("[]-]", new[] { "]" }, null, new[] { "]" }); TestCase(@"[a-\z]", new[] { "p" }, null, new[] { "p" }); - TestCase("??**********?****?", new string[0], new Options { /*null = true*/ }, new[] { "abc" }); - TestCase("??**********?****c", new string[0], new Options { /*null = true*/ }, new[] { "abc" }); - TestCase("?************c****?****", new string[0], new Options { /*null = true*/ }, new[] { "abc" }); - TestCase("*c*?**", new string[0], new Options { /*null = true*/ }, new[] { "abc" }); - TestCase("a*****c*?**", new string[0], new Options { /*null = true*/ }, new[] { "abc" }); - TestCase("a********???*******", new string[0], new Options { /*null = true*/ }, new[] { "abc" }); - TestCase("[]", new string[0], new Options { /*null = true*/ }, new[] { "a" }); - TestCase("[abc", new string[0], new Options { /*null = true*/ }, new[] { "[" }); + TestCase("??**********?****?", new string[0], new Options(), new[] { "abc" }); + TestCase("??**********?****c", new string[0], new Options(), new[] { "abc" }); + TestCase("?************c****?****", new string[0], new Options(), new[] { "abc" }); + TestCase("*c*?**", new string[0], new Options(), new[] { "abc" }); + TestCase("a*****c*?**", new string[0], new Options(), new[] { "abc" }); + TestCase("a********???*******", new string[0], new Options(), new[] { "abc" }); + TestCase("[]", new string[0], new Options(), new[] { "a" }); + TestCase("[abc", new string[0], new Options(), new[] { "[" }); AssertRegexes( "/^(?:(?!\\.)(?=.)[^/]*?\\/(?=.)man[^/]*?\\/(?=.)bash\\.[^/]*?)$/", @@ -256,18 +271,25 @@ public void AppleBash() "/^(?:\\[abc)$/" ); } + [Fact] public void NoCase() { AddFiles("a-b", "aXb", ".x", ".y", "a*b/", "a*b/ooo", "man/", "man/man1/", "man/man1/bash.1"); - TestCase("XYZ", new[] { "xYz" }, new Options { NoCase = true, /*null = true*/ } - , new[] { "xYz", "ABC", "IjK" }); - TestCase("ab*", new[] { "ABC" }, new Options { NoCase = true, /*null = true*/ } - , new[] { "xYz", "ABC", "IjK" }); - TestCase("[ia]?[ck]", new[] { "ABC", "IjK" }, new Options { NoCase = true, /*null = true*/ } - , new[] { "xYz", "ABC", "IjK" }); + TestCase( + "XYZ", new[] { "xYz" }, new Options { NoCase = true, /*null = true*/ } + , new[] { "xYz", "ABC", "IjK" } + ); + TestCase( + "ab*", new[] { "ABC" }, new Options { NoCase = true, /*null = true*/ } + , new[] { "xYz", "ABC", "IjK" } + ); + TestCase( + "[ia]?[ck]", new[] { "ABC", "IjK" }, new Options { NoCase = true, /*null = true*/ } + , new[] { "xYz", "ABC", "IjK" } + ); AssertRegexes( @@ -276,28 +298,29 @@ public void NoCase() "/^(?:(?!\\.)(?=.)[ia][^/][ck])$/i" ); } + [Fact] public void OneStar_TwoStar() { AddFiles("a-b", "aXb", ".x", ".y", "a*b/", "a*b/ooo", "man/", "man/man1/", "man/man1/bash.1"); // [ pattern, new [] { matches }, MM opts, files, TAP opts] - TestCase("{/*,*}", new string[0], new Options { /*null = true*/ }, new[] { "/asdf/asdf/asdf" }); - TestCase("{/?,*}", new[] { "/a", "bb" }, new Options { /*null = true*/ } - , new[] { "/a", "/b/b", "/a/b/c", "bb" }); + TestCase("{/*,*}", new string[0], new Options(), new[] { "/asdf/asdf/asdf" }); + TestCase("{/?,*}", new[] { "/a", "bb" }, new Options(), new[] { "/a", "/b/b", "/a/b/c", "bb" }); AssertRegexes( "/^(?:\\/(?!\\.)(?=.)[^/]*?|(?!\\.)(?=.)[^/]*?)$/", "/^(?:\\/(?!\\.)(?=.)[^/]|(?!\\.)(?=.)[^/]*?)$/" ); } + [Fact] public void DotMatching() { AddFiles("a-b", "aXb", ".x", ".y", "a*b/", "a*b/ooo", "man/", "man/man1/", "man/man1/bash.1"); //"Dots should not match unless requested" - TestCase("**", new[] { "a/b" }, new Options { }, new[] { "a/b", "a/.d", ".a/.d" }); + TestCase("**", new[] { "a/b" }, new Options(), new[] { "a/b", "a/.d", ".a/.d" }); // .. and . can only match patterns starting with ., // even when options.Dot is set. @@ -311,8 +334,10 @@ public void DotMatching() // this also tests that changing the options needs // to change the cache key, even if the pattern is // the same! - TestCase("**", new[] { "a/b", "a/.d", ".a/.d" }, new Options { Dot = true } - , new[] { ".a/.d", "a/.d", "a/b" }); + TestCase( + "**", new[] { "a/b", "a/.d", ".a/.d" }, new Options { Dot = true } + , new[] { ".a/.d", "a/.d", "a/b" } + ); AssertRegexes( "/^(?:(?:(?!(?:\\/|^)\\.).)*?)$/", @@ -323,6 +348,7 @@ public void DotMatching() "/^(?:(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?)$/" ); } + [Fact] public void ParenSlashes() { @@ -345,28 +371,31 @@ public void ParenSlashes() // bash/bsdglob says this: // , new [] { "*(a|{b),c)}", ["*(a|{b),c)}" }, new Options {}, new [] { "a", "ab", "ac", "ad" }); // but we do this instead: - TestCase("*(a|{b),c)}", new[] { "a", "ab", "ac" }, new Options { }, new[] { "a", "ab", "ac", "ad" }); + TestCase("*(a|{b),c)}", new[] { "a", "ab", "ac" }, new Options(), new[] { "a", "ab", "ac", "ad" }); // test partial parsing in the presence of comment/negation chars - TestCase("[!a*", new[] { "[!ab" }, new Options { }, new[] { "[!ab", "[ab" }); - TestCase("[#a*", new[] { "[#ab" }, new Options { }, new[] { "[#ab", "[ab" }); + TestCase("[!a*", new[] { "[!ab" }, new Options(), new[] { "[!ab", "[ab" }); + TestCase("[#a*", new[] { "[#ab" }, new Options(), new[] { "[#ab", "[ab" }); // like: {a,b|c\\,d\\\|e} except it's unclosed, so it has to be escaped. - TestCase("+(a|*\\|c\\\\|d\\\\\\|e\\\\\\\\|f\\\\\\\\\\|g" - , new[] { "+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g" } - , new Options { } - , new[] { "+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g", "a", "b\\c" }); + TestCase( + "+(a|*\\|c\\\\|d\\\\\\|e\\\\\\\\|f\\\\\\\\\\|g" + , new[] { "+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g" } + , new Options(), new[] { "+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g", "a", "b\\c" } + ); // crazy nested {,,} and *(||) tests. - ReplaceFiles("a", "b", "c", "d" - , "ab", "ac", "ad" - , "bc", "cb" - , "bc,d", "c,db", "c,d" - , "d)", "(b|c", "*(b|c" - , "b|c", "b|cc", "cb|c" - , "x(a|b|c)", "x(a|c)" - , "(a|b|c)", "(a|c)"); + ReplaceFiles( + "a", "b", "c", "d" + , "ab", "ac", "ad" + , "bc", "cb" + , "bc,d", "c,db", "c,d" + , "d)", "(b|c", "*(b|c" + , "b|c", "b|cc", "cb|c" + , "x(a|b|c)", "x(a|c)" + , "(a|b|c)", "(a|c)" + ); TestCase("*(a|{b,c})", new[] { "a", "b", "c", "ab", "ac" }); TestCase("{a,*(b|c,d)}", new[] { "a", "(b|c", "*(b|c", "d)" }); // a @@ -377,10 +406,14 @@ public void ParenSlashes() // test various flag settings. - TestCase("*(a|{b|c,c})", new[] { "x(a|b|c)", "x(a|c)", "(a|b|c)", "(a|c)" } - , new Options { NoExt = true }); - TestCase("a?b", new[] { "x/y/acb", "acb/" }, new Options { MatchBase = true } - , new[] { "x/y/acb", "acb/", "acb/d/e", "x/y/acb/d" }); + TestCase( + "*(a|{b|c,c})", new[] { "x(a|b|c)", "x(a|c)", "(a|b|c)", "(a|c)" } + , new Options { NoExt = true } + ); + TestCase( + "a?b", new[] { "x/y/acb", "acb/" }, new Options { MatchBase = true } + , new[] { "x/y/acb", "acb/", "acb/d/e", "x/y/acb/d" } + ); TestCase("#*", new[] { "#a", "#b" }, new Options { NoComment = true }, new[] { "#a", "#b", "c#d" }); AssertRegexes( @@ -398,6 +431,7 @@ public void ParenSlashes() "/^(?:(?=.)#[^/]*?)$/" ); } + [Fact] public void NegationTests() { @@ -417,37 +451,34 @@ public void NegationTests() TestCase("!\\!a*", new[] { "a!b", "d", "e", "\\!a" }); // negation nestled within a pattern - ReplaceFiles("foo.js" - , "foo.bar" + ReplaceFiles( + "foo.js" + , "foo.bar" // can't match this one without negative lookbehind. - , "foo.js.js" - , "blar.js" - , "foo." - , "boo.js.boo"); + , "foo.js.js" + , "blar.js" + , "foo." + , "boo.js.boo" + ); TestCase("*.!(js)", new[] { "foo.bar", "foo.", "boo.js.boo" }); // https://github.com/isaacs/minimatch/issues/5 - ReplaceFiles("a/b/.x/c" - , "a/b/.x/c/d" - , "a/b/.x/c/d/e" - , "a/b/.x" - , "a/b/.x/" - , "a/.x/b" - , ".x" - , ".x/" - , ".x/a" - , ".x/a/b" - , "a/.x/b/.x/c" - , ".x/.x"); - - TestCase("**/.x/**", new[] { ".x/" - , ".x/a" - , ".x/a/b" - , "a/.x/b" - , "a/b/.x/" - , "a/b/.x/c" - , "a/b/.x/c/d" - , "a/b/.x/c/d/e" }); + ReplaceFiles( + "a/b/.x/c" + , "a/b/.x/c/d" + , "a/b/.x/c/d/e" + , "a/b/.x" + , "a/b/.x/" + , "a/.x/b" + , ".x" + , ".x/" + , ".x/a" + , ".x/a/b" + , "a/.x/b/.x/c" + , ".x/.x" + ); + + TestCase("**/.x/**", new[] { ".x/", ".x/a", ".x/a/b", "a/.x/b", "a/b/.x/", "a/b/.x/c", "a/b/.x/c/d", "a/b/.x/c/d/e" }); AssertRegexes( "/^(?!^(?:(?=.)a[^/]*?)$).*$/", @@ -459,4 +490,4 @@ public void NegationTests() ); } } -} \ No newline at end of file +} diff --git a/test/Lsp.Tests/Models/ApplyWorkspaceEditParamsTests.cs b/test/Lsp.Tests/Models/ApplyWorkspaceEditParamsTests.cs index 3a424c030..bc212d996 100644 --- a/test/Lsp.Tests/Models/ApplyWorkspaceEditParamsTests.cs +++ b/test/Lsp.Tests/Models/ApplyWorkspaceEditParamsTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using FluentAssertions; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; 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; using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; @@ -12,21 +12,22 @@ namespace Lsp.Tests.Models { public class ApplyWorkspaceEditParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new ApplyWorkspaceEditParams() { - Edit = new WorkspaceEdit() { - Changes = new Dictionary>() { + var model = new ApplyWorkspaceEditParams { + Edit = new WorkspaceEdit { + Changes = new Dictionary> { { - new Uri("file:///abc/123/d.cs"), new [] { - new TextEdit() { + new Uri("file:///abc/123/d.cs"), new[] { + new TextEdit { NewText = "new text", - Range = new Range(new Position(1, 1), new Position(2,2)) + Range = new Range(new Position(1, 1), new Position(2, 2)) }, - new TextEdit() { + new TextEdit { NewText = "new text2", - Range = new Range(new Position(3, 3), new Position(4,4)) + Range = new Range(new Position(3, 3), new Position(4, 4)) } } } @@ -41,22 +42,23 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void NonStandardCharactersTest(string expected) { - var model = new ApplyWorkspaceEditParams() { - Edit = new WorkspaceEdit() { - Changes = new Dictionary>() { + var model = new ApplyWorkspaceEditParams { + Edit = new WorkspaceEdit { + Changes = new Dictionary> { { // Mörkö - new Uri("file:///abc/bc/123/M%C3%B6rk%C3%B6.cs"), new [] { - new TextEdit() { + new Uri("file:///abc/bc/123/M%C3%B6rk%C3%B6.cs"), new[] { + new TextEdit { NewText = "new text", - Range = new Range(new Position(1, 1), new Position(2,2)) + Range = new Range(new Position(1, 1), new Position(2, 2)) }, - new TextEdit() { + new TextEdit { NewText = "new text2", - Range = new Range(new Position(3, 3), new Position(4,4)) + Range = new Range(new Position(3, 3), new Position(4, 4)) } } } @@ -71,62 +73,63 @@ public void NonStandardCharactersTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void DocumentChangesTest(string expected) { - var model = new ApplyWorkspaceEditParams() { - Edit = new WorkspaceEdit() { + var model = new ApplyWorkspaceEditParams { + Edit = new WorkspaceEdit { DocumentChanges = new Container( - new TextDocumentEdit() { - TextDocument = new VersionedTextDocumentIdentifier() { + new TextDocumentEdit { + TextDocument = new VersionedTextDocumentIdentifier { Version = 1, Uri = new Uri("file:///abc/123/d.cs"), }, Edits = new[] { - new TextEdit() { + new TextEdit { NewText = "new text", - Range = new Range(new Position(1, 1), new Position(2,2)) + Range = new Range(new Position(1, 1), new Position(2, 2)) }, - new TextEdit() { + new TextEdit { NewText = "new text2", - Range = new Range(new Position(3, 3), new Position(4,4)) + Range = new Range(new Position(3, 3), new Position(4, 4)) } } }, - new TextDocumentEdit() { - TextDocument = new VersionedTextDocumentIdentifier() { + new TextDocumentEdit { + TextDocument = new VersionedTextDocumentIdentifier { Version = 1, Uri = new Uri("file:///abc/123/b.cs"), }, Edits = new[] { - new TextEdit() { + new TextEdit { NewText = "new text2", - Range = new Range(new Position(1, 1), new Position(2,2)) + Range = new Range(new Position(1, 1), new Position(2, 2)) }, - new TextEdit() { + new TextEdit { NewText = "new text3", - Range = new Range(new Position(3, 3), new Position(4,4)) + Range = new Range(new Position(3, 3), new Position(4, 4)) } } }, - new CreateFile() { + new CreateFile { Uri = "file:///abc/123/b.cs", - Options = new CreateFileOptions() { + Options = new CreateFileOptions { IgnoreIfExists = true, Overwrite = true } }, - new RenameFile() { + new RenameFile { OldUri = "file:///abc/123/b.cs", NewUri = "file:///abc/123/c.cs", - Options = new RenameFileOptions() { + Options = new RenameFileOptions { IgnoreIfExists = true, Overwrite = true } }, - new DeleteFile() { + new DeleteFile { Uri = "file:///abc/123/c.cs", - Options = new DeleteFileOptions() { + Options = new DeleteFileOptions { IgnoreIfNotExists = true, Recursive = false } @@ -139,15 +142,16 @@ public void DocumentChangesTest(string expected) result.Should().Be(expected); var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x - .ComparingByMembers() - //.ComparingByMembers() - //.ComparingByMembers() - //.ComparingByMembers() - //.ComparingByMembers() - //.ComparingByMembers() - //.ComparingByMembers() - //.ComparingByMembers() + deresult.Should().BeEquivalentTo( + model, x => x + .ComparingByMembers() + //.ComparingByMembers() + //.ComparingByMembers() + //.ComparingByMembers() + //.ComparingByMembers() + //.ComparingByMembers() + //.ComparingByMembers() + //.ComparingByMembers() ); } } diff --git a/test/Lsp.Tests/Models/ApplyWorkspaceEditResponseTests.cs b/test/Lsp.Tests/Models/ApplyWorkspaceEditResponseTests.cs index afccce5e1..2c25f35e2 100644 --- a/test/Lsp.Tests/Models/ApplyWorkspaceEditResponseTests.cs +++ b/test/Lsp.Tests/Models/ApplyWorkspaceEditResponseTests.cs @@ -8,10 +8,11 @@ namespace Lsp.Tests.Models { public class ApplyWorkspaceEditResponseTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new ApplyWorkspaceEditResponse() { + var model = new ApplyWorkspaceEditResponse { Applied = true, }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/CancelParamsTests.cs b/test/Lsp.Tests/Models/CancelParamsTests.cs index f68cecf25..b40ea502b 100644 --- a/test/Lsp.Tests/Models/CancelParamsTests.cs +++ b/test/Lsp.Tests/Models/CancelParamsTests.cs @@ -1,23 +1,25 @@ using FluentAssertions; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; +using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using Xunit; namespace Lsp.Tests.Models { public class CancelParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new CancelParams() { + var model = new CancelParams { Id = "123" }; var result = Fixture.SerializeObject(model); result.Should().Be(expected); - var deresult = new OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Serializer(ClientVersion.Lsp3).DeserializeObject(expected); + var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject(expected); deresult.Should().BeEquivalentTo(model); } } diff --git a/test/Lsp.Tests/Models/CodeActionContextTests.cs b/test/Lsp.Tests/Models/CodeActionContextTests.cs index 8ce362475..2460f8a44 100644 --- a/test/Lsp.Tests/Models/CodeActionContextTests.cs +++ b/test/Lsp.Tests/Models/CodeActionContextTests.cs @@ -3,23 +3,25 @@ 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 { public class CodeActionContextTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new CodeActionContext() { - Diagnostics = new[] { new Diagnostic() { - Code = new DiagnosticCode("abcd"), - Message = "message", - Range = new Range(new Position(1, 1), new Position(2,2)), - Severity = DiagnosticSeverity.Error, - Source = "csharp" - } } + var model = new CodeActionContext { + Diagnostics = new[] { + new Diagnostic { + Code = new DiagnosticCode("abcd"), + Message = "message", + Range = new Range(new Position(1, 1), new Position(2, 2)), + Severity = DiagnosticSeverity.Error, + Source = "csharp" + } + } }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/CodeActionParamsTests.cs b/test/Lsp.Tests/Models/CodeActionParamsTests.cs index 4f053ff6c..509256b0c 100644 --- a/test/Lsp.Tests/Models/CodeActionParamsTests.cs +++ b/test/Lsp.Tests/Models/CodeActionParamsTests.cs @@ -10,22 +10,24 @@ namespace Lsp.Tests.Models { public class CodeActionParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new CodeActionParams() { - Context = new CodeActionContext() { - Diagnostics = new[] { new Diagnostic() { - Code = new DiagnosticCode("abcd"), - Message = "message", - Range = new Range(new Position(1, 1), new Position(2,2)), - Severity = DiagnosticSeverity.Error, - Source = "csharp" - } } - + var model = new CodeActionParams { + Context = new CodeActionContext { + Diagnostics = new[] { + new Diagnostic { + Code = new DiagnosticCode("abcd"), + Message = "message", + Range = new Range(new Position(1, 1), new Position(2, 2)), + Severity = DiagnosticSeverity.Error, + Source = "csharp" + } + } }, Range = new Range(new Position(1, 1), new Position(2, 2)), - TextDocument = new TextDocumentIdentifier() { + TextDocument = new TextDocumentIdentifier { Uri = new Uri("file:///test/123/d.cs") } }; @@ -37,22 +39,24 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void NonStandardCharactersTest(string expected) { - var model = new CodeActionParams() { - Context = new CodeActionContext() { - Diagnostics = new[] { new Diagnostic() { - Code = new DiagnosticCode("abcd"), - Message = "message", - Range = new Range(new Position(1, 1), new Position(2,2)), - Severity = DiagnosticSeverity.Error, - Source = "csharp" - } } - + var model = new CodeActionParams { + Context = new CodeActionContext { + Diagnostics = new[] { + new Diagnostic { + Code = new DiagnosticCode("abcd"), + Message = "message", + Range = new Range(new Position(1, 1), new Position(2, 2)), + Severity = DiagnosticSeverity.Error, + Source = "csharp" + } + } }, Range = new Range(new Position(1, 1), new Position(2, 2)), - TextDocument = new TextDocumentIdentifier() { + TextDocument = new TextDocumentIdentifier { // 树 - Chinese for tree Uri = new Uri("file:///test/123/%E6%A0%91.cs") } diff --git a/test/Lsp.Tests/Models/CodeActionRegistrationOptionsTests.cs b/test/Lsp.Tests/Models/CodeActionRegistrationOptionsTests.cs index 5fad4fa09..7ab8c139e 100644 --- a/test/Lsp.Tests/Models/CodeActionRegistrationOptionsTests.cs +++ b/test/Lsp.Tests/Models/CodeActionRegistrationOptionsTests.cs @@ -8,19 +8,22 @@ namespace Lsp.Tests.Models { public class CodeActionRegistrationOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new CodeActionRegistrationOptions() { - DocumentSelector = new DocumentSelector(new[] { new DocumentFilter(){ - Language = "csharp", - Pattern = "pattern", - Scheme = "scheme" - }, new DocumentFilter(){ - Language = "vb", - Pattern = "pattern", - Scheme = "scheme" - } }), + var model = new CodeActionRegistrationOptions { + DocumentSelector = new DocumentSelector( + new DocumentFilter { + Language = "csharp", + Pattern = "pattern", + Scheme = "scheme" + }, new DocumentFilter { + Language = "vb", + Pattern = "pattern", + Scheme = "scheme" + } + ), CodeActionKinds = new[] { CodeActionKind.QuickFix, CodeActionKind.Refactor, diff --git a/test/Lsp.Tests/Models/CodeLensParamsTests.cs b/test/Lsp.Tests/Models/CodeLensParamsTests.cs index fe1588375..5dc78f65b 100644 --- a/test/Lsp.Tests/Models/CodeLensParamsTests.cs +++ b/test/Lsp.Tests/Models/CodeLensParamsTests.cs @@ -10,10 +10,11 @@ namespace Lsp.Tests.Models { public class CodeLensParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new CodeLensParams() { + var model = new CodeLensParams { TextDocument = new TextDocumentIdentifier(new Uri("file:///abc/123/d.cs")), }; var result = Fixture.SerializeObject(model); @@ -24,10 +25,11 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void NonStandardCharactersTest(string expected) { - var model = new CodeLensParams() { + var model = new CodeLensParams { // UNC path with Chinese character for tree. TextDocument = new TextDocumentIdentifier(DocumentUri.FromFileSystemPath("\\\\abc\\123\\树.cs")), }; diff --git a/test/Lsp.Tests/Models/CodeLensRegistrationOptionsTests.cs b/test/Lsp.Tests/Models/CodeLensRegistrationOptionsTests.cs index eaa5aa058..272d4a320 100644 --- a/test/Lsp.Tests/Models/CodeLensRegistrationOptionsTests.cs +++ b/test/Lsp.Tests/Models/CodeLensRegistrationOptionsTests.cs @@ -8,19 +8,22 @@ namespace Lsp.Tests.Models { public class CodeLensRegistrationOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new CodeLensRegistrationOptions() { - DocumentSelector = new DocumentSelector(new[] { new DocumentFilter(){ - Language = "csharp", - Pattern = "pattern", - Scheme = "scheme" - }, new DocumentFilter(){ - Language = "vb", - Pattern = "pattern", - Scheme = "scheme" - } }), + var model = new CodeLensRegistrationOptions { + DocumentSelector = new DocumentSelector( + new DocumentFilter { + Language = "csharp", + Pattern = "pattern", + Scheme = "scheme" + }, new DocumentFilter { + Language = "vb", + Pattern = "pattern", + Scheme = "scheme" + } + ), ResolveProvider = true }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/CodeLensTests.cs b/test/Lsp.Tests/Models/CodeLensTests.cs index 844252cd0..c175640e1 100644 --- a/test/Lsp.Tests/Models/CodeLensTests.cs +++ b/test/Lsp.Tests/Models/CodeLensTests.cs @@ -5,25 +5,26 @@ 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 { public class CodeLensTests { - [Theory, JsonFixture] + [Theory] + [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() - { - { "somethingCool" , 1 } - }), + Data = JObject.FromObject( + new Dictionary { + { "somethingCool", 1 } + } + ), Range = new Range(new Position(1, 2), new Position(2, 3)), }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/CommandTests.cs b/test/Lsp.Tests/Models/CommandTests.cs index f2d336334..c21f29f22 100644 --- a/test/Lsp.Tests/Models/CommandTests.cs +++ b/test/Lsp.Tests/Models/CommandTests.cs @@ -9,10 +9,11 @@ namespace Lsp.Tests.Models { public class CommandTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new Command() { + var model = new Command { Arguments = new JArray { 1, "2", true }, Name = "abc", Title = "Cool story bro" diff --git a/test/Lsp.Tests/Models/CompletionItemKindTests.cs b/test/Lsp.Tests/Models/CompletionItemKindTests.cs index 7f3d5dd60..ed778a751 100644 --- a/test/Lsp.Tests/Models/CompletionItemKindTests.cs +++ b/test/Lsp.Tests/Models/CompletionItemKindTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Models { public class CompletionItemKindTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = CompletionItemKind.Color; diff --git a/test/Lsp.Tests/Models/CompletionItemTests.cs b/test/Lsp.Tests/Models/CompletionItemTests.cs index 7d56a8424..a299dc7a3 100644 --- a/test/Lsp.Tests/Models/CompletionItemTests.cs +++ b/test/Lsp.Tests/Models/CompletionItemTests.cs @@ -8,15 +8,15 @@ namespace Lsp.Tests.Models { public class CompletionItemTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new CompletionItem() - { + var model = new CompletionItem { Kind = CompletionItemKind.Text, CommitCharacters = new[] { ";", "/", "." }, AdditionalTextEdits = new[] { - new TextEdit() { + new TextEdit { NewText = "new text" } } diff --git a/test/Lsp.Tests/Models/CompletionListTests.cs b/test/Lsp.Tests/Models/CompletionListTests.cs index 26646d794..7693c228a 100644 --- a/test/Lsp.Tests/Models/CompletionListTests.cs +++ b/test/Lsp.Tests/Models/CompletionListTests.cs @@ -9,14 +9,18 @@ namespace Lsp.Tests.Models { public class CompletionListTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new CompletionList(new List() { new CompletionItem() - { - Kind = CompletionItemKind.Class, - Detail = "details" - } }); + var model = new CompletionList( + new List { + new CompletionItem { + Kind = CompletionItemKind.Class, + Detail = "details" + } + } + ); var result = Fixture.SerializeObject(model); result.Should().Be(expected); @@ -25,15 +29,18 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void ComplexTest(string expected) { - var model = new CompletionList(new List() { - new CompletionItem() - { - Kind = CompletionItemKind.Class, - Detail = "details" - } }, true); + var model = new CompletionList( + new List { + new CompletionItem { + Kind = CompletionItemKind.Class, + Detail = "details" + } + }, true + ); var result = Fixture.SerializeObject(model); result.Should().Be(expected); diff --git a/test/Lsp.Tests/Models/CompletionRegistrationOptionsTests.cs b/test/Lsp.Tests/Models/CompletionRegistrationOptionsTests.cs index d4434d4e3..13bb9314a 100644 --- a/test/Lsp.Tests/Models/CompletionRegistrationOptionsTests.cs +++ b/test/Lsp.Tests/Models/CompletionRegistrationOptionsTests.cs @@ -8,13 +8,16 @@ namespace Lsp.Tests.Models { public class CompletionRegistrationOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new CompletionRegistrationOptions() { - DocumentSelector = new DocumentSelector(new DocumentFilter() { - Language = "csharp" - }), + var model = new CompletionRegistrationOptions { + DocumentSelector = new DocumentSelector( + new DocumentFilter { + Language = "csharp" + } + ), ResolveProvider = true, TriggerCharacters = new[] { "." } }; diff --git a/test/Lsp.Tests/Models/DiagnosticCodeTests.cs b/test/Lsp.Tests/Models/DiagnosticCodeTests.cs index c340ab913..f89429c88 100644 --- a/test/Lsp.Tests/Models/DiagnosticCodeTests.cs +++ b/test/Lsp.Tests/Models/DiagnosticCodeTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Models { public class DiagnosticCodeTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new DiagnosticCode(); diff --git a/test/Lsp.Tests/Models/DiagnosticSeverityTests.cs b/test/Lsp.Tests/Models/DiagnosticSeverityTests.cs index 646784f80..24d376ec9 100644 --- a/test/Lsp.Tests/Models/DiagnosticSeverityTests.cs +++ b/test/Lsp.Tests/Models/DiagnosticSeverityTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Models { public class DiagnosticSeverityTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new DiagnosticSeverity(); diff --git a/test/Lsp.Tests/Models/DiagnosticTests.cs b/test/Lsp.Tests/Models/DiagnosticTests.cs index cc5393038..335a43021 100644 --- a/test/Lsp.Tests/Models/DiagnosticTests.cs +++ b/test/Lsp.Tests/Models/DiagnosticTests.cs @@ -10,10 +10,11 @@ namespace Lsp.Tests.Models { public class DiagnosticTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new Diagnostic() { + var model = new Diagnostic { Code = new DiagnosticCode("abcd"), Message = "message", Range = new Range(new Position(1, 1), new Position(2, 2)), @@ -28,10 +29,11 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void RelatedInformationTest(string expected) { - var model = new Diagnostic() { + var model = new Diagnostic { Code = new DiagnosticCode("abcd"), Message = "message", Range = new Range(new Position(1, 1), new Position(2, 2)), @@ -63,7 +65,8 @@ public void RelatedInformationTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void OptionalTest(string expected) { var model = new Diagnostic(); diff --git a/test/Lsp.Tests/Models/DidChangeConfigurationParamsTests.cs b/test/Lsp.Tests/Models/DidChangeConfigurationParamsTests.cs index 7e6413991..e282fa561 100644 --- a/test/Lsp.Tests/Models/DidChangeConfigurationParamsTests.cs +++ b/test/Lsp.Tests/Models/DidChangeConfigurationParamsTests.cs @@ -10,15 +10,18 @@ namespace Lsp.Tests.Models { public class DidChangeConfigurationParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DidChangeConfigurationParams() { - Settings = JObject.FromObject(new Dictionary() { - { "abc", 1 }, - { "def", "a" }, - { "ghi", true }, - }) + var model = new DidChangeConfigurationParams { + Settings = JObject.FromObject( + new Dictionary { + { "abc", 1 }, + { "def", "a" }, + { "ghi", true }, + } + ) }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/DidChangeTextDocumentParamsTests.cs b/test/Lsp.Tests/Models/DidChangeTextDocumentParamsTests.cs index a6f62578e..a2b825e6a 100644 --- a/test/Lsp.Tests/Models/DidChangeTextDocumentParamsTests.cs +++ b/test/Lsp.Tests/Models/DidChangeTextDocumentParamsTests.cs @@ -4,24 +4,24 @@ 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 { public class DidChangeTextDocumentParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DidChangeTextDocumentParams() { + var model = new DidChangeTextDocumentParams { ContentChanges = new[] { - new TextDocumentContentChangeEvent() { - Range = new Range(new Position(1,1), new Position(2, 2)), + new TextDocumentContentChangeEvent { + Range = new Range(new Position(1, 1), new Position(2, 2)), RangeLength = 12, Text = "abc" } }, - TextDocument = new VersionedTextDocumentIdentifier() { + TextDocument = new VersionedTextDocumentIdentifier { Uri = "/somepath/to/a/file.ext", } }; @@ -33,18 +33,19 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void NonStandardCharactersTest(string expected) { - var model = new DidChangeTextDocumentParams() { + var model = new DidChangeTextDocumentParams { ContentChanges = new[] { - new TextDocumentContentChangeEvent() { - Range = new Range(new Position(1,1), new Position(2, 2)), + new TextDocumentContentChangeEvent { + Range = new Range(new Position(1, 1), new Position(2, 2)), RangeLength = 12, Text = "abc" } }, - TextDocument = new VersionedTextDocumentIdentifier() { + TextDocument = new VersionedTextDocumentIdentifier { Uri = DocumentUri.FromFileSystemPath("c:\\abc\\Mörkö.cs") } }; diff --git a/test/Lsp.Tests/Models/DidChangeWatchedFilesParamsTests.cs b/test/Lsp.Tests/Models/DidChangeWatchedFilesParamsTests.cs index 5af8d4841..668c8dd97 100644 --- a/test/Lsp.Tests/Models/DidChangeWatchedFilesParamsTests.cs +++ b/test/Lsp.Tests/Models/DidChangeWatchedFilesParamsTests.cs @@ -9,12 +9,13 @@ namespace Lsp.Tests.Models { public class DidChangeWatchedFilesParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DidChangeWatchedFilesParams() { + var model = new DidChangeWatchedFilesParams { Changes = new[] { - new FileEvent() { + new FileEvent { Type = FileChangeType.Created, Uri = new Uri("file:///someawesomefile") } @@ -28,12 +29,13 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void NonStandardCharactersTest(string expected) { - var model = new DidChangeWatchedFilesParams() { + var model = new DidChangeWatchedFilesParams { Changes = new[] { - new FileEvent() { + new FileEvent { Type = FileChangeType.Created, // Mörkö Uri = new Uri("file:///M%C3%B6rk%C3%B6.cs") diff --git a/test/Lsp.Tests/Models/DidCloseTextDocumentParamsTests.cs b/test/Lsp.Tests/Models/DidCloseTextDocumentParamsTests.cs index 4653b9617..f1075fb6b 100644 --- a/test/Lsp.Tests/Models/DidCloseTextDocumentParamsTests.cs +++ b/test/Lsp.Tests/Models/DidCloseTextDocumentParamsTests.cs @@ -9,10 +9,11 @@ namespace Lsp.Tests.Models { public class DidCloseTextDocumentParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DidCloseTextDocumentParams() { + var model = new DidCloseTextDocumentParams { TextDocument = new TextDocumentIdentifier(new Uri("file:///abc/def.cs")) }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/DidOpenTextDocumentParamsTests.cs b/test/Lsp.Tests/Models/DidOpenTextDocumentParamsTests.cs index dae8336ba..100881193 100644 --- a/test/Lsp.Tests/Models/DidOpenTextDocumentParamsTests.cs +++ b/test/Lsp.Tests/Models/DidOpenTextDocumentParamsTests.cs @@ -9,11 +9,12 @@ namespace Lsp.Tests.Models { public class DidOpenTextDocumentParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DidOpenTextDocumentParams() { - TextDocument = new TextDocumentItem() { + var model = new DidOpenTextDocumentParams { + TextDocument = new TextDocumentItem { Uri = new Uri("file:///abc/def.cs"), LanguageId = "csharp", Text = "content", diff --git a/test/Lsp.Tests/Models/DidSaveTextDocumentParamsTests.cs b/test/Lsp.Tests/Models/DidSaveTextDocumentParamsTests.cs index f3956746f..85454c7e2 100644 --- a/test/Lsp.Tests/Models/DidSaveTextDocumentParamsTests.cs +++ b/test/Lsp.Tests/Models/DidSaveTextDocumentParamsTests.cs @@ -9,10 +9,11 @@ namespace Lsp.Tests.Models { public class DidSaveTextDocumentParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DidSaveTextDocumentParams() { + var model = new DidSaveTextDocumentParams { Text = "content", TextDocument = new TextDocumentIdentifier(new Uri("file:///abc/def.cs")) }; diff --git a/test/Lsp.Tests/Models/DocumentFilterTests.cs b/test/Lsp.Tests/Models/DocumentFilterTests.cs index 8e5260476..04bb1e2cc 100644 --- a/test/Lsp.Tests/Models/DocumentFilterTests.cs +++ b/test/Lsp.Tests/Models/DocumentFilterTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Models { public class DocumentFilterTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void Empty(string expected) { var model = new DocumentFilter(); @@ -20,10 +21,11 @@ public void Empty(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void OnlyLanguage(string expected) { - var model = new DocumentFilter() { + var model = new DocumentFilter { Language = "csharp" }; var result = Fixture.SerializeObject(model); @@ -34,10 +36,11 @@ public void OnlyLanguage(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void OnlyScheme(string expected) { - var model = new DocumentFilter() { + var model = new DocumentFilter { Scheme = "abc" }; var result = Fixture.SerializeObject(model); @@ -48,10 +51,11 @@ public void OnlyScheme(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void OnlyPattern(string expected) { - var model = new DocumentFilter() { + var model = new DocumentFilter { Pattern = "123**" }; var result = Fixture.SerializeObject(model); @@ -62,10 +66,11 @@ public void OnlyPattern(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void Mixed(string expected) { - var model = new DocumentFilter() { + var model = new DocumentFilter { Pattern = "123**", Language = "csharp" }; @@ -77,10 +82,11 @@ public void Mixed(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void Full(string expected) { - var model = new DocumentFilter() { + var model = new DocumentFilter { Pattern = "123**", Language = "csharp", Scheme = "abc" diff --git a/test/Lsp.Tests/Models/DocumentFormattingParamsTests.cs b/test/Lsp.Tests/Models/DocumentFormattingParamsTests.cs index 2799ac5c5..49006715d 100644 --- a/test/Lsp.Tests/Models/DocumentFormattingParamsTests.cs +++ b/test/Lsp.Tests/Models/DocumentFormattingParamsTests.cs @@ -9,11 +9,12 @@ namespace Lsp.Tests.Models { public class DocumentFormattingParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DocumentFormattingParams() { - Options = new FormattingOptions() { + var model = new DocumentFormattingParams { + Options = new FormattingOptions { { "abc", 1 } }, TextDocument = new TextDocumentIdentifier(new Uri("file:///abc123.cs")) diff --git a/test/Lsp.Tests/Models/DocumentHighlightKindTests.cs b/test/Lsp.Tests/Models/DocumentHighlightKindTests.cs index bd4c7bb27..eaeb84a24 100644 --- a/test/Lsp.Tests/Models/DocumentHighlightKindTests.cs +++ b/test/Lsp.Tests/Models/DocumentHighlightKindTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Models { public class DocumentHighlightKindTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new DocumentHighlightKind(); diff --git a/test/Lsp.Tests/Models/DocumentHighlightTests.cs b/test/Lsp.Tests/Models/DocumentHighlightTests.cs index d50e937bf..2264bf3d6 100644 --- a/test/Lsp.Tests/Models/DocumentHighlightTests.cs +++ b/test/Lsp.Tests/Models/DocumentHighlightTests.cs @@ -3,16 +3,16 @@ 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 { public class DocumentHighlightTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DocumentHighlight() { + var model = new DocumentHighlight { Kind = DocumentHighlightKind.Text, Range = new Range(new Position(1, 1), new Position(2, 2)) }; diff --git a/test/Lsp.Tests/Models/DocumentLinkParamsTests.cs b/test/Lsp.Tests/Models/DocumentLinkParamsTests.cs index aac1dd948..6d4e92a75 100644 --- a/test/Lsp.Tests/Models/DocumentLinkParamsTests.cs +++ b/test/Lsp.Tests/Models/DocumentLinkParamsTests.cs @@ -9,10 +9,11 @@ namespace Lsp.Tests.Models { public class DocumentLinkParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DocumentLinkParams() { + var model = new DocumentLinkParams { TextDocument = new TextDocumentIdentifier(new Uri("file:///abc/123.cs")) }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/DocumentLinkRegistrationOptionsTests.cs b/test/Lsp.Tests/Models/DocumentLinkRegistrationOptionsTests.cs index d9616be14..5ff755932 100644 --- a/test/Lsp.Tests/Models/DocumentLinkRegistrationOptionsTests.cs +++ b/test/Lsp.Tests/Models/DocumentLinkRegistrationOptionsTests.cs @@ -8,13 +8,16 @@ namespace Lsp.Tests.Models { public class DocumentLinkRegistrationOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DocumentLinkRegistrationOptions() { - DocumentSelector = new DocumentSelector(new DocumentFilter() { - Language = "csharp" - }), + var model = new DocumentLinkRegistrationOptions { + DocumentSelector = new DocumentSelector( + new DocumentFilter { + Language = "csharp" + } + ), ResolveProvider = true }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/DocumentLinkTests.cs b/test/Lsp.Tests/Models/DocumentLinkTests.cs index 09dd8f83c..f98564e92 100644 --- a/test/Lsp.Tests/Models/DocumentLinkTests.cs +++ b/test/Lsp.Tests/Models/DocumentLinkTests.cs @@ -10,10 +10,11 @@ namespace Lsp.Tests.Models { public class DocumentLinkTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DocumentLink() { + var model = new DocumentLink { Range = new Range(new Position(1, 2), new Position(3, 4)), Target = new Uri("file:///abc/123.cs") }; diff --git a/test/Lsp.Tests/Models/DocumentOnTypeFormattingParamsTests.cs b/test/Lsp.Tests/Models/DocumentOnTypeFormattingParamsTests.cs index ca2b27c12..332d845ac 100644 --- a/test/Lsp.Tests/Models/DocumentOnTypeFormattingParamsTests.cs +++ b/test/Lsp.Tests/Models/DocumentOnTypeFormattingParamsTests.cs @@ -9,15 +9,16 @@ namespace Lsp.Tests.Models { public class DocumentOnTypeFormattingParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DocumentOnTypeFormattingParams() { + var model = new DocumentOnTypeFormattingParams { Character = "c", - Options = new FormattingOptions() { + Options = new FormattingOptions { { "abc", 1 } }, - Position = new Position(1,2), + Position = new Position(1, 2), TextDocument = new TextDocumentIdentifier(new Uri("file:///abc/123.cs")) }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/DocumentOnTypeFormattingRegistrationOptionsTests.cs b/test/Lsp.Tests/Models/DocumentOnTypeFormattingRegistrationOptionsTests.cs index 93a56ce03..49098bd00 100644 --- a/test/Lsp.Tests/Models/DocumentOnTypeFormattingRegistrationOptionsTests.cs +++ b/test/Lsp.Tests/Models/DocumentOnTypeFormattingRegistrationOptionsTests.cs @@ -8,15 +8,18 @@ namespace Lsp.Tests.Models { public class DocumentOnTypeFormattingRegistrationOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DocumentOnTypeFormattingRegistrationOptions() { - DocumentSelector = new DocumentSelector(new DocumentFilter() { - Language = "csharp" - }), + var model = new DocumentOnTypeFormattingRegistrationOptions { + DocumentSelector = new DocumentSelector( + new DocumentFilter { + Language = "csharp" + } + ), FirstTriggerCharacter = "1", - MoreTriggerCharacter = new [] { "1", "2" } + MoreTriggerCharacter = new[] { "1", "2" } }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/DocumentSelectorTests.cs b/test/Lsp.Tests/Models/DocumentSelectorTests.cs index 55b5f8bb6..d3f900ea2 100644 --- a/test/Lsp.Tests/Models/DocumentSelectorTests.cs +++ b/test/Lsp.Tests/Models/DocumentSelectorTests.cs @@ -8,24 +8,19 @@ namespace Lsp.Tests.Models { public class DocumentSelectorTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DocumentSelector(new DocumentFilter[] - { - new DocumentFilter() - { + var model = new DocumentSelector( + new DocumentFilter { Language = "csharp", - }, - new DocumentFilter() - { + }, new DocumentFilter { Pattern = "**/*.vb" - }, - new DocumentFilter() - { + }, new DocumentFilter { Scheme = "visualbasic" - }, - }); + } + ); var result = Fixture.SerializeObject(model); result.Should().Be(expected); diff --git a/test/Lsp.Tests/Models/DocumentSymbolInformationTests.cs b/test/Lsp.Tests/Models/DocumentSymbolInformationTests.cs index 607b879d8..8a36a8b34 100644 --- a/test/Lsp.Tests/Models/DocumentSymbolInformationTests.cs +++ b/test/Lsp.Tests/Models/DocumentSymbolInformationTests.cs @@ -10,13 +10,14 @@ namespace Lsp.Tests.Models { public class DocumentSymbolInformationTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new SymbolInformation() { + var model = new SymbolInformation { ContainerName = "abc", Kind = SymbolKind.Boolean, - Location = new Location() { + Location = new Location { Range = new Range(new Position(1, 2), new Position(3, 4)), Uri = new Uri("file:///abc/123.cs") }, diff --git a/test/Lsp.Tests/Models/DocumentSymbolParamsTests.cs b/test/Lsp.Tests/Models/DocumentSymbolParamsTests.cs index 15b2111cb..552c26f4f 100644 --- a/test/Lsp.Tests/Models/DocumentSymbolParamsTests.cs +++ b/test/Lsp.Tests/Models/DocumentSymbolParamsTests.cs @@ -9,10 +9,11 @@ namespace Lsp.Tests.Models { public class DocumentSymbolParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new DocumentSymbolParams() { + var model = new DocumentSymbolParams { TextDocument = new TextDocumentIdentifier(new Uri("file:///abc/123.cs")) }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/ExecuteCommandParamsTests.cs b/test/Lsp.Tests/Models/ExecuteCommandParamsTests.cs index a12228ba9..54dda75ba 100644 --- a/test/Lsp.Tests/Models/ExecuteCommandParamsTests.cs +++ b/test/Lsp.Tests/Models/ExecuteCommandParamsTests.cs @@ -9,10 +9,11 @@ namespace Lsp.Tests.Models { public class ExecuteCommandParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new ExecuteCommandParams() { + var model = new ExecuteCommandParams { Arguments = new JArray(1, "2"), Command = "command" }; diff --git a/test/Lsp.Tests/Models/ExecuteCommandRegistrationOptionsTests.cs b/test/Lsp.Tests/Models/ExecuteCommandRegistrationOptionsTests.cs index 13ae9e179..9e2afe5ea 100644 --- a/test/Lsp.Tests/Models/ExecuteCommandRegistrationOptionsTests.cs +++ b/test/Lsp.Tests/Models/ExecuteCommandRegistrationOptionsTests.cs @@ -8,11 +8,12 @@ namespace Lsp.Tests.Models { public class ExecuteCommandRegistrationOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new ExecuteCommandRegistrationOptions() { - Commands = new [] { "1", "2" } + var model = new ExecuteCommandRegistrationOptions { + Commands = new[] { "1", "2" } }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/FileChangeTypeTests.cs b/test/Lsp.Tests/Models/FileChangeTypeTests.cs index f0d3a11c8..bcf2be7ab 100644 --- a/test/Lsp.Tests/Models/FileChangeTypeTests.cs +++ b/test/Lsp.Tests/Models/FileChangeTypeTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Models { public class FileChangeTypeTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new FileChangeType(); diff --git a/test/Lsp.Tests/Models/FileEventTests.cs b/test/Lsp.Tests/Models/FileEventTests.cs index 715329ed2..5367909bc 100644 --- a/test/Lsp.Tests/Models/FileEventTests.cs +++ b/test/Lsp.Tests/Models/FileEventTests.cs @@ -9,10 +9,11 @@ namespace Lsp.Tests.Models { public class FileEventTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new FileEvent() { + var model = new FileEvent { Type = FileChangeType.Deleted, Uri = new Uri("file:///abc/123.cs") }; diff --git a/test/Lsp.Tests/Models/FormattingOptionsTests.cs b/test/Lsp.Tests/Models/FormattingOptionsTests.cs index c395a10d8..3906013fc 100644 --- a/test/Lsp.Tests/Models/FormattingOptionsTests.cs +++ b/test/Lsp.Tests/Models/FormattingOptionsTests.cs @@ -8,11 +8,12 @@ namespace Lsp.Tests.Models { public class FormattingOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new FormattingOptions() { - { "tabSize", 4 }, + var model = new FormattingOptions { + { "tabSize", 4 }, { "insertSpaces", true }, { "somethingElse", "cool" } }; diff --git a/test/Lsp.Tests/Models/HoverTests.cs b/test/Lsp.Tests/Models/HoverTests.cs index b98ad958b..ebfa309ec 100644 --- a/test/Lsp.Tests/Models/HoverTests.cs +++ b/test/Lsp.Tests/Models/HoverTests.cs @@ -3,16 +3,16 @@ 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 { public class HoverTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new Hover() { + var model = new Hover { Contents = new MarkedStringsOrMarkupContent("abc"), Range = new Range(new Position(1, 2), new Position(3, 4)) }; diff --git a/test/Lsp.Tests/Models/InitializeErrorTests.cs b/test/Lsp.Tests/Models/InitializeErrorTests.cs index 9837155e7..b83d5bee6 100644 --- a/test/Lsp.Tests/Models/InitializeErrorTests.cs +++ b/test/Lsp.Tests/Models/InitializeErrorTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Models { public class InitializeErrorTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new InitializeError(); diff --git a/test/Lsp.Tests/Models/InitializeParamsTests.cs b/test/Lsp.Tests/Models/InitializeParamsTests.cs index 2a7e23eac..990e5336a 100644 --- a/test/Lsp.Tests/Models/InitializeParamsTests.cs +++ b/test/Lsp.Tests/Models/InitializeParamsTests.cs @@ -17,59 +17,51 @@ public InitializeParamsTests(ITestOutputHelper testOutputHelper) : base(testOutp { } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new InitializeParams() - { - Capabilities = new ClientCapabilities() - { - Experimental = new Dictionary() { { "abc", "test" } }, - TextDocument = new TextDocumentClientCapabilities() - { - CodeAction = new CodeActionCapability() { DynamicRegistration = true }, - CodeLens = new CodeLensCapability() { DynamicRegistration = true }, - Definition = new DefinitionCapability() { DynamicRegistration = true }, - DocumentHighlight = new DocumentHighlightCapability() { DynamicRegistration = true }, - DocumentLink = new DocumentLinkCapability() { DynamicRegistration = true }, - DocumentSymbol = new DocumentSymbolCapability() { DynamicRegistration = true }, - Formatting = new DocumentFormattingCapability() { DynamicRegistration = true }, - Hover = new HoverCapability() { DynamicRegistration = true }, - OnTypeFormatting = new DocumentOnTypeFormattingCapability() { DynamicRegistration = true }, - RangeFormatting = new DocumentRangeFormattingCapability() { DynamicRegistration = true }, - References = new ReferenceCapability() { DynamicRegistration = true }, - Rename = new RenameCapability() { DynamicRegistration = true }, - SignatureHelp = new SignatureHelpCapability() { DynamicRegistration = true }, - Completion = new CompletionCapability() - { + var model = new InitializeParams { + Capabilities = new ClientCapabilities { + Experimental = new Dictionary { { "abc", "test" } }, + TextDocument = new TextDocumentClientCapabilities { + CodeAction = new CodeActionCapability { DynamicRegistration = true }, + CodeLens = new CodeLensCapability { DynamicRegistration = true }, + Definition = new DefinitionCapability { DynamicRegistration = true }, + DocumentHighlight = new DocumentHighlightCapability { DynamicRegistration = true }, + DocumentLink = new DocumentLinkCapability { DynamicRegistration = true }, + DocumentSymbol = new DocumentSymbolCapability { DynamicRegistration = true }, + Formatting = new DocumentFormattingCapability { DynamicRegistration = true }, + Hover = new HoverCapability { DynamicRegistration = true }, + OnTypeFormatting = new DocumentOnTypeFormattingCapability { DynamicRegistration = true }, + RangeFormatting = new DocumentRangeFormattingCapability { DynamicRegistration = true }, + References = new ReferenceCapability { DynamicRegistration = true }, + Rename = new RenameCapability { DynamicRegistration = true }, + SignatureHelp = new SignatureHelpCapability { DynamicRegistration = true }, + Completion = new CompletionCapability { DynamicRegistration = true, - CompletionItem = new CompletionItemCapability() - { + CompletionItem = new CompletionItemCapability { SnippetSupport = true } }, - Synchronization = new SynchronizationCapability() - { + Synchronization = new SynchronizationCapability { DynamicRegistration = true, WillSave = true, DidSave = true, WillSaveWaitUntil = true }, - FoldingRange = new FoldingRangeCapability - { + FoldingRange = new FoldingRangeCapability { DynamicRegistration = true, LineFoldingOnly = true, RangeLimit = 5000, } }, - Workspace = new WorkspaceClientCapabilities() - { + Workspace = new WorkspaceClientCapabilities { ApplyEdit = true, - DidChangeConfiguration = new DidChangeConfigurationCapability() { DynamicRegistration = true }, - DidChangeWatchedFiles = new DidChangeWatchedFilesCapability() { DynamicRegistration = true }, - ExecuteCommand = new ExecuteCommandCapability() { DynamicRegistration = true }, - Symbol = new WorkspaceSymbolCapability() { DynamicRegistration = true }, - + DidChangeConfiguration = new DidChangeConfigurationCapability { DynamicRegistration = true }, + DidChangeWatchedFiles = new DidChangeWatchedFilesCapability { DynamicRegistration = true }, + ExecuteCommand = new ExecuteCommandCapability { DynamicRegistration = true }, + Symbol = new WorkspaceSymbolCapability { DynamicRegistration = true }, } }, InitializationOptions = null, diff --git a/test/Lsp.Tests/Models/InitializeResultTests.cs b/test/Lsp.Tests/Models/InitializeResultTests.cs index 9939e73d6..56cdded3c 100644 --- a/test/Lsp.Tests/Models/InitializeResultTests.cs +++ b/test/Lsp.Tests/Models/InitializeResultTests.cs @@ -11,62 +11,55 @@ namespace Lsp.Tests.Models { public class InitializeResultTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new InitializeResult() - { - Capabilities = new ServerCapabilities() - { + var model = new InitializeResult { + Capabilities = new ServerCapabilities { CodeActionProvider = true, - CodeLensProvider = new CodeLensOptions() - { + CodeLensProvider = new CodeLensOptions { ResolveProvider = true, }, - CompletionProvider = new CompletionOptions() - { + CompletionProvider = new CompletionOptions { ResolveProvider = true, TriggerCharacters = new[] { "a", "b", "c" } }, DefinitionProvider = true, DocumentFormattingProvider = true, DocumentHighlightProvider = true, - DocumentLinkProvider = new DocumentLinkOptions() - { + DocumentLinkProvider = new DocumentLinkOptions { ResolveProvider = true }, - DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions() - { + DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = ".", MoreTriggerCharacter = new[] { ";", " " } }, DocumentRangeFormattingProvider = true, DocumentSymbolProvider = true, - ExecuteCommandProvider = new ExecuteCommandOptions() - { - Commands = new string[] { "command1", "command2" } + ExecuteCommandProvider = new ExecuteCommandOptions { + Commands = new[] { "command1", "command2" } + }, + Experimental = new Dictionary { + { "abc", "123" } }, - Experimental = new Dictionary() { - { "abc", "123" } - }, HoverProvider = true, ReferencesProvider = true, RenameProvider = true, - SignatureHelpProvider = new SignatureHelpOptions() - { + SignatureHelpProvider = new SignatureHelpOptions { TriggerCharacters = new[] { ";", " " } }, - TextDocumentSync = new TextDocumentSync(new TextDocumentSyncOptions() - { - Change = TextDocumentSyncKind.Full, - OpenClose = true, - Save = new SaveOptions() - { - IncludeText = true - }, - WillSave = true, - WillSaveWaitUntil = true - }), + TextDocumentSync = new TextDocumentSync( + new TextDocumentSyncOptions { + Change = TextDocumentSyncKind.Full, + OpenClose = true, + Save = new SaveOptions { + IncludeText = true + }, + WillSave = true, + WillSaveWaitUntil = true + } + ), WorkspaceSymbolProvider = true, } }; @@ -78,45 +71,37 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void BooleanOrTest(string expected) { - var model = new InitializeResult() - { - Capabilities = new ServerCapabilities - { - CodeActionProvider = new CodeActionOptions - { + var model = new InitializeResult { + Capabilities = new ServerCapabilities { + CodeActionProvider = new CodeActionOptions { CodeActionKinds = new[] { CodeActionKind.QuickFix } }, - ColorProvider = new DocumentColorOptions - { + ColorProvider = new DocumentColorOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.foo"), Id = "foo" }, - DeclarationProvider = new DeclarationOptions - { + DeclarationProvider = new DeclarationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.foo"), Id = "foo" }, - FoldingRangeProvider = new FoldingRangeOptions - { + FoldingRangeProvider = new FoldingRangeOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.foo"), Id = "foo" }, - ImplementationProvider = new ImplementationOptions - { + ImplementationProvider = new ImplementationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.foo"), Id = "foo" }, - RenameProvider = new RenameOptions - { + RenameProvider = new RenameOptions { PrepareProvider = true }, - TypeDefinitionProvider = new TypeDefinitionOptions - { + TypeDefinitionProvider = new TypeDefinitionOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.foo"), Id = "foo" } diff --git a/test/Lsp.Tests/Models/InsertTextFormatTests.cs b/test/Lsp.Tests/Models/InsertTextFormatTests.cs index 3cd846380..f99322562 100644 --- a/test/Lsp.Tests/Models/InsertTextFormatTests.cs +++ b/test/Lsp.Tests/Models/InsertTextFormatTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Models { public class InsertTextFormatTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new InsertTextFormat(); diff --git a/test/Lsp.Tests/Models/LocationOrLocationLinksTests.cs b/test/Lsp.Tests/Models/LocationOrLocationLinksTests.cs index 77695ea58..f66680098 100644 --- a/test/Lsp.Tests/Models/LocationOrLocationLinksTests.cs +++ b/test/Lsp.Tests/Models/LocationOrLocationLinksTests.cs @@ -10,7 +10,8 @@ namespace Lsp.Tests.Models { public class LocationOrLocationLinksTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new LocationOrLocationLinks(); @@ -22,14 +23,15 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void LocationTest(string expected) { - var model = new LocationOrLocationLinks(new Location() - { - Range = new Range(new Position(1, 1), new Position(3, 3)), - - }); + var model = new LocationOrLocationLinks( + new Location { + Range = new Range(new Position(1, 1), new Position(3, 3)), + } + ); var result = Fixture.SerializeObject(model); result.Should().Be(expected); @@ -38,18 +40,17 @@ public void LocationTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void LocationsTest(string expected) { - var model = new LocationOrLocationLinks(new Location() - { - Range = new Range(new Position(1, 1), new Position(3, 3)), - - }, new Location() - { - Range = new Range(new Position(1, 1), new Position(3, 3)), - - }); + var model = new LocationOrLocationLinks( + new Location { + Range = new Range(new Position(1, 1), new Position(3, 3)), + }, new Location { + Range = new Range(new Position(1, 1), new Position(3, 3)), + } + ); var result = Fixture.SerializeObject(model); result.Should().Be(expected); @@ -58,54 +59,57 @@ public void LocationsTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void LocationLinkTest(string expected) { - var model = new LocationOrLocationLinks(new LocationLink() - { - TargetSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), - TargetRange = new Range(new Position(1, 1), new Position(3, 3)), - TargetUri = new Uri("file:///asdfasdf/a.tst"), - OriginSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), - }); + var model = new LocationOrLocationLinks( + new LocationLink { + TargetSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), + TargetRange = new Range(new Position(1, 1), new Position(3, 3)), + TargetUri = new Uri("file:///asdfasdf/a.tst"), + OriginSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), + } + ); var result = Fixture.SerializeObject(model); result.Should().Be(expected); var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x - .ComparingByMembers() + deresult.Should().BeEquivalentTo( + model, x => x + .ComparingByMembers() ); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void LocationLinksTest(string expected) { - var model = new LocationOrLocationLinks(new LocationLink() - { - TargetSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), - TargetRange = new Range(new Position(1, 1), new Position(3, 3)), - TargetUri = new Uri("file:///asdfasdf/a.tst"), - OriginSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), - - }, - new LocationLink() - { - TargetSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), - TargetRange = new Range(new Position(1, 1), new Position(3, 3)), - TargetUri = new Uri("file:///asdfasdf/a.tst"), - OriginSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), - - }); + var model = new LocationOrLocationLinks( + new LocationLink { + TargetSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), + TargetRange = new Range(new Position(1, 1), new Position(3, 3)), + TargetUri = new Uri("file:///asdfasdf/a.tst"), + OriginSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), + }, + new LocationLink { + TargetSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), + TargetRange = new Range(new Position(1, 1), new Position(3, 3)), + TargetUri = new Uri("file:///asdfasdf/a.tst"), + OriginSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), + } + ); var result = Fixture.SerializeObject(model); result.Should().Be(expected); var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x - .ComparingByMembers() - .ComparingByMembers() - .ComparingByMembers() + deresult.Should().BeEquivalentTo( + model, x => x + .ComparingByMembers() + .ComparingByMembers() + .ComparingByMembers() ); } } diff --git a/test/Lsp.Tests/Models/LocationTests.cs b/test/Lsp.Tests/Models/LocationTests.cs index fe10494f5..2b5d44879 100644 --- a/test/Lsp.Tests/Models/LocationTests.cs +++ b/test/Lsp.Tests/Models/LocationTests.cs @@ -10,11 +10,12 @@ namespace Lsp.Tests.Models { public class LocationTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new Location() { - Range = new Range(new Position(1,2), new Position(3,4)), + var model = new Location { + Range = new Range(new Position(1, 2), new Position(3, 4)), Uri = new Uri("file:///abc/123.cs") }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/LogMessageParamsTests.cs b/test/Lsp.Tests/Models/LogMessageParamsTests.cs index 1aaa7cf2e..3c759cafc 100644 --- a/test/Lsp.Tests/Models/LogMessageParamsTests.cs +++ b/test/Lsp.Tests/Models/LogMessageParamsTests.cs @@ -8,10 +8,11 @@ namespace Lsp.Tests.Models { public class LogMessageParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new LogMessageParams() { + var model = new LogMessageParams { Message = "message", Type = MessageType.Error }; diff --git a/test/Lsp.Tests/Models/MarkedStringTests.cs b/test/Lsp.Tests/Models/MarkedStringTests.cs index ad2e9fa56..d028b1815 100644 --- a/test/Lsp.Tests/Models/MarkedStringTests.cs +++ b/test/Lsp.Tests/Models/MarkedStringTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Models { public class MarkedStringTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new MarkedString("csharp", "some documented text..."); diff --git a/test/Lsp.Tests/Models/MessageActionItemTests.cs b/test/Lsp.Tests/Models/MessageActionItemTests.cs index 478c082a7..bf9125bc4 100644 --- a/test/Lsp.Tests/Models/MessageActionItemTests.cs +++ b/test/Lsp.Tests/Models/MessageActionItemTests.cs @@ -8,10 +8,11 @@ namespace Lsp.Tests.Models { public class MessageActionItemTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new MessageActionItem() { + var model = new MessageActionItem { Title = "abc" }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/MessageTypeTests.cs b/test/Lsp.Tests/Models/MessageTypeTests.cs index 020325f56..664b50b32 100644 --- a/test/Lsp.Tests/Models/MessageTypeTests.cs +++ b/test/Lsp.Tests/Models/MessageTypeTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Models { public class MessageTypeTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new MessageType(); diff --git a/test/Lsp.Tests/Models/ParameterInformationTests.cs b/test/Lsp.Tests/Models/ParameterInformationTests.cs index 780e86d83..958c94d91 100644 --- a/test/Lsp.Tests/Models/ParameterInformationTests.cs +++ b/test/Lsp.Tests/Models/ParameterInformationTests.cs @@ -8,10 +8,11 @@ namespace Lsp.Tests.Models { public class ParameterInformationTests { - [Theory, JsonFixture] - public void SimpleTest(string expected) + [Theory] + [JsonFixture] + public void SimpleTest(string expected) { - var model = new ParameterInformation() { + var model = new ParameterInformation { Documentation = "docs", Label = "label" }; diff --git a/test/Lsp.Tests/Models/PositionTests.cs b/test/Lsp.Tests/Models/PositionTests.cs index cc8348674..360224333 100644 --- a/test/Lsp.Tests/Models/PositionTests.cs +++ b/test/Lsp.Tests/Models/PositionTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Models { public class PositionTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new Position(1, 1); diff --git a/test/Lsp.Tests/Models/PublishDiagnosticsParamsTests.cs b/test/Lsp.Tests/Models/PublishDiagnosticsParamsTests.cs index 14b001103..6fa65a971 100644 --- a/test/Lsp.Tests/Models/PublishDiagnosticsParamsTests.cs +++ b/test/Lsp.Tests/Models/PublishDiagnosticsParamsTests.cs @@ -10,13 +10,14 @@ namespace Lsp.Tests.Models { public class PublishDiagnosticsParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new PublishDiagnosticsParams() { + var model = new PublishDiagnosticsParams { Uri = new Uri("file:///abc/123.cs"), Diagnostics = new[] { - new Diagnostic() { + new Diagnostic { Code = new DiagnosticCode("abcd"), Message = "message", Range = new Range(new Position(1, 1), new Position(2, 2)), diff --git a/test/Lsp.Tests/Models/RangeTests.cs b/test/Lsp.Tests/Models/RangeTests.cs index 776baa360..17e63b385 100644 --- a/test/Lsp.Tests/Models/RangeTests.cs +++ b/test/Lsp.Tests/Models/RangeTests.cs @@ -3,13 +3,13 @@ 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 { public class RangeTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new Range(new Position(1, 1), new Position(2, 2)); diff --git a/test/Lsp.Tests/Models/ReferenceContextTests.cs b/test/Lsp.Tests/Models/ReferenceContextTests.cs index 2a297fe0c..16acce1ed 100644 --- a/test/Lsp.Tests/Models/ReferenceContextTests.cs +++ b/test/Lsp.Tests/Models/ReferenceContextTests.cs @@ -8,10 +8,11 @@ namespace Lsp.Tests.Models { public class ReferenceContextTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new ReferenceContext() { + var model = new ReferenceContext { IncludeDeclaration = true }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/ReferenceParamsTests.cs b/test/Lsp.Tests/Models/ReferenceParamsTests.cs index 00c2b63c6..74662e3e2 100644 --- a/test/Lsp.Tests/Models/ReferenceParamsTests.cs +++ b/test/Lsp.Tests/Models/ReferenceParamsTests.cs @@ -9,14 +9,15 @@ namespace Lsp.Tests.Models { public class ReferenceParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new ReferenceParams() { - Context = new ReferenceContext() { + var model = new ReferenceParams { + Context = new ReferenceContext { IncludeDeclaration = true, }, - Position = new Position(1,2), + Position = new Position(1, 2), TextDocument = new TextDocumentIdentifier(new Uri("file:///abc/123.cs")) }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/RegistrationParamsTests.cs b/test/Lsp.Tests/Models/RegistrationParamsTests.cs index 16bcc27d2..09811adf0 100644 --- a/test/Lsp.Tests/Models/RegistrationParamsTests.cs +++ b/test/Lsp.Tests/Models/RegistrationParamsTests.cs @@ -9,15 +9,18 @@ namespace Lsp.Tests.Models { public class RegistrationParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new RegistrationParams() { - Registrations = new[] { new Registration() { - Id = "abc", - Method = "method", - RegisterOptions = new Dictionary() - } } + var model = new RegistrationParams { + Registrations = new[] { + new Registration { + Id = "abc", + Method = "method", + RegisterOptions = new Dictionary() + } + } }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/RegistrationTests.cs b/test/Lsp.Tests/Models/RegistrationTests.cs index 5dfd5e873..f1cc13699 100644 --- a/test/Lsp.Tests/Models/RegistrationTests.cs +++ b/test/Lsp.Tests/Models/RegistrationTests.cs @@ -9,10 +9,11 @@ namespace Lsp.Tests.Models { public class RegistrationTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new Registration() { + var model = new Registration { Id = "abc", Method = "method", RegisterOptions = new Dictionary() diff --git a/test/Lsp.Tests/Models/RenameParamsTests.cs b/test/Lsp.Tests/Models/RenameParamsTests.cs index ea23a79cb..388b0e667 100644 --- a/test/Lsp.Tests/Models/RenameParamsTests.cs +++ b/test/Lsp.Tests/Models/RenameParamsTests.cs @@ -9,10 +9,11 @@ namespace Lsp.Tests.Models { public class RenameParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new RenameParams() { + var model = new RenameParams { NewName = "new name", Position = new Position(1, 2), TextDocument = new TextDocumentIdentifier(new Uri("file:///abc/123.cs")) diff --git a/test/Lsp.Tests/Models/ShowMessageParamsTests.cs b/test/Lsp.Tests/Models/ShowMessageParamsTests.cs index 8a6e019cf..35725cc22 100644 --- a/test/Lsp.Tests/Models/ShowMessageParamsTests.cs +++ b/test/Lsp.Tests/Models/ShowMessageParamsTests.cs @@ -8,10 +8,11 @@ namespace Lsp.Tests.Models { public class ShowMessageParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new ShowMessageParams() { + var model = new ShowMessageParams { Message = "message", Type = MessageType.Log }; diff --git a/test/Lsp.Tests/Models/ShowMessageRequestParamsTests.cs b/test/Lsp.Tests/Models/ShowMessageRequestParamsTests.cs index 2df783fc6..dc391dddf 100644 --- a/test/Lsp.Tests/Models/ShowMessageRequestParamsTests.cs +++ b/test/Lsp.Tests/Models/ShowMessageRequestParamsTests.cs @@ -8,14 +8,17 @@ namespace Lsp.Tests.Models { public class ShowMessageRequestParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new ShowMessageRequestParams() { + var model = new ShowMessageRequestParams { Message = "message", - Actions = new Container(new MessageActionItem() { - Title = "abc" - }), + Actions = new Container( + new MessageActionItem { + Title = "abc" + } + ), Type = MessageType.Error }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/SignatureHelpRegistrationOptionsTests.cs b/test/Lsp.Tests/Models/SignatureHelpRegistrationOptionsTests.cs index 7f202db5b..75d8ca3cf 100644 --- a/test/Lsp.Tests/Models/SignatureHelpRegistrationOptionsTests.cs +++ b/test/Lsp.Tests/Models/SignatureHelpRegistrationOptionsTests.cs @@ -8,14 +8,17 @@ namespace Lsp.Tests.Models { public class SignatureHelpRegistrationOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new SignatureHelpRegistrationOptions() { - DocumentSelector = new DocumentSelector(new DocumentFilter() { - Language = "csharp" - }), - TriggerCharacters = new [] {"a","b"} + var model = new SignatureHelpRegistrationOptions { + DocumentSelector = new DocumentSelector( + new DocumentFilter { + Language = "csharp" + } + ), + TriggerCharacters = new[] { "a", "b" } }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/SignatureHelpTests.cs b/test/Lsp.Tests/Models/SignatureHelpTests.cs index fb52f9fa4..6529a0b1f 100644 --- a/test/Lsp.Tests/Models/SignatureHelpTests.cs +++ b/test/Lsp.Tests/Models/SignatureHelpTests.cs @@ -8,20 +8,24 @@ namespace Lsp.Tests.Models { public class SignatureHelpTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new SignatureHelp() { + var model = new SignatureHelp { ActiveParameter = 1, ActiveSignature = 2, - Signatures = new[] { new SignatureInformation() { - Documentation = "ab", - Label = "ab", - Parameters = new[] { new ParameterInformation() { - Documentation = "param", - Label = "param" - } } - } + Signatures = new[] { + new SignatureInformation { + Documentation = "ab", + Label = "ab", + Parameters = new[] { + new ParameterInformation { + Documentation = "param", + Label = "param" + } + } + } } }; var result = Fixture.SerializeObject(model); @@ -32,7 +36,8 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void NoSignaturesTest(string expected) { var model = new SignatureHelp(); diff --git a/test/Lsp.Tests/Models/SignatureInformationTests.cs b/test/Lsp.Tests/Models/SignatureInformationTests.cs index b8639e1be..30d7ee2fe 100644 --- a/test/Lsp.Tests/Models/SignatureInformationTests.cs +++ b/test/Lsp.Tests/Models/SignatureInformationTests.cs @@ -9,16 +9,19 @@ namespace Lsp.Tests.Models { public class SignatureInformationTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new SignatureInformation() { + var model = new SignatureInformation { Documentation = "ab", Label = "ab", - Parameters = new[] { new ParameterInformation() { - Documentation = "param", - Label = "param" - } } + Parameters = new[] { + new ParameterInformation { + Documentation = "param", + Label = "param" + } + } }; var result = Fixture.SerializeObject(model); @@ -28,43 +31,50 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void ParamRangeTest(string expected) { - var model = new SignatureInformation() { + var model = new SignatureInformation { Documentation = "ab", Label = "ab", - Parameters = new[] { new ParameterInformation() { - Documentation = "param", - Label = (1, 2) - } } + Parameters = new[] { + new ParameterInformation { + Documentation = "param", + Label = ( 1, 2 ) + } + } }; var result = Fixture.SerializeObject(model); result.Should().Be(expected); var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x - .ComparingByMembers>() - .ComparingByMembers() - .ComparingByMembers() - .ComparingByMembers() + deresult.Should().BeEquivalentTo( + model, x => x + .ComparingByMembers>() + .ComparingByMembers() + .ComparingByMembers() + .ComparingByMembers() ); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void MarkupContentTest(string expected) { - var model = new SignatureInformation() { + var model = new SignatureInformation { Documentation = "ab", Label = "ab", - Parameters = new[] { new ParameterInformation() { - Documentation = new MarkupContent() { - Kind = MarkupKind.Markdown, - Value = "### Value" - }, - Label = "param" - } } + Parameters = new[] { + new ParameterInformation { + Documentation = new MarkupContent { + Kind = MarkupKind.Markdown, + Value = "### Value" + }, + Label = "param" + } + } }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/SymbolKindTests.cs b/test/Lsp.Tests/Models/SymbolKindTests.cs index 883c71178..e3943b94e 100644 --- a/test/Lsp.Tests/Models/SymbolKindTests.cs +++ b/test/Lsp.Tests/Models/SymbolKindTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Models { public class SymbolKindTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new SymbolKind(); diff --git a/test/Lsp.Tests/Models/TextDocumentChangeRegistrationOptionsTests.cs b/test/Lsp.Tests/Models/TextDocumentChangeRegistrationOptionsTests.cs index ca9a6ddbc..53e646a2d 100644 --- a/test/Lsp.Tests/Models/TextDocumentChangeRegistrationOptionsTests.cs +++ b/test/Lsp.Tests/Models/TextDocumentChangeRegistrationOptionsTests.cs @@ -9,13 +9,16 @@ namespace Lsp.Tests.Models { public class TextDocumentChangeRegistrationOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new TextDocumentChangeRegistrationOptions() { - DocumentSelector = new DocumentSelector(new DocumentFilter() { - Language = "csharp" - }), + var model = new TextDocumentChangeRegistrationOptions { + DocumentSelector = new DocumentSelector( + new DocumentFilter { + Language = "csharp" + } + ), SyncKind = TextDocumentSyncKind.Full }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/TextDocumentContentChangeEventTests.cs b/test/Lsp.Tests/Models/TextDocumentContentChangeEventTests.cs index f07811bbf..1ff528e13 100644 --- a/test/Lsp.Tests/Models/TextDocumentContentChangeEventTests.cs +++ b/test/Lsp.Tests/Models/TextDocumentContentChangeEventTests.cs @@ -3,16 +3,16 @@ 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 { public class TextDocumentContentChangeEventTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new TextDocumentContentChangeEvent() { + var model = new TextDocumentContentChangeEvent { Range = new Range(new Position(1, 2), new Position(3, 4)), RangeLength = 12, Text = "abc" diff --git a/test/Lsp.Tests/Models/TextDocumentEditTests.cs b/test/Lsp.Tests/Models/TextDocumentEditTests.cs index ee0ae2eef..7ed399e81 100644 --- a/test/Lsp.Tests/Models/TextDocumentEditTests.cs +++ b/test/Lsp.Tests/Models/TextDocumentEditTests.cs @@ -10,24 +10,23 @@ namespace Lsp.Tests.Models { public class TextDocumentEditTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new TextDocumentEdit() - { - TextDocument = new VersionedTextDocumentIdentifier() - { + var model = new TextDocumentEdit { + TextDocument = new VersionedTextDocumentIdentifier { Version = 1, Uri = new Uri("file:///abc/123/d.cs"), }, Edits = new[] { - new TextEdit() { + new TextEdit { NewText = "new text", - Range = new Range(new Position(1, 1), new Position(2,2)) + Range = new Range(new Position(1, 1), new Position(2, 2)) }, - new TextEdit() { + new TextEdit { NewText = "new text2", - Range = new Range(new Position(3, 3), new Position(4,4)) + Range = new Range(new Position(3, 3), new Position(4, 4)) } } }; diff --git a/test/Lsp.Tests/Models/TextDocumentIdentifierTests.cs b/test/Lsp.Tests/Models/TextDocumentIdentifierTests.cs index 2e7734525..f6f444a1f 100644 --- a/test/Lsp.Tests/Models/TextDocumentIdentifierTests.cs +++ b/test/Lsp.Tests/Models/TextDocumentIdentifierTests.cs @@ -10,7 +10,8 @@ namespace Lsp.Tests.Models { public class TextDocumentIdentifierTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new TextDocumentIdentifier(new Uri("file:///abc/123/d.cs")); @@ -26,11 +27,17 @@ public void SimpleTest(string expected) public void Should_Deserialize_For_Example_Value() { var serializer = new Serializer(ClientVersion.Lsp3); - var result = serializer.DeserializeObject(@"{ + var result = serializer.DeserializeObject( + @"{ ""uri"":""file:///Users/tyler/Code/PowerShell/vscode/PowerShellEditorServices/test/PowerShellEditorServices.Test.E2E/bin/Debug/netcoreapp3.1/0b0jnxg2.kgh.ps1"" - }"); + }" + ); - result.Uri.Should().Be(DocumentUri.Parse("file:///Users/tyler/Code/PowerShell/vscode/PowerShellEditorServices/test/PowerShellEditorServices.Test.E2E/bin/Debug/netcoreapp3.1/0b0jnxg2.kgh.ps1")); + result.Uri.Should().Be( + DocumentUri.Parse( + "file:///Users/tyler/Code/PowerShell/vscode/PowerShellEditorServices/test/PowerShellEditorServices.Test.E2E/bin/Debug/netcoreapp3.1/0b0jnxg2.kgh.ps1" + ) + ); } } } diff --git a/test/Lsp.Tests/Models/TextDocumentItemTests.cs b/test/Lsp.Tests/Models/TextDocumentItemTests.cs index 09acdb379..e701e392f 100644 --- a/test/Lsp.Tests/Models/TextDocumentItemTests.cs +++ b/test/Lsp.Tests/Models/TextDocumentItemTests.cs @@ -9,10 +9,11 @@ namespace Lsp.Tests.Models { public class TextDocumentItemTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new TextDocumentItem() { + var model = new TextDocumentItem { Uri = new Uri("file:///abc/def.cs"), LanguageId = "csharp", Text = "content", diff --git a/test/Lsp.Tests/Models/TextDocumentPositionParamsTests.cs b/test/Lsp.Tests/Models/TextDocumentPositionParamsTests.cs index b5112a567..d6e4292dc 100644 --- a/test/Lsp.Tests/Models/TextDocumentPositionParamsTests.cs +++ b/test/Lsp.Tests/Models/TextDocumentPositionParamsTests.cs @@ -9,10 +9,11 @@ namespace Lsp.Tests.Models { public class TextDocumentPositionParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new TextDocumentPositionParams() { + var model = new TextDocumentPositionParams { Position = new Position(1, 2), TextDocument = new TextDocumentIdentifier(new Uri("file:///abc/123.cs")) }; diff --git a/test/Lsp.Tests/Models/TextDocumentRegistrationOptionsTests.cs b/test/Lsp.Tests/Models/TextDocumentRegistrationOptionsTests.cs index 1262028d1..254239866 100644 --- a/test/Lsp.Tests/Models/TextDocumentRegistrationOptionsTests.cs +++ b/test/Lsp.Tests/Models/TextDocumentRegistrationOptionsTests.cs @@ -8,13 +8,16 @@ namespace Lsp.Tests.Models { public class TextDocumentRegistrationOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new TextDocumentRegistrationOptions() { - DocumentSelector = new DocumentSelector(new DocumentFilter() { - Language = "csharp" - }) + var model = new TextDocumentRegistrationOptions { + DocumentSelector = new DocumentSelector( + new DocumentFilter { + Language = "csharp" + } + ) }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/TextDocumentSaveReasonTests.cs b/test/Lsp.Tests/Models/TextDocumentSaveReasonTests.cs index 859aa801c..e85963871 100644 --- a/test/Lsp.Tests/Models/TextDocumentSaveReasonTests.cs +++ b/test/Lsp.Tests/Models/TextDocumentSaveReasonTests.cs @@ -8,7 +8,8 @@ namespace Lsp.Tests.Models { public class TextDocumentSaveReasonTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { var model = new TextDocumentSaveReason(); diff --git a/test/Lsp.Tests/Models/TextDocumentSaveRegistrationOptionsTests.cs b/test/Lsp.Tests/Models/TextDocumentSaveRegistrationOptionsTests.cs index 0ebbcdae3..a252ec9fe 100644 --- a/test/Lsp.Tests/Models/TextDocumentSaveRegistrationOptionsTests.cs +++ b/test/Lsp.Tests/Models/TextDocumentSaveRegistrationOptionsTests.cs @@ -8,13 +8,16 @@ namespace Lsp.Tests.Models { public class TextDocumentSaveRegistrationOptionsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new TextDocumentSaveRegistrationOptions() { - DocumentSelector = new DocumentSelector(new DocumentFilter() { - Language = "csharp" - }), + var model = new TextDocumentSaveRegistrationOptions { + DocumentSelector = new DocumentSelector( + new DocumentFilter { + Language = "csharp" + } + ), IncludeText = true }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/TextEditTests.cs b/test/Lsp.Tests/Models/TextEditTests.cs index 3c8198b4a..301f5fbe6 100644 --- a/test/Lsp.Tests/Models/TextEditTests.cs +++ b/test/Lsp.Tests/Models/TextEditTests.cs @@ -3,16 +3,16 @@ 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 { public class TextEditTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new TextEdit() { + var model = new TextEdit { NewText = "new text", Range = new Range(new Position(1, 1), new Position(2, 2)) }; diff --git a/test/Lsp.Tests/Models/UnregistrationParamsTests.cs b/test/Lsp.Tests/Models/UnregistrationParamsTests.cs index 783af0422..4cd83faef 100644 --- a/test/Lsp.Tests/Models/UnregistrationParamsTests.cs +++ b/test/Lsp.Tests/Models/UnregistrationParamsTests.cs @@ -8,16 +8,17 @@ namespace Lsp.Tests.Models { public class UnregistrationParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new UnregistrationParams() - { - Unregisterations = new UnregistrationContainer(new Unregistration() - { - Id = "abc", - Method = "ads" - }) + var model = new UnregistrationParams { + Unregisterations = new UnregistrationContainer( + new Unregistration { + Id = "abc", + Method = "ads" + } + ) }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/Models/UnregistrationTests.cs b/test/Lsp.Tests/Models/UnregistrationTests.cs index 7e20ea5d0..195d6d139 100644 --- a/test/Lsp.Tests/Models/UnregistrationTests.cs +++ b/test/Lsp.Tests/Models/UnregistrationTests.cs @@ -8,10 +8,11 @@ namespace Lsp.Tests.Models { public class UnregistrationTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new Unregistration() { + var model = new Unregistration { Id = "abc", Method = "ads" }; diff --git a/test/Lsp.Tests/Models/VersionedTextDocumentIdentifierTests.cs b/test/Lsp.Tests/Models/VersionedTextDocumentIdentifierTests.cs index 8a6c3a351..aa30ec553 100644 --- a/test/Lsp.Tests/Models/VersionedTextDocumentIdentifierTests.cs +++ b/test/Lsp.Tests/Models/VersionedTextDocumentIdentifierTests.cs @@ -9,11 +9,11 @@ namespace Lsp.Tests.Models { public class VersionedTextDocumentIdentifierTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new VersionedTextDocumentIdentifier() - { + var model = new VersionedTextDocumentIdentifier { Uri = new Uri("file:///abc/123.cs"), Version = 12 }; diff --git a/test/Lsp.Tests/Models/WillSaveTextDocumentParamsTests.cs b/test/Lsp.Tests/Models/WillSaveTextDocumentParamsTests.cs index a95dc644c..d15f71058 100644 --- a/test/Lsp.Tests/Models/WillSaveTextDocumentParamsTests.cs +++ b/test/Lsp.Tests/Models/WillSaveTextDocumentParamsTests.cs @@ -9,10 +9,11 @@ namespace Lsp.Tests.Models { public class WillSaveTextDocumentParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new WillSaveTextDocumentParams() { + var model = new WillSaveTextDocumentParams { Reason = TextDocumentSaveReason.FocusOut, TextDocument = new TextDocumentIdentifier(new Uri("file:///abc/123.cs")) }; diff --git a/test/Lsp.Tests/Models/WorkspaceEditTests.cs b/test/Lsp.Tests/Models/WorkspaceEditTests.cs index eb0ff84f7..03239b651 100644 --- a/test/Lsp.Tests/Models/WorkspaceEditTests.cs +++ b/test/Lsp.Tests/Models/WorkspaceEditTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using FluentAssertions; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; 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; using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; @@ -12,25 +12,25 @@ namespace Lsp.Tests.Models { public class WorkspaceEditTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new WorkspaceEdit() - { - Changes = new Dictionary>() { - { - new Uri("file:///abc/123/d.cs"), new [] { - new TextEdit() { - NewText = "new text", - Range = new Range(new Position(1, 1), new Position(2,2)) - }, - new TextEdit() { - NewText = "new text2", - Range = new Range(new Position(3, 3), new Position(4,4)) - } + var model = new WorkspaceEdit { + Changes = new Dictionary> { + { + new Uri("file:///abc/123/d.cs"), new[] { + new TextEdit { + NewText = "new text", + Range = new Range(new Position(1, 1), new Position(2, 2)) + }, + new TextEdit { + NewText = "new text2", + Range = new Range(new Position(3, 3), new Position(4, 4)) } } } + } }; var result = Fixture.SerializeObject(model); @@ -40,80 +40,77 @@ public void SimpleTest(string expected) deresult.Should().BeEquivalentTo(model); } - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void DocumentChangesTest(string expected) { - var model = new WorkspaceEdit() - { + var model = new WorkspaceEdit { DocumentChanges = new Container( - new TextDocumentEdit() - { - TextDocument = new VersionedTextDocumentIdentifier() - { - Version = 1, - Uri = new Uri("file:///abc/123/d.cs"), - }, - Edits = new[] { - new TextEdit() { - NewText = "new text", - Range = new Range(new Position(1, 1), new Position(2,2)) - }, - new TextEdit() { - NewText = "new text2", - Range = new Range(new Position(3, 3), new Position(4,4)) - } - } + new TextDocumentEdit { + TextDocument = new VersionedTextDocumentIdentifier { + Version = 1, + Uri = new Uri("file:///abc/123/d.cs"), }, - new TextDocumentEdit() - { - TextDocument = new VersionedTextDocumentIdentifier() - { - Version = 1, - Uri = new Uri("file:///abc/123/b.cs"), + Edits = new[] { + new TextEdit { + NewText = "new text", + Range = new Range(new Position(1, 1), new Position(2, 2)) }, - Edits = new[] { - new TextEdit() { - NewText = "new text2", - Range = new Range(new Position(1, 1), new Position(2,2)) - }, - new TextEdit() { - NewText = "new text3", - Range = new Range(new Position(3, 3), new Position(4,4)) - } - } - }, - new CreateFile() { - Uri = "file:///abc/123/b.cs", - Options = new CreateFileOptions() { - IgnoreIfExists = true, - Overwrite = true - } - }, - new RenameFile() { - OldUri = "file:///abc/123/b.cs", - NewUri = "file:///abc/123/c.cs", - Options = new RenameFileOptions() { - IgnoreIfExists = true, - Overwrite = true + new TextEdit { + NewText = "new text2", + Range = new Range(new Position(3, 3), new Position(4, 4)) } + } + }, + new TextDocumentEdit { + TextDocument = new VersionedTextDocumentIdentifier { + Version = 1, + Uri = new Uri("file:///abc/123/b.cs"), }, - new DeleteFile() { - Uri = "file:///abc/123/c.cs", - Options = new DeleteFileOptions() { - IgnoreIfNotExists = true, - Recursive = false + Edits = new[] { + new TextEdit { + NewText = "new text2", + Range = new Range(new Position(1, 1), new Position(2, 2)) + }, + new TextEdit { + NewText = "new text3", + Range = new Range(new Position(3, 3), new Position(4, 4)) } } - ) + }, + new CreateFile { + Uri = "file:///abc/123/b.cs", + Options = new CreateFileOptions { + IgnoreIfExists = true, + Overwrite = true + } + }, + new RenameFile { + OldUri = "file:///abc/123/b.cs", + NewUri = "file:///abc/123/c.cs", + Options = new RenameFileOptions { + IgnoreIfExists = true, + Overwrite = true + } + }, + new DeleteFile { + Uri = "file:///abc/123/c.cs", + Options = new DeleteFileOptions { + IgnoreIfNotExists = true, + Recursive = false + } + } + ) }; var result = Fixture.SerializeObject(model); result.Should().Be(expected); var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject(expected); - deresult.Should().BeEquivalentTo(model, x => x - .ComparingByMembers() - ); + deresult.Should().BeEquivalentTo( + model, x => x + .ComparingByMembers() + ); } } } diff --git a/test/Lsp.Tests/Models/WorkspaceSymbolInformationTests.cs b/test/Lsp.Tests/Models/WorkspaceSymbolInformationTests.cs index baa74ee28..f23e8fe52 100644 --- a/test/Lsp.Tests/Models/WorkspaceSymbolInformationTests.cs +++ b/test/Lsp.Tests/Models/WorkspaceSymbolInformationTests.cs @@ -10,13 +10,14 @@ namespace Lsp.Tests.Models { public class WorkspaceSymbolInformationTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new SymbolInformation() { + var model = new SymbolInformation { ContainerName = "abc", Kind = SymbolKind.Boolean, - Location = new Location() { + Location = new Location { Range = new Range(new Position(1, 2), new Position(3, 4)), Uri = new Uri("file:///abc/123.cs") }, diff --git a/test/Lsp.Tests/Models/WorkspaceSymbolParamsTests.cs b/test/Lsp.Tests/Models/WorkspaceSymbolParamsTests.cs index 070491cf1..4663e423f 100644 --- a/test/Lsp.Tests/Models/WorkspaceSymbolParamsTests.cs +++ b/test/Lsp.Tests/Models/WorkspaceSymbolParamsTests.cs @@ -8,10 +8,11 @@ namespace Lsp.Tests.Models { public class WorkspaceSymbolParamsTests { - [Theory, JsonFixture] + [Theory] + [JsonFixture] public void SimpleTest(string expected) { - var model = new WorkspaceSymbolParams() { + var model = new WorkspaceSymbolParams { Query = "query" }; var result = Fixture.SerializeObject(model); diff --git a/test/Lsp.Tests/RequestProcessIdentifierTests.cs b/test/Lsp.Tests/RequestProcessIdentifierTests.cs index 14dc4121d..638ed98f5 100644 --- a/test/Lsp.Tests/RequestProcessIdentifierTests.cs +++ b/test/Lsp.Tests/RequestProcessIdentifierTests.cs @@ -48,9 +48,9 @@ public void ShouldIdentifyAs_Default() [InlineData(typeof(ISignatureHelpHandler))] public void ShouldIdentifyAs_Parallel(Type type) { - var identifier = new RequestProcessIdentifier(RequestProcessType.Serial); + var identifier = new RequestProcessIdentifier(); var handler = Substitute.For(); - handler.Handler.Returns((IJsonRpcHandler)Substitute.For(new Type[] { type }, new object[0])); + handler.Handler.Returns((IJsonRpcHandler) Substitute.For(new[] { type }, new object[0])); handler.HandlerType.Returns(type); handler.ImplementationType.Returns(x => handler.Handler.GetType()); @@ -76,7 +76,7 @@ public void ShouldIdentifyAs_Serial(Type type) { var identifier = new RequestProcessIdentifier(RequestProcessType.Parallel); var handler = Substitute.For(); - handler.Handler.Returns((IJsonRpcHandler)Substitute.For(new Type[] { type }, new object[0])); + handler.Handler.Returns((IJsonRpcHandler) Substitute.For(new[] { type }, new object[0])); handler.HandlerType.Returns(type); handler.ImplementationType.Returns(x => handler.Handler.GetType()); diff --git a/test/Lsp.Tests/SemanticTokensDocumentTests.cs b/test/Lsp.Tests/SemanticTokensDocumentTests.cs index 3d3cffd35..151205df4 100644 --- a/test/Lsp.Tests/SemanticTokensDocumentTests.cs +++ b/test/Lsp.Tests/SemanticTokensDocumentTests.cs @@ -9,8 +9,8 @@ using Microsoft.Extensions.Logging; using NSubstitute; using OmniSharp.Extensions.LanguageServer.Protocol.Document.Proposals; -using OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals; using OmniSharp.Extensions.LanguageServer.Protocol.Models; +using OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals; using Xunit; using Xunit.Abstractions; using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; @@ -31,49 +31,49 @@ public SemanticTokensDocumentTests(ITestOutputHelper testOutputHelper) _testOutputHelper = testOutputHelper; _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") - } - .Select(z => z.ToString()) - .ToArray(), + 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") + } + .Select(z => z.ToString()) + .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"), - } - .Select(x => x.ToString()) - .ToArray(), + 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"), + } + .Select(x => x.ToString()) + .ToArray(), }; } @@ -129,12 +129,12 @@ public class ReturnDocumentTokensFromScratch_ForRange_Data : TheoryData expectedTokens) + public void ReturnDocumentEdits( + string originalText, string modifiedText, + IEnumerable expectedTokens + ) { var document = new SemanticTokensDocument(_legend); @@ -193,9 +195,11 @@ public void ReturnDocumentEdits(string originalText, string modifiedText, Tokenize(originalText, builder); builder.Commit(); originalTokens = document.GetSemanticTokens(); - builder = document.Edit(new SemanticTokensDeltaParams() { - PreviousResultId = document.Id, - }); + builder = document.Edit( + new SemanticTokensDeltaParams { + PreviousResultId = document.Id, + } + ); Tokenize(modifiedText, builder); builder.Commit(); } @@ -209,8 +213,8 @@ public void ReturnDocumentEdits(string originalText, string modifiedText, var edit1 = edits.Edits.First(); var edit1Tokens = originalTokens.Data - .RemoveRange(edit1.Start, edit1.DeleteCount) - .InsertRange(edit1.Start, edit1.Data); + .RemoveRange(edit1.Start, edit1.DeleteCount) + .InsertRange(edit1.Start, edit1.Data); var edit1Data = Normalize(modifiedText, edit1Tokens).ToArray(); _logger.LogDebug("Some Data {Data}", edit1Data.AsEnumerable()); @@ -234,14 +238,19 @@ public ReturnDocumentEdits_Data() "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)" - }); - Add("using", "using System;", + } + ); + Add( + "using", "using System;", new NormalizedToken[] { "using (macro:async|deprecated)", "System (macro:async|deprecated)" - }); - Add("using System;", "using", new NormalizedToken[] { - "using (macro:async|deprecated)" - }); + } + ); + Add( + "using System;", "using", new NormalizedToken[] { + "using (macro:async|deprecated)" + } + ); } } @@ -255,20 +264,23 @@ private class TokenizationValue private void Tokenize(string document, SemanticTokensBuilder builder) { var faker = new Faker() - .RuleFor(z => z.type, - f => f.PickRandom(SemanticTokenType.Defaults).OrNull(f, 0.2f) ?? new SemanticTokenType("none") - ) - .RuleFor(x => x.Modifiers, - f => Enumerable.Range(0, f.Random.Int(0, 3)) - .Select(z => - f.PickRandom(SemanticTokenModifier.Defaults).OrNull(f, 0.2f) ?? - new SemanticTokenModifier("none") + .RuleFor( + z => z.type, + f => f.PickRandom(SemanticTokenType.Defaults).OrNull(f, 0.2f) ?? new SemanticTokenType("none") ) - .ToArray() - .OrNull(f, 0.2f) - ); - - foreach (var (line, text) in document.Split('\n').Select((text, line) => (line, text))) + .RuleFor( + x => x.Modifiers, + f => Enumerable.Range(0, f.Random.Int(0, 3)) + .Select( + z => + f.PickRandom(SemanticTokenModifier.Defaults).OrNull(f, 0.2f) ?? + new SemanticTokenModifier("none") + ) + .ToArray() + .OrNull(f, 0.2f) + ); + + foreach (var (line, text) in document.Split('\n').Select((text, line) => ( line, text ))) { var parts = text.TrimEnd().Split(';', ' ', '.', '"', '(', ')'); var index = 0; @@ -287,7 +299,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); } } } @@ -318,16 +330,13 @@ public NormalizedToken(string text, SemanticTokenType type, params SemanticToken Modifiers = modifiers; } - public bool Equals(string other) - { - return string.Equals(ToString(), other); - } + public bool Equals(string other) => string.Equals(ToString(), other); public bool Equals(NormalizedToken other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; - return other.ToString() == this.ToString(); + return other.ToString() == ToString(); } public override bool Equals(object obj) @@ -370,8 +379,8 @@ public static implicit operator NormalizedToken(string value) item[0], other[0], other[1].Split('|') - .Select(x => new SemanticTokenModifier(x)) - .ToArray() + .Select(x => new SemanticTokenModifier(x)) + .ToArray() ); } @@ -388,13 +397,15 @@ private IReadOnlyList Normalize(string document, IReadOnlyList< { var parts = Decompose(values).ToArray(); return parts - .Select((item, index) => GetNormalizedToken(document, parts, index)) - .Where(z => z != null) - .ToArray(); + .Select((item, index) => GetNormalizedToken(document, parts, index)) + .Where(z => z != null) + .ToArray(); } - private NormalizedToken GetNormalizedToken(string document, - IReadOnlyList<(int lineOffset, int charOffset, int length, int type, int modifiers)> tokens, int tokenIndex) + private NormalizedToken GetNormalizedToken( + string document, + IReadOnlyList<(int lineOffset, int charOffset, int length, int type, int modifiers)> tokens, int tokenIndex + ) { var lines = document.Split('\n'); var lineIndex = 0; @@ -413,24 +424,26 @@ private NormalizedToken GetNormalizedToken(string document, return new NormalizedToken( line.Substring(characterOffset, textToken.length), _legend.TokenTypes - .Where((x, i) => i == textToken.type) - .Select(x => new SemanticTokenType(x)) - .First(), + .Where((x, i) => i == textToken.type) + .Select(x => new SemanticTokenType(x)) + .First(), _legend.TokenModifiers - .Where((x, i) => - (textToken.modifiers & Convert.ToInt32(Math.Pow(2, i))) == Convert.ToInt32(Math.Pow(2, i)) - ) - .Select(x => new SemanticTokenModifier(x)) - .ToArray() + .Where( + (x, i) => + ( textToken.modifiers & Convert.ToInt32(Math.Pow(2, i)) ) == Convert.ToInt32(Math.Pow(2, i)) + ) + .Select(x => new SemanticTokenModifier(x)) + .ToArray() ); } private static IEnumerable<(int lineOffset, int charOffset, int length, int type, int modifiers)> Decompose( - IReadOnlyList values) + 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/SupportedCapabilitiesFixture.cs b/test/Lsp.Tests/SupportedCapabilitiesFixture.cs index 45e81c887..d5d14c86b 100644 --- a/test/Lsp.Tests/SupportedCapabilitiesFixture.cs +++ b/test/Lsp.Tests/SupportedCapabilitiesFixture.cs @@ -10,7 +10,8 @@ public class SupportedCapabilitiesFixture { public static readonly ISupportedCapabilities AlwaysTrue = new AlwaysTrueSupportedCapabilities(); public static readonly ISupportedCapabilities AlwaysFalse = new AlwaysFalseSupportedCapabilities(); - class AlwaysTrueSupportedCapabilities : ISupportedCapabilities + + private class AlwaysTrueSupportedCapabilities : ISupportedCapabilities { public bool AllowsDynamicRegistration(ILspHandlerDescriptor descriptor) => true; @@ -25,7 +26,7 @@ public void Add(IEnumerable supports) } } - class AlwaysFalseSupportedCapabilities : ISupportedCapabilities + private class AlwaysFalseSupportedCapabilities : ISupportedCapabilities { public bool AllowsDynamicRegistration(ILspHandlerDescriptor descriptor) => false; diff --git a/test/Lsp.Tests/Testing/LanguageServerTestBaseTests.cs b/test/Lsp.Tests/Testing/LanguageServerTestBaseTests.cs index 66e20ca33..ee5535382 100644 --- a/test/Lsp.Tests/Testing/LanguageServerTestBaseTests.cs +++ b/test/Lsp.Tests/Testing/LanguageServerTestBaseTests.cs @@ -22,21 +22,17 @@ protected override (Stream clientOutput, Stream serverInput) SetupServer() var clientPipe = new Pipe(TestOptions.DefaultPipeOptions); var serverPipe = new Pipe(TestOptions.DefaultPipeOptions); - var server = LanguageServer.PreInit(options => { - options.WithInput(serverPipe.Reader).WithOutput(clientPipe.Writer); - }); + var server = LanguageServer.PreInit(options => { options.WithInput(serverPipe.Reader).WithOutput(clientPipe.Writer); }); server.Initialize(CancellationToken); - return (clientPipe.Reader.AsStream(), serverPipe.Writer.AsStream()); + return ( clientPipe.Reader.AsStream(), serverPipe.Writer.AsStream() ); } [Fact] public async Task Should_Connect_To_Server() { - var client = await InitializeClient(x => { - - }); + var client = await InitializeClient(x => { }); client.ClientSettings.Should().NotBeNull(); client.ServerSettings.Should().NotBeNull(); diff --git a/test/Lsp.Tests/TextDocumentSyncHandlerExtensions.cs b/test/Lsp.Tests/TextDocumentSyncHandlerExtensions.cs index d5279af5c..79b0cc530 100644 --- a/test/Lsp.Tests/TextDocumentSyncHandlerExtensions.cs +++ b/test/Lsp.Tests/TextDocumentSyncHandlerExtensions.cs @@ -1,29 +1,27 @@ using NSubstitute; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Document; +using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace Lsp.Tests { - static class TextDocumentSyncHandlerExtensions + internal static class TextDocumentSyncHandlerExtensions { - public static ITextDocumentSyncHandler With(DocumentSelector documentSelector, string language) - { - return Substitute.For().With(documentSelector, language); - } + public static ITextDocumentSyncHandler With(DocumentSelector documentSelector, string language) => + Substitute.For().With(documentSelector, language); public static ITextDocumentSyncHandler With(this ITextDocumentSyncHandler handler, DocumentSelector documentSelector, string language) { - ((IDidChangeTextDocumentHandler)handler).GetRegistrationOptions().Returns(new TextDocumentChangeRegistrationOptions() { DocumentSelector = documentSelector }); - ((IDidOpenTextDocumentHandler)handler).GetRegistrationOptions().Returns(new TextDocumentRegistrationOptions() { DocumentSelector = documentSelector }); - ((IDidCloseTextDocumentHandler)handler).GetRegistrationOptions().Returns(new TextDocumentRegistrationOptions() { DocumentSelector = documentSelector }); - ((IDidSaveTextDocumentHandler)handler).GetRegistrationOptions().Returns(new TextDocumentSaveRegistrationOptions() { DocumentSelector = documentSelector }); - ((ITextDocumentIdentifier) handler).GetTextDocumentAttributes(Arg.Any()) - .Returns(c => new TextDocumentAttributes(c.Arg(), language)); + ( (IDidChangeTextDocumentHandler) handler ).GetRegistrationOptions().Returns(new TextDocumentChangeRegistrationOptions { DocumentSelector = documentSelector }); + ( (IDidOpenTextDocumentHandler) handler ).GetRegistrationOptions().Returns(new TextDocumentRegistrationOptions { DocumentSelector = documentSelector }); + ( (IDidCloseTextDocumentHandler) handler ).GetRegistrationOptions().Returns(new TextDocumentRegistrationOptions { DocumentSelector = documentSelector }); + ( (IDidSaveTextDocumentHandler) handler ).GetRegistrationOptions().Returns(new TextDocumentSaveRegistrationOptions { DocumentSelector = documentSelector }); + handler.GetTextDocumentAttributes(Arg.Any()) + .Returns(c => new TextDocumentAttributes(c.Arg(), language)); handler - .GetTextDocumentAttributes(Arg.Is(x => documentSelector.IsMatch(new TextDocumentAttributes(x, language)))) - .Returns(c => new TextDocumentAttributes(c.Arg(), language)); + .GetTextDocumentAttributes(Arg.Is(x => documentSelector.IsMatch(new TextDocumentAttributes(x, language)))) + .Returns(c => new TextDocumentAttributes(c.Arg(), language)); return handler; } @@ -36,9 +34,7 @@ private static void For(this ITextDocumentSyncHandler handler, DocumentSelect } private static TextDocumentRegistrationOptions GetOptions(IRegistration handler, DocumentSelector documentSelector) - where R : TextDocumentRegistrationOptions, new() - { - return new R { DocumentSelector = documentSelector }; - } + where R : TextDocumentRegistrationOptions, new() => + new R { DocumentSelector = documentSelector }; } } diff --git a/test/Lsp.Tests/VsCodeDocumentUriTests.cs b/test/Lsp.Tests/VsCodeDocumentUriTests.cs index 1cd2ee789..3a16f8644 100644 --- a/test/Lsp.Tests/VsCodeDocumentUriTests.cs +++ b/test/Lsp.Tests/VsCodeDocumentUriTests.cs @@ -11,10 +11,7 @@ public class VsCodeDocumentUriTests { private readonly ITestOutputHelper _testOutputHelper; - public VsCodeDocumentUriTests(ITestOutputHelper testOutputHelper) - { - _testOutputHelper = testOutputHelper; - } + public VsCodeDocumentUriTests(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper; [Fact(DisplayName = "file#toString")] public void FileToString() @@ -70,52 +67,73 @@ public void URI_fsPath___no_fsPath_when_no_path() [Fact(DisplayName = "http#toString")] public void http_toString() { - DocumentUri.From(new DocumentUriComponents - {Scheme = "http", Authority = "www.msft.com", Path = "/my/path"}).ToString().Should().Be( - "http://www.msft.com/my/path"); - - DocumentUri.From(new DocumentUriComponents - {Scheme = "http", Authority = "www.msft.com", Path = "/my/path"}).ToString().Should().Be( - "http://www.msft.com/my/path"); - - DocumentUri.From(new DocumentUriComponents - {Scheme = "http", Authority = "www.MSFT.com", Path = "/my/path"}).ToString().Should().Be( - "http://www.msft.com/my/path"); - - DocumentUri.From(new DocumentUriComponents {Scheme = "http", Authority = "", Path = "my/path"}) - .ToString().Should().Be("http:/my/path"); - - DocumentUri.From(new DocumentUriComponents {Scheme = "http", Authority = "", Path = "/my/path"}) - .ToString().Should().Be("http:/my/path"); + DocumentUri.From( + new DocumentUriComponents + { Scheme = "http", Authority = "www.msft.com", Path = "/my/path" } + ).ToString().Should().Be( + "http://www.msft.com/my/path" + ); + + DocumentUri.From( + new DocumentUriComponents + { Scheme = "http", Authority = "www.msft.com", Path = "/my/path" } + ).ToString().Should().Be( + "http://www.msft.com/my/path" + ); + + DocumentUri.From( + new DocumentUriComponents + { Scheme = "http", Authority = "www.MSFT.com", Path = "/my/path" } + ).ToString().Should().Be( + "http://www.msft.com/my/path" + ); + + DocumentUri.From(new DocumentUriComponents { Scheme = "http", Authority = "", Path = "my/path" }) + .ToString().Should().Be("http:/my/path"); + + DocumentUri.From(new DocumentUriComponents { Scheme = "http", Authority = "", Path = "/my/path" }) + .ToString().Should().Be("http:/my/path"); //http://a-test-site.com/#test=true - DocumentUri.From(new DocumentUriComponents - {Scheme = "http", Authority = "a-test-site.com", Path = "/", Query = "test=true"}).ToString() - .Should() - .Be( - "http://a-test-site.com/?test%3Dtrue"); - - DocumentUri.From(new DocumentUriComponents { - Scheme = "http", Authority = "a-test-site.com", Path = "/", Query = "", Fragment = "test=true" - }) - .ToString().Should().Be("http://a-test-site.com/#test%3Dtrue"); + DocumentUri.From( + new DocumentUriComponents + { Scheme = "http", Authority = "a-test-site.com", Path = "/", Query = "test=true" } + ).ToString() + .Should() + .Be( + "http://a-test-site.com/?test%3Dtrue" + ); + + DocumentUri.From( + new DocumentUriComponents { + Scheme = "http", Authority = "a-test-site.com", Path = "/", Query = "", Fragment = "test=true" + } + ) + .ToString().Should().Be("http://a-test-site.com/#test%3Dtrue"); } [Fact(DisplayName = "http#toString, encode=FALSE")] public void http_toString__encode_FALSE() { - DocumentUri.From(new DocumentUriComponents - {Scheme = "http", Authority = "a-test-site.com", Path = "/", Query = "test=true"}) - .ToUnencodedString().Should().Be("http://a-test-site.com/?test=true"); - - DocumentUri.From(new DocumentUriComponents { - Scheme = "http", Authority = "a-test-site.com", Path = "/", Query = "", Fragment = "test=true" - }) - .ToUnencodedString().Should().Be("http://a-test-site.com/#test=true"); - - DocumentUri.From(new DocumentUriComponents - {Scheme = "http", Path = "/api/files/test.me", Query = "t=1234"}).ToUnencodedString().Should().Be( - "http:/api/files/test.me?t=1234"); + DocumentUri.From( + new DocumentUriComponents + { Scheme = "http", Authority = "a-test-site.com", Path = "/", Query = "test=true" } + ) + .ToUnencodedString().Should().Be("http://a-test-site.com/?test=true"); + + DocumentUri.From( + new DocumentUriComponents { + Scheme = "http", Authority = "a-test-site.com", Path = "/", Query = "", Fragment = "test=true" + } + ) + .ToUnencodedString().Should().Be("http://a-test-site.com/#test=true"); + + DocumentUri.From( + new DocumentUriComponents + { Scheme = "http", Path = "/api/files/test.me", Query = "t=1234" } + ).ToUnencodedString().Should().Be( + "http:/api/files/test.me?t=1234" + ); var value = DocumentUri.Parse("file://shares/pröjects/c%23/#l12"); value.Authority.Should().Be("shares"); @@ -137,69 +155,82 @@ public void with__identity() { var uri = DocumentUri.Parse("foo:bar/path"); - var uri2 = uri.With(new DocumentUriComponents { }); + var uri2 = uri.With(new DocumentUriComponents()); Assert.True(uri == uri2); - uri2 = uri.With(new DocumentUriComponents {Scheme = "foo", Path = "bar/path"}); + uri2 = uri.With(new DocumentUriComponents { Scheme = "foo", Path = "bar/path" }); Assert.True(uri == uri2); } [Fact(DisplayName = "with, changes")] public void with__changes() { - DocumentUri.Parse("before:some/file/path").With(new DocumentUriComponents {Scheme = "after"}) - .ToString().Should().Be("after:some/file/path"); - - DocumentUri.From(new DocumentUriComponents {Scheme = "s"}).With(new DocumentUriComponents - {Scheme = "http", Path = "/api/files/test.me", Query = "t=1234"}).ToString().Should().Be( - "http:/api/files/test.me?t%3D1234"); - - DocumentUri.From(new DocumentUriComponents {Scheme = "s"}).With(new DocumentUriComponents - {Scheme = "http", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = ""}) - .ToString().Should().Be("http:/api/files/test.me?t%3D1234"); - - DocumentUri.From(new DocumentUriComponents {Scheme = "s"}).With(new DocumentUriComponents { - Scheme = "https", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = "" - }) - .ToString().Should().Be("https:/api/files/test.me?t%3D1234"); - - DocumentUri.From(new DocumentUriComponents {Scheme = "s"}).With(new DocumentUriComponents - {Scheme = "HTTP", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = ""}) - .ToString().Should().Be("HTTP:/api/files/test.me?t%3D1234"); - - DocumentUri.From(new DocumentUriComponents {Scheme = "s"}).With(new DocumentUriComponents { - Scheme = "HTTPS", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = "" - }) - .ToString().Should().Be("HTTPS:/api/files/test.me?t%3D1234"); - - DocumentUri.From(new DocumentUriComponents {Scheme = "s"}).With(new DocumentUriComponents - {Scheme = "boo", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = ""}) - .ToString().Should().Be("boo:/api/files/test.me?t%3D1234"); + DocumentUri.Parse("before:some/file/path").With(new DocumentUriComponents { Scheme = "after" }) + .ToString().Should().Be("after:some/file/path"); + + DocumentUri.From(new DocumentUriComponents { Scheme = "s" }).With( + new DocumentUriComponents + { Scheme = "http", Path = "/api/files/test.me", Query = "t=1234" } + ).ToString().Should().Be( + "http:/api/files/test.me?t%3D1234" + ); + + DocumentUri.From(new DocumentUriComponents { Scheme = "s" }).With( + new DocumentUriComponents + { Scheme = "http", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = "" } + ) + .ToString().Should().Be("http:/api/files/test.me?t%3D1234"); + + DocumentUri.From(new DocumentUriComponents { Scheme = "s" }).With( + new DocumentUriComponents { + Scheme = "https", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = "" + } + ) + .ToString().Should().Be("https:/api/files/test.me?t%3D1234"); + + DocumentUri.From(new DocumentUriComponents { Scheme = "s" }).With( + new DocumentUriComponents + { Scheme = "HTTP", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = "" } + ) + .ToString().Should().Be("HTTP:/api/files/test.me?t%3D1234"); + + DocumentUri.From(new DocumentUriComponents { Scheme = "s" }).With( + new DocumentUriComponents { + Scheme = "HTTPS", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = "" + } + ) + .ToString().Should().Be("HTTPS:/api/files/test.me?t%3D1234"); + + DocumentUri.From(new DocumentUriComponents { Scheme = "s" }).With( + new DocumentUriComponents + { Scheme = "boo", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = "" } + ) + .ToString().Should().Be("boo:/api/files/test.me?t%3D1234"); } [Fact(DisplayName = "with, remove components #8465")] public void with__remove_components__8465() { - DocumentUri.Parse("scheme://authority/path").With(new DocumentUriComponents {Authority = ""}) - .ToString().Should().Be("scheme:/path"); + DocumentUri.Parse("scheme://authority/path").With(new DocumentUriComponents { Authority = "" }) + .ToString().Should().Be("scheme:/path"); - DocumentUri.Parse("scheme:/path").With(new DocumentUriComponents {Authority = "authority"}) - .With(new DocumentUriComponents {Authority = ""}).ToString().Should().Be("scheme:/path"); + DocumentUri.Parse("scheme:/path").With(new DocumentUriComponents { Authority = "authority" }) + .With(new DocumentUriComponents { Authority = "" }).ToString().Should().Be("scheme:/path"); - DocumentUri.Parse("scheme:/path").With(new DocumentUriComponents {Authority = "authority"}) - .With(new DocumentUriComponents {Path = ""}).ToString().Should().Be("scheme://authority"); + DocumentUri.Parse("scheme:/path").With(new DocumentUriComponents { Authority = "authority" }) + .With(new DocumentUriComponents { Path = "" }).ToString().Should().Be("scheme://authority"); - DocumentUri.Parse("scheme:/path").With(new DocumentUriComponents {Authority = ""}).ToString().Should() - .Be("scheme:/path"); + DocumentUri.Parse("scheme:/path").With(new DocumentUriComponents { Authority = "" }).ToString().Should() + .Be("scheme:/path"); } [Fact(DisplayName = "with, validation")] public void with_validation() { var uri = DocumentUri.Parse("foo:bar/path"); - Assert.Throws(() => uri.With(new DocumentUriComponents {Scheme = "fai:l"})); - Assert.Throws(() => uri.With(new DocumentUriComponents {Scheme = "fäil"})); - Assert.Throws(() => uri.With(new DocumentUriComponents {Authority = "fail"})); - Assert.Throws(() => uri.With(new DocumentUriComponents {Path = "//fail"})); + Assert.Throws(() => uri.With(new DocumentUriComponents { Scheme = "fai:l" })); + Assert.Throws(() => uri.With(new DocumentUriComponents { Scheme = "fäil" })); + Assert.Throws(() => uri.With(new DocumentUriComponents { Authority = "fail" })); + Assert.Throws(() => uri.With(new DocumentUriComponents { Path = "//fail" })); } [Fact(DisplayName = "parse")] @@ -236,11 +267,13 @@ public void Parse() value.GetFileSystemPath().Should().Be("\\\\shares\\files\\c#\\p.cs"); value = DocumentUri.Parse( - "file:///c:/Source/Z%C3%BCrich%20or%20Zurich%20(%CB%88zj%CA%8A%C9%99r%C9%AAk,/Code/resources/app/plugins/c%23/plugin.json"); + "file:///c:/Source/Z%C3%BCrich%20or%20Zurich%20(%CB%88zj%CA%8A%C9%99r%C9%AAk,/Code/resources/app/plugins/c%23/plugin.json" + ); value.Scheme.Should().Be("file"); value.Authority.Should().Be(""); value.Path.Should().Be( - "/c:/Source/Zürich or Zurich (ˈzjʊərɪk,/Code/resources/app/plugins/c#/plugin.json"); + "/c:/Source/Zürich or Zurich (ˈzjʊərɪk,/Code/resources/app/plugins/c#/plugin.json" + ); value.Fragment.Should().Be(""); value.Query.Should().Be(""); @@ -309,10 +342,7 @@ public void Parse() } [Fact(DisplayName = "parse, disallow")] - public void parse_disallow() - { - Assert.Throws(() => DocumentUri.Parse("file:////shares/files/p.cs")); - } + public void parse_disallow() => Assert.Throws(() => DocumentUri.Parse("file:////shares/files/p.cs")); [Fact(DisplayName = "URI#file, win-speciale")] public void URI_file__win_speciale() @@ -414,9 +444,11 @@ public void URI_toString_upper_case_percent_espaces() public void URI_toString_lower_case_windows_drive_letter() { DocumentUri.Parse("untitled:c:/Users/jrieken/Code/abc.txt").ToString().Should().Be( - "untitled:c:/Users/jrieken/Code/abc.txt"); + "untitled:c:/Users/jrieken/Code/abc.txt" + ); DocumentUri.Parse("untitled:C:/Users/jrieken/Code/abc.txt").ToString().Should().Be( - "untitled:c:/Users/jrieken/Code/abc.txt"); + "untitled:c:/Users/jrieken/Code/abc.txt" + ); } [Fact(DisplayName = "URI#toString, escape all the bits")] @@ -424,7 +456,8 @@ public void URI_toString__escape_all_the_bits() { var value = DocumentUri.File("/Users/jrieken/Code/_samples/18500/Mödel + Other Thîngß/model.js"); value.ToString().Should().Be( - "file:///Users/jrieken/Code/_samples/18500/M%C3%B6del%20%2B%20Other%20Th%C3%AEng%C3%9F/model.js"); + "file:///Users/jrieken/Code/_samples/18500/M%C3%B6del%20%2B%20Other%20Th%C3%AEng%C3%9F/model.js" + ); } [Fact(DisplayName = "URI#toString, don\"t encode port")] @@ -433,8 +466,10 @@ public void URI_toString_don_t_encode_port() var value = DocumentUri.Parse("http://localhost:8080/far"); value.ToString().Should().Be("http://localhost:8080/far"); - value = DocumentUri.From(new DocumentUriComponents - {Scheme = "http", Authority = "löcalhost:8080", Path = "/far", Query = null, Fragment = null}); + value = DocumentUri.From( + new DocumentUriComponents + { Scheme = "http", Authority = "löcalhost:8080", Path = "/far", Query = null, Fragment = null } + ); value.ToString().Should().Be("http://l%C3%B6calhost:8080/far"); } @@ -453,15 +488,17 @@ public void URI_toString_user_information_in_authority() value = DocumentUri.Parse("http://foo@localhost:8080/far"); value.ToString().Should().Be("http://foo@localhost:8080/far"); - value = DocumentUri.From(new DocumentUriComponents - {Scheme = "http", Authority = "föö:bör@löcalhost:8080", Path = "/far", Query = null, Fragment = null}); + value = DocumentUri.From( + new DocumentUriComponents + { Scheme = "http", Authority = "föö:bör@löcalhost:8080", Path = "/far", Query = null, Fragment = null } + ); value.ToString().Should().Be("http://f%C3%B6%C3%B6:b%C3%B6r@l%C3%B6calhost:8080/far"); } [Fact(DisplayName = "correctFileUriToFilePath2")] public void CorrectFileUriToFilePath2() { - Action test = (string input, string expected) => { + Action test = (input, expected) => { var value = DocumentUri.Parse(input); value.GetFileSystemPath().Should().Be(expected); var value2 = DocumentUri.File(value.GetFileSystemPath()); @@ -472,13 +509,16 @@ public void CorrectFileUriToFilePath2() test("file:///c:/alex.txt", "c:\\alex.txt"); test( "file:///c:/Source/Z%C3%BCrich%20or%20Zurich%20(%CB%88zj%CA%8A%C9%99r%C9%AAk,/Code/resources/app/plugins", - "c:\\Source\\Zürich or Zurich (ˈzjʊərɪk,\\Code\\resources\\app\\plugins"); + "c:\\Source\\Zürich or Zurich (ˈzjʊərɪk,\\Code\\resources\\app\\plugins" + ); test( "file://monacotools/folder/isi.txt", - "\\\\monacotools\\folder\\isi.txt"); + "\\\\monacotools\\folder\\isi.txt" + ); test( "file://monacotools1/certificates/SSL/", - "\\\\monacotools1\\certificates\\SSL\\"); + "\\\\monacotools1\\certificates\\SSL\\" + ); } [Fact(DisplayName = "URI - http, query & toString")] @@ -497,7 +537,8 @@ public void URI___http__query___toString() uri.Query.Should().Be("LinkId=518008&foö&ké¥=üü"); uri.ToUnencodedString().Should().Be("https://go.microsoft.com/fwlink/?LinkId=518008&foö&ké¥=üü"); uri.ToString().Should().Be( - "https://go.microsoft.com/fwlink/?LinkId%3D518008%26fo%C3%B6%26k%C3%A9%C2%A5%3D%C3%BC%C3%BC"); + "https://go.microsoft.com/fwlink/?LinkId%3D518008%26fo%C3%B6%26k%C3%A9%C2%A5%3D%C3%BC%C3%BC" + ); uri2 = DocumentUri.Parse(uri.ToString()); uri2.Query.Should().Be("LinkId=518008&foö&ké¥=üü"); diff --git a/test/Lsp.Tests/WorkspaceSymbolKindTests.cs b/test/Lsp.Tests/WorkspaceSymbolKindTests.cs index 570b12e17..a2bf3c49e 100644 --- a/test/Lsp.Tests/WorkspaceSymbolKindTests.cs +++ b/test/Lsp.Tests/WorkspaceSymbolKindTests.cs @@ -1,9 +1,10 @@ using FluentAssertions; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; 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; + #pragma warning disable 618 namespace Lsp.Tests @@ -14,10 +15,11 @@ public class WorkspaceSymbolKindTests public void DefaultBehavior_Should_Only_Support_InitialSymbolKinds() { var serializer = new Serializer(); - var json = serializer.SerializeObject(new SymbolInformation() - { - Kind = SymbolKind.Event - }); + var json = serializer.SerializeObject( + new SymbolInformation { + Kind = SymbolKind.Event + } + ); var result = serializer.DeserializeObject(json); result.Kind.Should().Be(SymbolKind.Event); @@ -27,10 +29,11 @@ public void DefaultBehavior_Should_Only_Support_InitialSymbolKinds() public void DefaultBehavior_Should_Only_Support_InitialSymbolTags() { var serializer = new Serializer(); - var json = serializer.SerializeObject(new SymbolInformation() - { - Tags = new Container(SymbolTag.Deprecated) - }); + var json = serializer.SerializeObject( + new SymbolInformation { + Tags = new Container(SymbolTag.Deprecated) + } + ); var result = serializer.DeserializeObject(json); result.Tags.Should().Contain(SymbolTag.Deprecated); @@ -40,24 +43,25 @@ public void DefaultBehavior_Should_Only_Support_InitialSymbolTags() public void CustomBehavior_When_SymbolKind_Defined_By_Client() { var serializer = new Serializer(); - serializer.SetClientCapabilities(ClientVersion.Lsp3, new ClientCapabilities() - { - Workspace = new WorkspaceClientCapabilities() - { - Symbol = new Supports(true, new WorkspaceSymbolCapability() - { - DynamicRegistration = true, - SymbolKind = new SymbolKindCapability() - { - ValueSet = new Container(SymbolKind.Class) - } - }) + serializer.SetClientCapabilities( + ClientVersion.Lsp3, new ClientCapabilities { + Workspace = new WorkspaceClientCapabilities { + Symbol = new Supports( + true, new WorkspaceSymbolCapability { + DynamicRegistration = true, + SymbolKind = new SymbolKindCapability { + ValueSet = new Container(SymbolKind.Class) + } + } + ) + } + } + ); + var json = serializer.SerializeObject( + new SymbolInformation { + Kind = SymbolKind.Event } - }); - var json = serializer.SerializeObject(new SymbolInformation() - { - Kind = SymbolKind.Event - }); + ); var result = serializer.DeserializeObject(json); result.Kind.Should().Be(SymbolKind.Class); @@ -67,24 +71,26 @@ public void CustomBehavior_When_SymbolKind_Defined_By_Client() public void CustomBehavior_When_SymbolTag_Defined_By_Client() { var serializer = new Serializer(); - serializer.SetClientCapabilities(ClientVersion.Lsp3, new ClientCapabilities() - { - Workspace = new WorkspaceClientCapabilities() - { - Symbol = new Supports(true, new WorkspaceSymbolCapability() - { - DynamicRegistration = true, - TagSupport = new TagSupportCapability() { - ValueSet = new Container() - } - }) + serializer.SetClientCapabilities( + ClientVersion.Lsp3, new ClientCapabilities { + Workspace = new WorkspaceClientCapabilities { + Symbol = new Supports( + true, new WorkspaceSymbolCapability { + DynamicRegistration = true, + TagSupport = new TagSupportCapability { + ValueSet = new Container() + } + } + ) + } } - }); + ); - var json = serializer.SerializeObject(new SymbolInformation() - { - Tags = new Container(SymbolTag.Deprecated) - }); + var json = serializer.SerializeObject( + new SymbolInformation { + Tags = new Container(SymbolTag.Deprecated) + } + ); var result = serializer.DeserializeObject(json); result.Tags.Should().BeEmpty(); diff --git a/test/TestingUtils/AutoNSubstitute/AutoSubstitute.cs b/test/TestingUtils/AutoNSubstitute/AutoSubstitute.cs index 4f1a01b3c..62afd1850 100644 --- a/test/TestingUtils/AutoNSubstitute/AutoSubstitute.cs +++ b/test/TestingUtils/AutoNSubstitute/AutoSubstitute.cs @@ -1,11 +1,7 @@ using System; -using System.Collections.Concurrent; -using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; -using System.Linq; using DryIoc; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; // ReSharper disable once CheckNamespace namespace NSubstitute.Internals @@ -22,16 +18,17 @@ internal class AutoSubstitute : IDisposable /// internal AutoSubstitute( IContainer container = null, - Func configureAction = null) + Func configureAction = null + ) { Container = container ?? new Container(); Container = Container - - .With(rules => rules - .WithTestLoggerResolver((request, loggerType) => ActivatorUtilities.CreateInstance(request.Container, loggerType)) - .WithUndefinedTestDependenciesResolver(request => Substitute.For(new[] { request.ServiceType }, null)) - .WithConcreteTypeDynamicRegistrations((type, o) => true, Reuse.Transient) + .With( + rules => rules + .WithTestLoggerResolver((request, loggerType) => ActivatorUtilities.CreateInstance(request.Container, loggerType)) + .WithUndefinedTestDependenciesResolver(request => Substitute.For(new[] { request.ServiceType }, null)) + .WithConcreteTypeDynamicRegistrations((type, o) => true, Reuse.Transient) ); if (configureAction != null) @@ -41,7 +38,7 @@ internal AutoSubstitute( } /// - /// Gets the that handles the component resolution. + /// Gets the that handles the component resolution. /// internal IContainer Container { get; } diff --git a/test/TestingUtils/AutoNSubstitute/AutoTestBase.cs b/test/TestingUtils/AutoNSubstitute/AutoTestBase.cs index e7cb1db55..91d86aa77 100644 --- a/test/TestingUtils/AutoNSubstitute/AutoTestBase.cs +++ b/test/TestingUtils/AutoNSubstitute/AutoTestBase.cs @@ -25,8 +25,8 @@ internal AutoTestBase(ITestOutputHelper testOutputHelper, Action action) _action = cb => { action(cb); Services - .AddLogging() - .AddSingleton(LoggerFactory); + .AddLogging() + .AddSingleton(LoggerFactory); cb.Populate(Services); }; } @@ -35,18 +35,22 @@ internal AutoTestBase(ITestOutputHelper testOutputHelper, Action action) public ILogger Logger { get; } public IServiceCollection Services { get; } = new ServiceCollection(); - internal AutoSubstitute AutoSubstitute => _autoSubstitute ??= new AutoSubstitute(new Container().WithDependencyInjectionAdapter(), _ => { - _action(_); - return _; - }); + internal AutoSubstitute AutoSubstitute => _autoSubstitute ??= new AutoSubstitute( + new Container().WithDependencyInjectionAdapter(), _ => { + _action(_); + return _; + } + ); internal IContainer Container { get => AutoSubstitute.Container; - set => _autoSubstitute = new AutoSubstitute(value, _ => { - _action(_); - return _; - }); + set => _autoSubstitute = new AutoSubstitute( + value, _ => { + _action(_); + return _; + } + ); } public IServiceProvider ServiceProvider => AutoSubstitute.Container.Resolve(); diff --git a/test/TestingUtils/AutoNSubstitute/DryIocExtensions.cs b/test/TestingUtils/AutoNSubstitute/DryIocExtensions.cs index 789d927a3..d2ca14963 100644 --- a/test/TestingUtils/AutoNSubstitute/DryIocExtensions.cs +++ b/test/TestingUtils/AutoNSubstitute/DryIocExtensions.cs @@ -21,7 +21,7 @@ internal static Rules WithTestLoggerResolver(this Rules rules, Func(); return rules.WithUnknownServiceResolvers( - (rules.UnknownServiceResolvers ?? Array.Empty()).ToImmutableList().Add( + ( rules.UnknownServiceResolvers ?? Array.Empty() ).ToImmutableList().Add( request => { var serviceType = request.ServiceType; if (!serviceType.IsInterface || !serviceType.IsGenericType || @@ -55,7 +55,7 @@ internal static Rules WithUndefinedTestDependenciesResolver(this Rules rules, Fu { var dictionary = new ConcurrentDictionary(); return rules.WithUnknownServiceResolvers( - (rules.UnknownServiceResolvers ?? Array.Empty()).ToImmutableList().Add( + ( rules.UnknownServiceResolvers ?? Array.Empty() ).ToImmutableList().Add( request => { var serviceType = request.ServiceType; if (!serviceType.IsAbstract) diff --git a/test/TestingUtils/AutoNSubstitute/TestExtensions.cs b/test/TestingUtils/AutoNSubstitute/TestExtensions.cs index c0e417781..db89129d4 100644 --- a/test/TestingUtils/AutoNSubstitute/TestExtensions.cs +++ b/test/TestingUtils/AutoNSubstitute/TestExtensions.cs @@ -8,19 +8,15 @@ namespace NSubstitute { public static class TestExtensions { - public static void Wait(this CancellationTokenSource cancellationTokenSource) - { - cancellationTokenSource.Token.WaitHandle.WaitOne(); - } + public static void Wait(this CancellationTokenSource cancellationTokenSource) => cancellationTokenSource.Token.WaitHandle.WaitOne(); public static JsonRpcTestOptions ConfigureForXUnit( - this JsonRpcTestOptions jsonRpcTestOptions, - ITestOutputHelper outputHelper, - LogEventLevel logEventLevel = LogEventLevel.Debug) - { - return jsonRpcTestOptions - .WithClientLoggerFactory(new TestLoggerFactory(outputHelper, "{Timestamp:yyyy-MM-dd HH:mm:ss} [Client] [{Level}] {Message}{NewLine}{Exception}", logEventLevel)) - .WithServerLoggerFactory(new TestLoggerFactory(outputHelper, "{Timestamp:yyyy-MM-dd HH:mm:ss} [Server] [{Level}] {Message}{NewLine}{Exception}", logEventLevel)); - } + this JsonRpcTestOptions jsonRpcTestOptions, + ITestOutputHelper outputHelper, + LogEventLevel logEventLevel = LogEventLevel.Debug + ) => + jsonRpcTestOptions + .WithClientLoggerFactory(new TestLoggerFactory(outputHelper, "{Timestamp:yyyy-MM-dd HH:mm:ss} [Client] [{Level}] {Message}{NewLine}{Exception}", logEventLevel)) + .WithServerLoggerFactory(new TestLoggerFactory(outputHelper, "{Timestamp:yyyy-MM-dd HH:mm:ss} [Server] [{Level}] {Message}{NewLine}{Exception}", logEventLevel)); } } diff --git a/test/TestingUtils/AutoNSubstitute/TestLoggerFactory.cs b/test/TestingUtils/AutoNSubstitute/TestLoggerFactory.cs index 8823edf80..73323a574 100644 --- a/test/TestingUtils/AutoNSubstitute/TestLoggerFactory.cs +++ b/test/TestingUtils/AutoNSubstitute/TestLoggerFactory.cs @@ -13,23 +13,25 @@ public class TestLoggerFactory : ILoggerFactory { private readonly SerilogLoggerProvider _loggerProvider; - public TestLoggerFactory(ITestOutputHelper testOutputHelper, string outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}", LogEventLevel logEventLevel = LogEventLevel.Debug) - { + public TestLoggerFactory( + ITestOutputHelper testOutputHelper, string outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}", + LogEventLevel logEventLevel = LogEventLevel.Debug + ) => _loggerProvider = new SerilogLoggerProvider( new LoggerConfiguration() - .MinimumLevel.Is(logEventLevel) - .WriteTo.TestOutput(testOutputHelper) - .CreateLogger() + .MinimumLevel.Is(logEventLevel) + .WriteTo.TestOutput(testOutputHelper) + .CreateLogger() ); - } - ILogger ILoggerFactory.CreateLogger(string categoryName) + ILogger ILoggerFactory.CreateLogger(string categoryName) => _loggerProvider.CreateLogger(categoryName); + + void ILoggerFactory.AddProvider(ILoggerProvider provider) { - return _loggerProvider.CreateLogger(categoryName); } - void ILoggerFactory.AddProvider(ILoggerProvider provider) { } - - void IDisposable.Dispose() { } + void IDisposable.Dispose() + { + } } } diff --git a/test/TestingUtils/AutoNSubstitute/TraceWriter.cs b/test/TestingUtils/AutoNSubstitute/TraceWriter.cs index 729922b63..fda504366 100644 --- a/test/TestingUtils/AutoNSubstitute/TraceWriter.cs +++ b/test/TestingUtils/AutoNSubstitute/TraceWriter.cs @@ -9,10 +9,7 @@ public class TraceWriter : ITraceWriter { private readonly ILogger _logger; - public TraceWriter(ILogger logger) - { - _logger = logger; - } + public TraceWriter(ILogger logger) => _logger = logger; public void AddSingle(string trace) => _logger.LogInformation(trace); From efbcd0c94bd58c318ff8d341dce50e55126afa85 Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Tue, 11 Aug 2020 00:33:47 -0400 Subject: [PATCH 4/7] make cancellation tests more reslient for failure --- src/JsonRpc.Testing/JsonRpcTestOptions.cs | 2 +- .../Integration/RequestCancellationTests.cs | 18 +++++++------ .../Integration/RequestCancellationTests.cs | 26 ++++++++++--------- 3 files changed, 25 insertions(+), 21 deletions(-) diff --git a/src/JsonRpc.Testing/JsonRpcTestOptions.cs b/src/JsonRpc.Testing/JsonRpcTestOptions.cs index a9607fd48..3badfc304 100644 --- a/src/JsonRpc.Testing/JsonRpcTestOptions.cs +++ b/src/JsonRpc.Testing/JsonRpcTestOptions.cs @@ -23,7 +23,7 @@ public JsonRpcTestOptions(ILoggerFactory clientLoggerFactory, ILoggerFactory ser public ILoggerFactory ServerLoggerFactory { get; internal set; } = NullLoggerFactory.Instance; public TimeSpan SettleTimeSpan { get; internal set; } = TimeSpan.FromMilliseconds(100); public TimeSpan SettleTimeout { get; internal set; } = TimeSpan.FromMilliseconds(500); - public TimeSpan TestTimeout { get; internal set; } = TimeSpan.FromSeconds(30); + public TimeSpan TestTimeout { get; internal set; } = TimeSpan.FromMinutes(5); public PipeOptions DefaultPipeOptions { get; internal set; } = new PipeOptions(); } } diff --git a/test/Dap.Tests/Integration/RequestCancellationTests.cs b/test/Dap.Tests/Integration/RequestCancellationTests.cs index f70d3671d..52dcd9f06 100644 --- a/test/Dap.Tests/Integration/RequestCancellationTests.cs +++ b/test/Dap.Tests/Integration/RequestCancellationTests.cs @@ -34,16 +34,18 @@ public async Task Should_Cancel_Pending_Requests() } [Fact] - public async Task Should_Cancel_Requests_After_Timeout() + public void Should_Cancel_Requests_After_Timeout() { - var (client, server) = await Initialize( - ConfigureClient, x => { - ConfigureServer(x); - x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(1000)); - } - ); + Func> action = async () => { + var (client, server) = await Initialize( + ConfigureClient, x => { + ConfigureServer(x); + x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(1000)); + } + ); - Func> action = () => client.RequestCompletions(new CompletionsArguments()); + return await client.RequestCompletions(new CompletionsArguments()); + }; action.Should().Throw(); } diff --git a/test/Lsp.Tests/Integration/RequestCancellationTests.cs b/test/Lsp.Tests/Integration/RequestCancellationTests.cs index 118f95311..36fd1f66f 100644 --- a/test/Lsp.Tests/Integration/RequestCancellationTests.cs +++ b/test/Lsp.Tests/Integration/RequestCancellationTests.cs @@ -89,20 +89,22 @@ await client.TextDocument.RequestCompletion( } [Fact] - public async Task Should_Cancel_Requests_After_Timeout_without_Content_Modified() + public void Should_Cancel_Requests_After_Timeout_without_Content_Modified() { - var (client, server) = await Initialize( - ConfigureClient, x => { - ConfigureServer(x); - x.WithContentModifiedSupport(false).WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(3000)); - } - ); + Func action = async () => { + var (client, server) = await Initialize( + ConfigureClient, x => { + ConfigureServer(x); + x.WithContentModifiedSupport(false).WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(3000)); + } + ); - Func action = () => client.TextDocument.RequestCompletion( - new CompletionParams { - TextDocument = "/a/file.cs" - }, CancellationToken - ).AsTask(); + await client.TextDocument.RequestCompletion( + new CompletionParams { + TextDocument = "/a/file.cs" + }, CancellationToken + ).AsTask(); + }; action.Should().Throw(); } From 649f94cdf309ca9bb2095afc78652a6a59691ae0 Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Tue, 11 Aug 2020 00:36:40 -0400 Subject: [PATCH 5/7] Updated tools and remove grm (global tool is used elsewhere) --- .config/dotnet-tools.json | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 33ec38808..23dd823b5 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,31 +3,27 @@ "isRoot": true, "tools": { "cake.tool": { - "version": "0.35.0", + "version": "0.38.4", "commands": ["dotnet-cake"] }, "gitversion.tool": { - "version": "5.2.4", + "version": "5.3.7", "commands": ["dotnet-gitversion"] }, "dotnet-reportgenerator-globaltool": { - "version": "4.3.0", + "version": "4.6.4", "commands": ["reportgenerator"] }, "codecov.tool": { - "version": "1.10.0", + "version": "1.12.1", "commands": ["codecov"] }, - "gitreleasemanager.tool": { - "version": "0.11.0", - "commands": ["dotnet-gitreleasemanager"] - }, "nuke.globaltool": { - "version": "0.24.4", + "version": "0.24.11", "commands": ["nuke"] }, "nukeeper": { - "version": "0.26.1", + "version": "0.33.0", "commands": ["nukeeper"] }, "jetbrains.resharper.globaltools": { From c31affc406ddcde4ba12208de44162934d39e48d Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Tue, 11 Aug 2020 02:42:29 -0400 Subject: [PATCH 6/7] Updated readme --- Directory.Build.targets | 2 +- GitReleaseManager.yaml | 6 --- README.md | 93 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 94 insertions(+), 7 deletions(-) diff --git a/Directory.Build.targets b/Directory.Build.targets index 9acff7577..aa69f9700 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -12,7 +12,7 @@ - + diff --git a/GitReleaseManager.yaml b/GitReleaseManager.yaml index 64326d518..fbb334a42 100644 --- a/GitReleaseManager.yaml +++ b/GitReleaseManager.yaml @@ -22,9 +22,3 @@ issue-labels-include: - 'dependencies' - 'deprecated' - 'removed' -issue-labels-exclude: - - 'duplicate' - - 'question' - - 'wontfix' - - 'merge' - - 'invalid' diff --git a/README.md b/README.md index 9f364bb4b..8d9868213 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,89 @@ This is an implementation of the [Language Server Protocol](https://github.com/M This is currently under heavy development and the API's are subject to change. +# Status + +[![github-release-badge]][github-release] +[![github-license-badge]][github-license] +[![codecov-badge]][codecov] + + + +| Azure Pipelines | GitHub Actions | +| --------------- | -------------- | +| [![azurepipelines-badge]][azurepipelines] | [![github-badge]][github] | +| [![azurepipelines-history-badge]][azurepipelines-history] | [![github-history-badge]][github] | + + + +| Package | NuGet | +| ------- | ----- | +| OmniSharp.Extensions.DebugAdapter | [![nuget-version-hefb6om79mfg-badge]![nuget-downloads-hefb6om79mfg-badge]][nuget-hefb6om79mfg] | +| OmniSharp.Extensions.DebugAdapter.Client | [![nuget-version-94qjnkon/cda-badge]![nuget-downloads-94qjnkon/cda-badge]][nuget-94qjnkon/cda] | +| OmniSharp.Extensions.DebugAdapter.Server | [![nuget-version-f/4jrt4grmdg-badge]![nuget-downloads-f/4jrt4grmdg-badge]][nuget-f/4jrt4grmdg] | +| OmniSharp.Extensions.DebugAdapter.Shared | [![nuget-version-2fkn0yzdbhmg-badge]![nuget-downloads-2fkn0yzdbhmg-badge]][nuget-2fkn0yzdbhmg] | +| OmniSharp.Extensions.DebugAdapter.Testing | [![nuget-version-jppuysmkpfcw-badge]![nuget-downloads-jppuysmkpfcw-badge]][nuget-jppuysmkpfcw] | +| OmniSharp.Extensions.JsonRpc | [![nuget-version-a1bmkwyotvkg-badge]![nuget-downloads-a1bmkwyotvkg-badge]][nuget-a1bmkwyotvkg] | +| OmniSharp.Extensions.JsonRpc.Testing | [![nuget-version-punkj7/efvjq-badge]![nuget-downloads-punkj7/efvjq-badge]][nuget-punkj7/efvjq] | +| OmniSharp.Extensions.LanguageClient | [![nuget-version-fclou9t/p2ba-badge]![nuget-downloads-fclou9t/p2ba-badge]][nuget-fclou9t/p2ba] | +| OmniSharp.Extensions.LanguageProtocol | [![nuget-version-vddj9t6jnirq-badge]![nuget-downloads-vddj9t6jnirq-badge]][nuget-vddj9t6jnirq] | +| OmniSharp.Extensions.LanguageProtocol.Testing | [![nuget-version-md8c3c/bo/8g-badge]![nuget-downloads-md8c3c/bo/8g-badge]][nuget-md8c3c/bo/8g] | +| OmniSharp.Extensions.LanguageServer | [![nuget-version-fkxlzvrmzpbw-badge]![nuget-downloads-fkxlzvrmzpbw-badge]][nuget-fkxlzvrmzpbw] | +| OmniSharp.Extensions.LanguageServer.Shared | [![nuget-version-4htmykprzq1a-badge]![nuget-downloads-4htmykprzq1a-badge]][nuget-4htmykprzq1a] | + + + +[github-release]: https://github.com/OmniSharp/csharp-language-server-protocol/releases/latest +[github-release-badge]: https://img.shields.io/github/release/OmniSharp/csharp-language-server-protocol.svg?logo=github&style=flat "Latest Release" +[github-license]: https://github.com/OmniSharp/csharp-language-server-protocol/blob/master/LICENSE +[github-license-badge]: https://img.shields.io/github/license/OmniSharp/csharp-language-server-protocol.svg?style=flat "License" +[codecov]: https://codecov.io/gh/OmniSharp/csharp-language-server-protocol +[codecov-badge]: https://img.shields.io/codecov/c/github/OmniSharp/csharp-language-server-protocol.svg?color=E03997&label=codecov&logo=codecov&logoColor=E03997&style=flat "Code Coverage" +[azurepipelines]: https://omnisharp.visualstudio.com/Build/_build/latest?definitionId=1&branchName=master +[azurepipelines-badge]: https://img.shields.io/azure-devops/build/omnisharp/Build/1.svg?color=98C6FF&label=azure%20pipelines&logo=azuredevops&logoColor=98C6FF&style=flat "Azure Pipelines Status" +[azurepipelines-history]: https://omnisharp.visualstudio.com/Build/_build?definitionId=1&branchName=master +[azurepipelines-history-badge]: https://buildstats.info/azurepipelines/chart/omnisharp/Build/1?includeBuildsFromPullRequest=false "Azure Pipelines History" +[github]: https://github.com/OmniSharp/csharp-language-server-protocol/actions?query=workflow%3Aci +[github-badge]: https://img.shields.io/github/workflow/status/OmniSharp/csharp-language-server-protocol/ci.svg?label=github&logo=github&color=b845fc&logoColor=b845fc&style=flat "GitHub Actions Status" +[github-history-badge]: https://buildstats.info/github/chart/OmniSharp/csharp-language-server-protocol?includeBuildsFromPullRequest=false "GitHub Actions History" +[nuget-hefb6om79mfg]: https://www.nuget.org/packages/OmniSharp.Extensions.DebugAdapter/ +[nuget-version-hefb6om79mfg-badge]: https://img.shields.io/nuget/v/OmniSharp.Extensions.DebugAdapter.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" +[nuget-downloads-hefb6om79mfg-badge]: https://img.shields.io/nuget/dt/OmniSharp.Extensions.DebugAdapter.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" +[nuget-94qjnkon/cda]: https://www.nuget.org/packages/OmniSharp.Extensions.DebugAdapter.Client/ +[nuget-version-94qjnkon/cda-badge]: https://img.shields.io/nuget/v/OmniSharp.Extensions.DebugAdapter.Client.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" +[nuget-downloads-94qjnkon/cda-badge]: https://img.shields.io/nuget/dt/OmniSharp.Extensions.DebugAdapter.Client.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" +[nuget-f/4jrt4grmdg]: https://www.nuget.org/packages/OmniSharp.Extensions.DebugAdapter.Server/ +[nuget-version-f/4jrt4grmdg-badge]: https://img.shields.io/nuget/v/OmniSharp.Extensions.DebugAdapter.Server.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" +[nuget-downloads-f/4jrt4grmdg-badge]: https://img.shields.io/nuget/dt/OmniSharp.Extensions.DebugAdapter.Server.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" +[nuget-2fkn0yzdbhmg]: https://www.nuget.org/packages/OmniSharp.Extensions.DebugAdapter.Shared/ +[nuget-version-2fkn0yzdbhmg-badge]: https://img.shields.io/nuget/v/OmniSharp.Extensions.DebugAdapter.Shared.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" +[nuget-downloads-2fkn0yzdbhmg-badge]: https://img.shields.io/nuget/dt/OmniSharp.Extensions.DebugAdapter.Shared.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" +[nuget-jppuysmkpfcw]: https://www.nuget.org/packages/OmniSharp.Extensions.DebugAdapter.Testing/ +[nuget-version-jppuysmkpfcw-badge]: https://img.shields.io/nuget/v/OmniSharp.Extensions.DebugAdapter.Testing.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" +[nuget-downloads-jppuysmkpfcw-badge]: https://img.shields.io/nuget/dt/OmniSharp.Extensions.DebugAdapter.Testing.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" +[nuget-a1bmkwyotvkg]: https://www.nuget.org/packages/OmniSharp.Extensions.JsonRpc/ +[nuget-version-a1bmkwyotvkg-badge]: https://img.shields.io/nuget/v/OmniSharp.Extensions.JsonRpc.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" +[nuget-downloads-a1bmkwyotvkg-badge]: https://img.shields.io/nuget/dt/OmniSharp.Extensions.JsonRpc.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" +[nuget-punkj7/efvjq]: https://www.nuget.org/packages/OmniSharp.Extensions.JsonRpc.Testing/ +[nuget-version-punkj7/efvjq-badge]: https://img.shields.io/nuget/v/OmniSharp.Extensions.JsonRpc.Testing.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" +[nuget-downloads-punkj7/efvjq-badge]: https://img.shields.io/nuget/dt/OmniSharp.Extensions.JsonRpc.Testing.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" +[nuget-fclou9t/p2ba]: https://www.nuget.org/packages/OmniSharp.Extensions.LanguageClient/ +[nuget-version-fclou9t/p2ba-badge]: https://img.shields.io/nuget/v/OmniSharp.Extensions.LanguageClient.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" +[nuget-downloads-fclou9t/p2ba-badge]: https://img.shields.io/nuget/dt/OmniSharp.Extensions.LanguageClient.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" +[nuget-vddj9t6jnirq]: https://www.nuget.org/packages/OmniSharp.Extensions.LanguageProtocol/ +[nuget-version-vddj9t6jnirq-badge]: https://img.shields.io/nuget/v/OmniSharp.Extensions.LanguageProtocol.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" +[nuget-downloads-vddj9t6jnirq-badge]: https://img.shields.io/nuget/dt/OmniSharp.Extensions.LanguageProtocol.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" +[nuget-md8c3c/bo/8g]: https://www.nuget.org/packages/OmniSharp.Extensions.LanguageProtocol.Testing/ +[nuget-version-md8c3c/bo/8g-badge]: https://img.shields.io/nuget/v/OmniSharp.Extensions.LanguageProtocol.Testing.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" +[nuget-downloads-md8c3c/bo/8g-badge]: https://img.shields.io/nuget/dt/OmniSharp.Extensions.LanguageProtocol.Testing.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" +[nuget-fkxlzvrmzpbw]: https://www.nuget.org/packages/OmniSharp.Extensions.LanguageServer/ +[nuget-version-fkxlzvrmzpbw-badge]: https://img.shields.io/nuget/v/OmniSharp.Extensions.LanguageServer.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" +[nuget-downloads-fkxlzvrmzpbw-badge]: https://img.shields.io/nuget/dt/OmniSharp.Extensions.LanguageServer.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" +[nuget-4htmykprzq1a]: https://www.nuget.org/packages/OmniSharp.Extensions.LanguageServer.Shared/ +[nuget-version-4htmykprzq1a-badge]: https://img.shields.io/nuget/v/OmniSharp.Extensions.LanguageServer.Shared.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" +[nuget-downloads-4htmykprzq1a-badge]: https://img.shields.io/nuget/dt/OmniSharp.Extensions.LanguageServer.Shared.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" + + ## License Copyright © .NET Foundation, and contributors. @@ -27,3 +110,13 @@ By signing the [CLA](https://cla.dotnetfoundation.org/OmniSharp/omnisharp-roslyn ## .NET Foundation This project is supported by the [.NET Foundation](http://www.dotnetfoundation.org). + + From 2c138e45c5adcf1bea629004aa98b901ea9febc3 Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Tue, 11 Aug 2020 02:53:39 -0400 Subject: [PATCH 7/7] Update azure-pipelines --- .azure-pipelines.yml | 202 ++++++++++++++++++++----------------------- 1 file changed, 93 insertions(+), 109 deletions(-) diff --git a/.azure-pipelines.yml b/.azure-pipelines.yml index 99039c92a..fcdac60a0 100644 --- a/.azure-pipelines.yml +++ b/.azure-pipelines.yml @@ -1,123 +1,107 @@ trigger: - batch: true - branches: - include: - - master - - refs/tags/* - paths: - exclude: - - '**/*.md' - - '.appveyor.yml' - - '.codecov.yml' - - 'GitVersion.yml' - - 'GitReleaseManager.yaml' - - .vscode/* - - .git* - - .editorconfig - - .nuke - - LICENSE + batch: true + branches: + include: + - master + - next + - refs/tags/* + paths: + exclude: + - '**/*.md' + - '.appveyor.yml' + - '.codecov.yml' + - 'GitVersion.yml' + - 'GitReleaseManager.yaml' + - .vscode/* + - .git* + - .editorconfig + - .nuke + - LICENSE pr: - autoCancel: true - branches: - include: - - master + autoCancel: true + branches: + include: + - master + - next resources: - repositories: - - repository: rsg - type: github - name: RocketSurgeonsGuild/AzureDevopsTemplates - ref: refs/tags/v0.12.0 - endpoint: github + repositories: + - repository: rsg + type: github + name: RocketSurgeonsGuild/AzureDevopsTemplates + ref: refs/tags/v0.13.0 + endpoint: github variables: - - name: CONFIGURATION - value: Release - - name: VERBOSITY - value: Normal - - name: COVERAGE - value: '$(Agent.BuildDirectory)/c' - - name: ARTIFACTS - value: $(Build.ArtifactStagingDirectory) - - name: DOTNET_SKIP_FIRST_TIME_EXPERIENCE - value: 'true' - - name: CodeCovToken - value: 'd122bf99-4ca6-4a7c-a7ff-90468bcc7703' - # Fixes the github package repo warnings on restore - - name: EmitAssetsLogMessages - value: false - - name: HideWarningsAndErrors - value: true + - name: CONFIGURATION + value: Release + - name: VERBOSITY + value: Normal + - name: COVERAGE + value: '$(Agent.BuildDirectory)/c' + - name: ARTIFACTS + value: $(Build.ArtifactStagingDirectory) + - name: DOTNET_SKIP_FIRST_TIME_EXPERIENCE + value: 'true' + - name: CodeCovToken + value: 'd122bf99-4ca6-4a7c-a7ff-90468bcc7703' jobs: - - template: jobs/gitversion.yml@rsg + - template: jobs/publish-release.yml@rsg + parameters: + GitHubPackages: false + PublishNuGetPackagesFromArtifact: 'NuGet - Windows' - - job: Build - strategy: - matrix: - Windows: - BuildName: 'Windows' - ImageName: 'windows-latest' - Linux: - BuildName: 'Linux' - ImageName: 'ubuntu-latest' - macOS: - BuildName: 'macOS' - ImageName: 'macOS-latest' - pool: - vmImage: $(ImageName) - steps: - - template: support/mono.yml@rsg - - template: support/install-dotnet.yml@rsg - parameters: - DotNetSdk: - - '2.x' - - '3.x' - - template: support/gitversion-hack.yml@rsg + - job: Build + strategy: + matrix: + Windows: + BuildName: 'Windows' + ImageName: 'windows-latest' + Linux: + BuildName: 'Linux' + ImageName: 'ubuntu-latest' + macOS: + BuildName: 'macOS' + ImageName: 'macOS-latest' + pool: + vmImage: $(ImageName) + steps: + - template: support/mono.yml@rsg + # - ${{ if startsWith(variables['Build.SourceBranch'], 'refs/tags/v') }}: + # - template: support/download-release-notes.yml@rsg + - template: support/install-dotnet.yml@rsg + parameters: + DotNetSdk: + - '2.x' + - '3.x' - - task: DotNetCoreCLI@2 - displayName: 'dotnet tool restore' - inputs: - command: custom - custom: tool - arguments: 'restore' + - task: DotNetCoreCLI@2 + displayName: 'dotnet tool restore' + inputs: + command: custom + custom: tool + arguments: 'restore' - - task: DotNetCoreCLI@2 - displayName: 'dotnet restore' - inputs: - command: restore - feedsToUse: config - nugetConfigPath: NuGet.config - verbosityRestore: Minimal + - task: DotNetCoreCLI@2 + displayName: 'dotnet restore' + inputs: + command: restore + feedsToUse: config + nugetConfigPath: NuGet.config + verbosityRestore: Minimal - - template: ./azure-pipelines.nuke.yml - parameters: - Artifacts: $(Artifacts) - Configuration: $(Configuration) - Coverage: $(Coverage) + - template: ./azure-pipelines.nuke.yml + parameters: + Artifacts: $(Artifacts) + Configuration: $(Configuration) + Coverage: $(Coverage) - - template: support/publish-artifacts.yml@rsg - parameters: - Artifacts: $(Artifacts) - Configuration: $(Configuration) - Coverage: $(Coverage) - Postfix: ' - $(BuildName)' - PublishVSTest: true - - ${{ if and(or(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'), eq(variables['Build.SourceBranch'], 'refs/heads/master')), ne(variables['System.PullRequest.IsFork'], 'true')) }}: - - job: Publish_NuGet_Packages - displayName: "Publish NuGet Packages" - pool: - vmImage: "windows-latest" - dependsOn: - - Build - steps: - - checkout: none - - download: current - displayName: "Download NuGet Packages" - artifact: 'NuGet - Windows' - - template: support/nuget-push.yml@rsg - parameters: - Artifacts: "$(Pipeline.Workspace)" - GitHubPackages: false - MyGetPackages: true + - template: support/publish-artifacts.yml@rsg + parameters: + Artifacts: $(Artifacts) + Configuration: $(Configuration) + Coverage: $(Coverage) + Postfix: ' - $(BuildName)' + PublishVSTest: true