-
Notifications
You must be signed in to change notification settings - Fork 172
/
server.rb
1263 lines (1101 loc) · 45.8 KB
/
server.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# typed: strict
# frozen_string_literal: true
module RubyLsp
class Server < BaseServer
extend T::Sig
# Only for testing
sig { returns(GlobalState) }
attr_reader :global_state
sig { override.params(message: T::Hash[Symbol, T.untyped]).void }
def process_message(message)
case message[:method]
when "initialize"
send_log_message("Initializing Ruby LSP v#{VERSION}...")
run_initialize(message)
when "initialized"
send_log_message("Finished initializing Ruby LSP!") unless @test_mode
run_initialized
when "textDocument/didOpen"
text_document_did_open(message)
when "textDocument/didClose"
text_document_did_close(message)
when "textDocument/didChange"
text_document_did_change(message)
when "textDocument/selectionRange"
text_document_selection_range(message)
when "textDocument/documentSymbol"
text_document_document_symbol(message)
when "textDocument/documentLink"
text_document_document_link(message)
when "textDocument/codeLens"
text_document_code_lens(message)
when "textDocument/semanticTokens/full"
text_document_semantic_tokens_full(message)
when "textDocument/semanticTokens/full/delta"
text_document_semantic_tokens_delta(message)
when "textDocument/foldingRange"
text_document_folding_range(message)
when "textDocument/semanticTokens/range"
text_document_semantic_tokens_range(message)
when "textDocument/formatting"
text_document_formatting(message)
when "textDocument/rangeFormatting"
text_document_range_formatting(message)
when "textDocument/documentHighlight"
text_document_document_highlight(message)
when "textDocument/onTypeFormatting"
text_document_on_type_formatting(message)
when "textDocument/hover"
text_document_hover(message)
when "textDocument/inlayHint"
text_document_inlay_hint(message)
when "textDocument/codeAction"
text_document_code_action(message)
when "codeAction/resolve"
code_action_resolve(message)
when "textDocument/diagnostic"
text_document_diagnostic(message)
when "textDocument/completion"
text_document_completion(message)
when "completionItem/resolve"
text_document_completion_item_resolve(message)
when "textDocument/signatureHelp"
text_document_signature_help(message)
when "textDocument/definition"
text_document_definition(message)
when "textDocument/prepareTypeHierarchy"
text_document_prepare_type_hierarchy(message)
when "textDocument/rename"
text_document_rename(message)
when "textDocument/prepareRename"
text_document_prepare_rename(message)
when "textDocument/references"
text_document_references(message)
when "typeHierarchy/supertypes"
type_hierarchy_supertypes(message)
when "typeHierarchy/subtypes"
type_hierarchy_subtypes(message)
when "workspace/didChangeWatchedFiles"
workspace_did_change_watched_files(message)
when "workspace/symbol"
workspace_symbol(message)
when "rubyLsp/textDocument/showSyntaxTree"
text_document_show_syntax_tree(message)
when "rubyLsp/workspace/dependencies"
workspace_dependencies(message)
when "rubyLsp/workspace/addons"
send_message(
Result.new(
id: message[:id],
response:
Addon.addons.map do |addon|
version_method = addon.method(:version)
# If the add-on doesn't define a `version` method, we'd be calling the abstract method defined by
# Sorbet, which would raise an error.
# Therefore, we only call the method if it's defined by the add-on itself
if version_method.owner != Addon
version = addon.version
end
{ name: addon.name, version: version, errored: addon.error? }
end,
),
)
when "$/cancelRequest"
@mutex.synchronize { @cancelled_requests << message[:params][:id] }
when nil
process_response(message) if message[:result]
end
rescue DelegateRequestError
send_message(Error.new(id: message[:id], code: DelegateRequestError::CODE, message: "DELEGATE_REQUEST"))
rescue StandardError, LoadError => e
# If an error occurred in a request, we have to return an error response or else the editor will hang
if message[:id]
# If a document is deleted before we are able to process all of its enqueued requests, we will try to read it
# from disk and it raise this error. This is expected, so we don't include the `data` attribute to avoid
# reporting these to our telemetry
case e
when Store::NonExistingDocumentError
send_message(Error.new(
id: message[:id],
code: Constant::ErrorCodes::INVALID_PARAMS,
message: e.full_message,
))
when Document::LocationNotFoundError
send_message(Error.new(
id: message[:id],
code: Constant::ErrorCodes::REQUEST_FAILED,
message: <<~MESSAGE,
Request #{message[:method]} failed to find the target position.
The file might have been modified while the server was in the middle of searching for the target.
If you experience this regularly, please report any findings and extra information on
https://github.com/Shopify/ruby-lsp/issues/2446
MESSAGE
))
else
send_message(Error.new(
id: message[:id],
code: Constant::ErrorCodes::INTERNAL_ERROR,
message: e.full_message,
data: {
errorClass: e.class.name,
errorMessage: e.message,
backtrace: e.backtrace&.join("\n"),
},
))
end
end
send_log_message("Error processing #{message[:method]}: #{e.full_message}", type: Constant::MessageType::ERROR)
end
# Process responses to requests that were sent to the client
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def process_response(message)
case message.dig(:result, :method)
when "window/showMessageRequest"
window_show_message_request(message)
end
end
sig { params(include_project_addons: T::Boolean).void }
def load_addons(include_project_addons: true)
# If invoking Bundler.setup failed, then the load path will not be configured properly and trying to load add-ons
# with Gem.find_files will find every single version installed of an add-on, leading to requiring several
# different versions of the same files. We cannot load add-ons if Bundler.setup failed
return if @setup_error
errors = Addon.load_addons(@global_state, @outgoing_queue, include_project_addons: include_project_addons)
if errors.any?
send_log_message(
"Error loading addons:\n\n#{errors.map(&:full_message).join("\n\n")}",
type: Constant::MessageType::WARNING,
)
end
errored_addons = Addon.addons.select(&:error?)
if errored_addons.any?
send_message(
Notification.new(
method: "window/showMessage",
params: Interface::ShowMessageParams.new(
type: Constant::MessageType::WARNING,
message: "Error loading add-ons:\n\n#{errored_addons.map(&:formatted_errors).join("\n\n")}",
),
),
)
unless @test_mode
send_log_message(
errored_addons.map(&:errors_details).join("\n\n"),
type: Constant::MessageType::WARNING,
)
end
end
end
private
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def run_initialize(message)
options = message[:params]
global_state_notifications = @global_state.apply_options(options)
client_name = options.dig(:clientInfo, :name)
@store.client_name = client_name if client_name
configured_features = options.dig(:initializationOptions, :enabledFeatures)
configured_hints = options.dig(:initializationOptions, :featuresConfiguration, :inlayHint)
T.must(@store.features_configuration.dig(:inlayHint)).configuration.merge!(configured_hints) if configured_hints
enabled_features = case configured_features
when Array
# If the configuration is using an array, then absent features are disabled and present ones are enabled. That's
# why we use `false` as the default value
Hash.new(false).merge!(configured_features.to_h { |feature| [feature, true] })
when Hash
# If the configuration is already a hash, merge it with a default value of `true`. That way clients don't have
# to opt-in to every single feature
Hash.new(true).merge!(configured_features.transform_keys(&:to_s))
else
# If no configuration was passed by the client, just enable every feature
Hash.new(true)
end
bundle_env_path = File.join(".ruby-lsp", "bundle_env")
bundle_env = if File.exist?(bundle_env_path)
env = File.readlines(bundle_env_path).to_h { |line| T.cast(line.chomp.split("=", 2), [String, String]) }
FileUtils.rm(bundle_env_path)
env
end
document_symbol_provider = Requests::DocumentSymbol.provider if enabled_features["documentSymbols"]
document_link_provider = Requests::DocumentLink.provider if enabled_features["documentLink"]
code_lens_provider = Requests::CodeLens.provider if enabled_features["codeLens"]
hover_provider = Requests::Hover.provider if enabled_features["hover"]
folding_ranges_provider = Requests::FoldingRanges.provider if enabled_features["foldingRanges"]
semantic_tokens_provider = Requests::SemanticHighlighting.provider if enabled_features["semanticHighlighting"]
document_formatting_provider = Requests::Formatting.provider if enabled_features["formatting"]
diagnostics_provider = Requests::Diagnostics.provider if enabled_features["diagnostics"]
on_type_formatting_provider = Requests::OnTypeFormatting.provider if enabled_features["onTypeFormatting"]
code_action_provider = Requests::CodeActions.provider if enabled_features["codeActions"]
inlay_hint_provider = Requests::InlayHints.provider if enabled_features["inlayHint"]
completion_provider = Requests::Completion.provider if enabled_features["completion"]
signature_help_provider = Requests::SignatureHelp.provider if enabled_features["signatureHelp"]
type_hierarchy_provider = Requests::PrepareTypeHierarchy.provider if enabled_features["typeHierarchy"]
rename_provider = Requests::Rename.provider unless @global_state.has_type_checker
response = {
capabilities: Interface::ServerCapabilities.new(
text_document_sync: Interface::TextDocumentSyncOptions.new(
change: Constant::TextDocumentSyncKind::INCREMENTAL,
open_close: true,
),
position_encoding: @global_state.encoding_name,
selection_range_provider: enabled_features["selectionRanges"],
hover_provider: hover_provider,
document_symbol_provider: document_symbol_provider,
document_link_provider: document_link_provider,
folding_range_provider: folding_ranges_provider,
semantic_tokens_provider: semantic_tokens_provider,
document_formatting_provider: document_formatting_provider && @global_state.formatter != "none",
document_highlight_provider: enabled_features["documentHighlights"],
code_action_provider: code_action_provider,
document_on_type_formatting_provider: on_type_formatting_provider,
diagnostic_provider: diagnostics_provider,
inlay_hint_provider: inlay_hint_provider,
completion_provider: completion_provider,
code_lens_provider: code_lens_provider,
definition_provider: enabled_features["definition"],
workspace_symbol_provider: enabled_features["workspaceSymbol"] && !@global_state.has_type_checker,
signature_help_provider: signature_help_provider,
type_hierarchy_provider: type_hierarchy_provider,
rename_provider: rename_provider,
references_provider: !@global_state.has_type_checker,
document_range_formatting_provider: true,
experimental: {
addon_detection: true,
},
),
serverInfo: {
name: "Ruby LSP",
version: VERSION,
},
formatter: @global_state.formatter,
degraded_mode: !!(@install_error || @setup_error),
bundle_env: bundle_env,
}
send_message(Result.new(id: message[:id], response: response))
# Not every client supports dynamic registration or file watching
if @global_state.client_capabilities.supports_watching_files
send_message(
Request.new(
id: @current_request_id,
method: "client/registerCapability",
params: Interface::RegistrationParams.new(
registrations: [
# Register watching Ruby files
Interface::Registration.new(
id: "workspace/didChangeWatchedFiles",
method: "workspace/didChangeWatchedFiles",
register_options: Interface::DidChangeWatchedFilesRegistrationOptions.new(
watchers: [
Interface::FileSystemWatcher.new(
glob_pattern: "**/*.rb",
kind: Constant::WatchKind::CREATE | Constant::WatchKind::CHANGE | Constant::WatchKind::DELETE,
),
],
),
),
],
),
),
)
end
process_indexing_configuration(options.dig(:initializationOptions, :indexing))
begin_progress("indexing-progress", "Ruby LSP: indexing files")
global_state_notifications.each { |notification| send_message(notification) }
if @setup_error
send_message(Notification.telemetry(
type: "error",
errorMessage: @setup_error.message,
errorClass: @setup_error.class,
stack: @setup_error.backtrace&.join("\n"),
))
end
if @install_error
send_message(Notification.telemetry(
type: "error",
errorMessage: @install_error.message,
errorClass: @install_error.class,
stack: @install_error.backtrace&.join("\n"),
))
end
end
sig { void }
def run_initialized
load_addons
RubyVM::YJIT.enable if defined?(RubyVM::YJIT.enable)
unless @setup_error
if defined?(Requests::Support::RuboCopFormatter)
begin
@global_state.register_formatter("rubocop", Requests::Support::RuboCopFormatter.new)
rescue RuboCop::Error => e
# The user may have provided unknown config switches in .rubocop or
# is trying to load a non-existent config file.
send_message(Notification.window_show_message(
"RuboCop configuration error: #{e.message}. Formatting will not be available.",
type: Constant::MessageType::ERROR,
))
end
end
if defined?(Requests::Support::SyntaxTreeFormatter)
@global_state.register_formatter("syntax_tree", Requests::Support::SyntaxTreeFormatter.new)
end
end
perform_initial_indexing
check_formatter_is_available
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_did_open(message)
@mutex.synchronize do
text_document = message.dig(:params, :textDocument)
language_id = case text_document[:languageId]
when "erb", "eruby"
Document::LanguageId::ERB
when "rbs"
Document::LanguageId::RBS
else
Document::LanguageId::Ruby
end
document = @store.set(
uri: text_document[:uri],
source: text_document[:text],
version: text_document[:version],
encoding: @global_state.encoding,
language_id: language_id,
)
if document.past_expensive_limit? && text_document[:uri].scheme == "file"
log_message = <<~MESSAGE
The file #{text_document[:uri].path} is too long. For performance reasons, semantic highlighting and
diagnostics will be disabled.
MESSAGE
send_message(
Notification.new(
method: "window/logMessage",
params: Interface::LogMessageParams.new(
type: Constant::MessageType::WARNING,
message: log_message,
),
),
)
end
end
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_did_close(message)
@mutex.synchronize do
uri = message.dig(:params, :textDocument, :uri)
@store.delete(uri)
# Clear diagnostics for the closed file, so that they no longer appear in the problems tab
send_message(
Notification.new(
method: "textDocument/publishDiagnostics",
params: Interface::PublishDiagnosticsParams.new(uri: uri.to_s, diagnostics: []),
),
)
end
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_did_change(message)
params = message[:params]
text_document = params[:textDocument]
@mutex.synchronize do
@store.push_edits(uri: text_document[:uri], edits: params[:contentChanges], version: text_document[:version])
end
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_selection_range(message)
uri = message.dig(:params, :textDocument, :uri)
ranges = @store.cache_fetch(uri, "textDocument/selectionRange") do |document|
case document
when RubyDocument, ERBDocument
Requests::SelectionRanges.new(document).perform
else
[]
end
end
# Per the selection range request spec (https://microsoft.github.io/language-server-protocol/specification#textDocument_selectionRange),
# every position in the positions array should have an element at the same index in the response
# array. For positions without a valid selection range, the corresponding element in the response
# array will be nil.
response = message.dig(:params, :positions).map do |position|
ranges.find do |range|
range.cover?(position)
end
end
send_message(Result.new(id: message[:id], response: response))
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def run_combined_requests(message)
uri = URI(message.dig(:params, :textDocument, :uri))
document = @store.get(uri)
unless document.is_a?(RubyDocument) || document.is_a?(ERBDocument)
send_empty_response(message[:id])
return
end
# If the response has already been cached by another request, return it
cached_response = document.cache_get(message[:method])
if cached_response != Document::EMPTY_CACHE
send_message(Result.new(id: message[:id], response: cached_response))
return
end
parse_result = document.parse_result
# Run requests for the document
dispatcher = Prism::Dispatcher.new
folding_range = Requests::FoldingRanges.new(parse_result.comments, dispatcher)
document_symbol = Requests::DocumentSymbol.new(uri, dispatcher)
document_link = Requests::DocumentLink.new(uri, parse_result.comments, dispatcher)
code_lens = Requests::CodeLens.new(@global_state, uri, dispatcher)
inlay_hint = Requests::InlayHints.new(document, T.must(@store.features_configuration.dig(:inlayHint)), dispatcher)
dispatcher.dispatch(parse_result.value)
# Store all responses retrieve in this round of visits in the cache and then return the response for the request
# we actually received
document.cache_set("textDocument/foldingRange", folding_range.perform)
document.cache_set("textDocument/documentSymbol", document_symbol.perform)
document.cache_set("textDocument/documentLink", document_link.perform)
document.cache_set("textDocument/codeLens", code_lens.perform)
document.cache_set("textDocument/inlayHint", inlay_hint.perform)
send_message(Result.new(id: message[:id], response: document.cache_get(message[:method])))
end
alias_method :text_document_document_symbol, :run_combined_requests
alias_method :text_document_document_link, :run_combined_requests
alias_method :text_document_code_lens, :run_combined_requests
alias_method :text_document_folding_range, :run_combined_requests
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_semantic_tokens_full(message)
document = @store.get(message.dig(:params, :textDocument, :uri))
if document.past_expensive_limit?
send_empty_response(message[:id])
return
end
unless document.is_a?(RubyDocument) || document.is_a?(ERBDocument)
send_empty_response(message[:id])
return
end
dispatcher = Prism::Dispatcher.new
semantic_highlighting = Requests::SemanticHighlighting.new(@global_state, dispatcher, document, nil)
dispatcher.visit(document.parse_result.value)
send_message(Result.new(id: message[:id], response: semantic_highlighting.perform))
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_semantic_tokens_delta(message)
document = @store.get(message.dig(:params, :textDocument, :uri))
if document.past_expensive_limit?
send_empty_response(message[:id])
return
end
unless document.is_a?(RubyDocument) || document.is_a?(ERBDocument)
send_empty_response(message[:id])
return
end
dispatcher = Prism::Dispatcher.new
request = Requests::SemanticHighlighting.new(
@global_state,
dispatcher,
document,
message.dig(:params, :previousResultId),
)
dispatcher.visit(document.parse_result.value)
send_message(Result.new(id: message[:id], response: request.perform))
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_semantic_tokens_range(message)
params = message[:params]
range = params[:range]
uri = params.dig(:textDocument, :uri)
document = @store.get(uri)
if document.past_expensive_limit?
send_empty_response(message[:id])
return
end
unless document.is_a?(RubyDocument) || document.is_a?(ERBDocument)
send_empty_response(message[:id])
return
end
dispatcher = Prism::Dispatcher.new
request = Requests::SemanticHighlighting.new(
@global_state,
dispatcher,
document,
nil,
range: range.dig(:start, :line)..range.dig(:end, :line),
)
dispatcher.visit(document.parse_result.value)
send_message(Result.new(id: message[:id], response: request.perform))
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_range_formatting(message)
# If formatter is set to `auto` but no supported formatting gem is found, don't attempt to format
if @global_state.formatter == "none"
send_empty_response(message[:id])
return
end
params = message[:params]
uri = params.dig(:textDocument, :uri)
# Do not format files outside of the workspace. For example, if someone is looking at a gem's source code, we
# don't want to format it
path = uri.to_standardized_path
unless path.nil? || path.start_with?(@global_state.workspace_path)
send_empty_response(message[:id])
return
end
document = @store.get(uri)
unless document.is_a?(RubyDocument)
send_empty_response(message[:id])
return
end
response = Requests::RangeFormatting.new(@global_state, document, params).perform
send_message(Result.new(id: message[:id], response: response))
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_formatting(message)
# If formatter is set to `auto` but no supported formatting gem is found, don't attempt to format
if @global_state.formatter == "none"
send_empty_response(message[:id])
return
end
uri = message.dig(:params, :textDocument, :uri)
# Do not format files outside of the workspace. For example, if someone is looking at a gem's source code, we
# don't want to format it
path = uri.to_standardized_path
unless path.nil? || path.start_with?(@global_state.workspace_path)
send_log_message(<<~MESSAGE)
Ignoring formatting request for file outside of the workspace.
Workspace path was set by editor as #{@global_state.workspace_path}.
File path requested for formatting was #{path}
MESSAGE
send_empty_response(message[:id])
return
end
document = @store.get(uri)
unless document.is_a?(RubyDocument)
send_empty_response(message[:id])
return
end
response = Requests::Formatting.new(@global_state, document).perform
send_message(Result.new(id: message[:id], response: response))
rescue Requests::Request::InvalidFormatter => error
send_message(Notification.window_show_message(
"Configuration error: #{error.message}",
type: Constant::MessageType::ERROR,
))
send_empty_response(message[:id])
rescue StandardError, LoadError => error
send_message(Notification.window_show_message(
"Formatting error: #{error.message}",
type: Constant::MessageType::ERROR,
))
send_empty_response(message[:id])
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_document_highlight(message)
params = message[:params]
dispatcher = Prism::Dispatcher.new
document = @store.get(params.dig(:textDocument, :uri))
unless document.is_a?(RubyDocument) || document.is_a?(ERBDocument)
send_empty_response(message[:id])
return
end
request = Requests::DocumentHighlight.new(@global_state, document, params[:position], dispatcher)
dispatcher.dispatch(document.parse_result.value)
send_message(Result.new(id: message[:id], response: request.perform))
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_on_type_formatting(message)
params = message[:params]
document = @store.get(params.dig(:textDocument, :uri))
unless document.is_a?(RubyDocument)
send_empty_response(message[:id])
return
end
send_message(
Result.new(
id: message[:id],
response: Requests::OnTypeFormatting.new(
document,
params[:position],
params[:ch],
@store.client_name,
).perform,
),
)
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_hover(message)
params = message[:params]
dispatcher = Prism::Dispatcher.new
document = @store.get(params.dig(:textDocument, :uri))
unless document.is_a?(RubyDocument) || document.is_a?(ERBDocument)
send_empty_response(message[:id])
return
end
send_message(
Result.new(
id: message[:id],
response: Requests::Hover.new(
document,
@global_state,
params[:position],
dispatcher,
sorbet_level(document),
).perform,
),
)
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_rename(message)
params = message[:params]
document = @store.get(params.dig(:textDocument, :uri))
unless document.is_a?(RubyDocument)
send_empty_response(message[:id])
return
end
send_message(
Result.new(
id: message[:id],
response: Requests::Rename.new(@global_state, @store, document, params).perform,
),
)
rescue Requests::Rename::InvalidNameError => e
send_message(Error.new(id: message[:id], code: Constant::ErrorCodes::REQUEST_FAILED, message: e.message))
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_prepare_rename(message)
params = message[:params]
document = @store.get(params.dig(:textDocument, :uri))
unless document.is_a?(RubyDocument)
send_empty_response(message[:id])
return
end
send_message(
Result.new(
id: message[:id],
response: Requests::PrepareRename.new(document, params[:position]).perform,
),
)
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_references(message)
params = message[:params]
document = @store.get(params.dig(:textDocument, :uri))
unless document.is_a?(RubyDocument)
send_empty_response(message[:id])
return
end
send_message(
Result.new(
id: message[:id],
response: Requests::References.new(@global_state, @store, document, params).perform,
),
)
end
sig { params(document: Document[T.untyped]).returns(RubyDocument::SorbetLevel) }
def sorbet_level(document)
return RubyDocument::SorbetLevel::Ignore unless @global_state.has_type_checker
return RubyDocument::SorbetLevel::Ignore unless document.is_a?(RubyDocument)
document.sorbet_level
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_inlay_hint(message)
params = message[:params]
document = @store.get(params.dig(:textDocument, :uri))
range = params.dig(:range, :start, :line)..params.dig(:range, :end, :line)
cached_response = document.cache_get("textDocument/inlayHint")
if cached_response != Document::EMPTY_CACHE
send_message(
Result.new(
id: message[:id],
response: cached_response.select { |hint| range.cover?(hint.position[:line]) },
),
)
return
end
hints_configurations = T.must(@store.features_configuration.dig(:inlayHint))
dispatcher = Prism::Dispatcher.new
unless document.is_a?(RubyDocument) || document.is_a?(ERBDocument)
send_empty_response(message[:id])
return
end
request = Requests::InlayHints.new(document, hints_configurations, dispatcher)
dispatcher.visit(document.parse_result.value)
result = request.perform
document.cache_set("textDocument/inlayHint", result)
send_message(Result.new(id: message[:id], response: result.select { |hint| range.cover?(hint.position[:line]) }))
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_code_action(message)
params = message[:params]
document = @store.get(params.dig(:textDocument, :uri))
unless document.is_a?(RubyDocument) || document.is_a?(ERBDocument)
send_empty_response(message[:id])
return
end
send_message(
Result.new(
id: message[:id],
response: Requests::CodeActions.new(
document,
params[:range],
params[:context],
).perform,
),
)
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def code_action_resolve(message)
params = message[:params]
uri = URI(params.dig(:data, :uri))
document = @store.get(uri)
unless document.is_a?(RubyDocument)
fail_request_and_notify(message[:id], "Code actions are currently only available for Ruby documents")
return
end
result = Requests::CodeActionResolve.new(document, @global_state, params).perform
case result
when Requests::CodeActionResolve::Error::EmptySelection
fail_request_and_notify(message[:id], "Invalid selection for extract variable refactor")
when Requests::CodeActionResolve::Error::InvalidTargetRange
fail_request_and_notify(message[:id], "Couldn't find an appropriate location to place extracted refactor")
when Requests::CodeActionResolve::Error::UnknownCodeAction
fail_request_and_notify(message[:id], "Unknown code action")
else
send_message(Result.new(id: message[:id], response: result))
end
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_diagnostic(message)
# Do not compute diagnostics for files outside of the workspace. For example, if someone is looking at a gem's
# source code, we don't want to show diagnostics for it
uri = message.dig(:params, :textDocument, :uri)
path = uri.to_standardized_path
unless path.nil? || path.start_with?(@global_state.workspace_path)
send_empty_response(message[:id])
return
end
document = @store.get(uri)
response = document.cache_fetch("textDocument/diagnostic") do |document|
case document
when RubyDocument
Requests::Diagnostics.new(@global_state, document).perform
end
end
send_message(
Result.new(
id: message[:id],
response: response && Interface::FullDocumentDiagnosticReport.new(kind: "full", items: response),
),
)
rescue Requests::Request::InvalidFormatter => error
send_message(Notification.window_show_message(
"Configuration error: #{error.message}",
type: Constant::MessageType::ERROR,
))
send_empty_response(message[:id])
rescue StandardError, LoadError => error
send_message(Notification.window_show_message(
"Error running diagnostics: #{error.message}",
type: Constant::MessageType::ERROR,
))
send_empty_response(message[:id])
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_completion(message)
params = message[:params]
dispatcher = Prism::Dispatcher.new
document = @store.get(params.dig(:textDocument, :uri))
unless document.is_a?(RubyDocument) || document.is_a?(ERBDocument)
send_empty_response(message[:id])
return
end
send_message(
Result.new(
id: message[:id],
response: Requests::Completion.new(
document,
@global_state,
params,
sorbet_level(document),
dispatcher,
).perform,
),
)
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_completion_item_resolve(message)
# When responding to a delegated completion request, it means we're handling a completion item that isn't related
# to Ruby (probably related to an ERB host language like HTML). We need to return the original completion item
# back to the editor so that it's displayed correctly
if message.dig(:params, :data, :delegateCompletion)
send_message(Result.new(
id: message[:id],
response: message[:params],
))
return
end
send_message(Result.new(
id: message[:id],
response: Requests::CompletionResolve.new(@global_state, message[:params]).perform,
))
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_signature_help(message)
params = message[:params]
dispatcher = Prism::Dispatcher.new
document = @store.get(params.dig(:textDocument, :uri))
unless document.is_a?(RubyDocument) || document.is_a?(ERBDocument)
send_empty_response(message[:id])
return
end
send_message(
Result.new(
id: message[:id],
response: Requests::SignatureHelp.new(
document,
@global_state,
params[:position],
params[:context],
dispatcher,
sorbet_level(document),
).perform,
),
)
end
sig { params(message: T::Hash[Symbol, T.untyped]).void }
def text_document_definition(message)
params = message[:params]
dispatcher = Prism::Dispatcher.new
document = @store.get(params.dig(:textDocument, :uri))
unless document.is_a?(RubyDocument) || document.is_a?(ERBDocument)
send_empty_response(message[:id])
return
end
send_message(
Result.new(
id: message[:id],
response: Requests::Definition.new(
document,
@global_state,
params[:position],
dispatcher,
sorbet_level(document),
).perform,