solargraph 0.58.1 → 0.58.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +1 -0
  3. data/CHANGELOG.md +7 -1
  4. data/lib/solargraph/api_map/cache.rb +110 -110
  5. data/lib/solargraph/api_map/constants.rb +279 -279
  6. data/lib/solargraph/api_map/index.rb +193 -193
  7. data/lib/solargraph/api_map/source_to_yard.rb +97 -97
  8. data/lib/solargraph/api_map/store.rb +384 -384
  9. data/lib/solargraph/api_map.rb +945 -945
  10. data/lib/solargraph/complex_type/type_methods.rb +228 -228
  11. data/lib/solargraph/complex_type/unique_type.rb +482 -482
  12. data/lib/solargraph/complex_type.rb +444 -444
  13. data/lib/solargraph/convention/data_definition/data_definition_node.rb +91 -91
  14. data/lib/solargraph/convention/data_definition.rb +105 -105
  15. data/lib/solargraph/convention/struct_definition/struct_assignment_node.rb +61 -61
  16. data/lib/solargraph/convention/struct_definition/struct_definition_node.rb +102 -102
  17. data/lib/solargraph/convention/struct_definition.rb +164 -164
  18. data/lib/solargraph/diagnostics/require_not_found.rb +53 -53
  19. data/lib/solargraph/diagnostics/rubocop.rb +118 -118
  20. data/lib/solargraph/diagnostics/rubocop_helpers.rb +68 -68
  21. data/lib/solargraph/diagnostics/type_check.rb +55 -55
  22. data/lib/solargraph/doc_map.rb +439 -439
  23. data/lib/solargraph/equality.rb +34 -34
  24. data/lib/solargraph/gem_pins.rb +98 -98
  25. data/lib/solargraph/language_server/host/diagnoser.rb +89 -89
  26. data/lib/solargraph/language_server/host/dispatch.rb +130 -130
  27. data/lib/solargraph/language_server/host/message_worker.rb +112 -112
  28. data/lib/solargraph/language_server/host/sources.rb +99 -99
  29. data/lib/solargraph/language_server/host.rb +878 -878
  30. data/lib/solargraph/language_server/message/extended/check_gem_version.rb +114 -114
  31. data/lib/solargraph/language_server/message/extended/document.rb +23 -23
  32. data/lib/solargraph/language_server/message/text_document/completion.rb +56 -56
  33. data/lib/solargraph/language_server/message/text_document/definition.rb +40 -40
  34. data/lib/solargraph/language_server/message/text_document/document_symbol.rb +26 -26
  35. data/lib/solargraph/language_server/message/text_document/formatting.rb +148 -148
  36. data/lib/solargraph/language_server/message/text_document/hover.rb +58 -58
  37. data/lib/solargraph/language_server/message/text_document/signature_help.rb +24 -24
  38. data/lib/solargraph/language_server/message/text_document/type_definition.rb +25 -25
  39. data/lib/solargraph/language_server/message/workspace/workspace_symbol.rb +23 -23
  40. data/lib/solargraph/library.rb +683 -683
  41. data/lib/solargraph/location.rb +82 -82
  42. data/lib/solargraph/logging.rb +37 -37
  43. data/lib/solargraph/parser/comment_ripper.rb +69 -69
  44. data/lib/solargraph/parser/flow_sensitive_typing.rb +255 -255
  45. data/lib/solargraph/parser/node_processor/base.rb +92 -92
  46. data/lib/solargraph/parser/node_processor.rb +62 -62
  47. data/lib/solargraph/parser/parser_gem/class_methods.rb +149 -149
  48. data/lib/solargraph/parser/parser_gem/node_chainer.rb +166 -166
  49. data/lib/solargraph/parser/parser_gem/node_methods.rb +486 -486
  50. data/lib/solargraph/parser/parser_gem/node_processors/and_node.rb +22 -22
  51. data/lib/solargraph/parser/parser_gem/node_processors/args_node.rb +59 -59
  52. data/lib/solargraph/parser/parser_gem/node_processors/begin_node.rb +15 -15
  53. data/lib/solargraph/parser/parser_gem/node_processors/block_node.rb +46 -46
  54. data/lib/solargraph/parser/parser_gem/node_processors/def_node.rb +53 -53
  55. data/lib/solargraph/parser/parser_gem/node_processors/if_node.rb +23 -23
  56. data/lib/solargraph/parser/parser_gem/node_processors/ivasgn_node.rb +40 -40
  57. data/lib/solargraph/parser/parser_gem/node_processors/lvasgn_node.rb +29 -29
  58. data/lib/solargraph/parser/parser_gem/node_processors/masgn_node.rb +59 -59
  59. data/lib/solargraph/parser/parser_gem/node_processors/opasgn_node.rb +98 -98
  60. data/lib/solargraph/parser/parser_gem/node_processors/orasgn_node.rb +17 -17
  61. data/lib/solargraph/parser/parser_gem/node_processors/resbody_node.rb +38 -38
  62. data/lib/solargraph/parser/parser_gem/node_processors/sclass_node.rb +52 -52
  63. data/lib/solargraph/parser/parser_gem/node_processors/send_node.rb +291 -291
  64. data/lib/solargraph/parser/parser_gem/node_processors/while_node.rb +29 -29
  65. data/lib/solargraph/parser/parser_gem/node_processors.rb +70 -70
  66. data/lib/solargraph/parser/region.rb +69 -69
  67. data/lib/solargraph/parser/snippet.rb +17 -17
  68. data/lib/solargraph/pin/base.rb +729 -729
  69. data/lib/solargraph/pin/base_variable.rb +126 -126
  70. data/lib/solargraph/pin/block.rb +104 -104
  71. data/lib/solargraph/pin/breakable.rb +9 -9
  72. data/lib/solargraph/pin/callable.rb +231 -231
  73. data/lib/solargraph/pin/closure.rb +72 -72
  74. data/lib/solargraph/pin/common.rb +79 -79
  75. data/lib/solargraph/pin/conversions.rb +123 -123
  76. data/lib/solargraph/pin/delegated_method.rb +120 -120
  77. data/lib/solargraph/pin/documenting.rb +114 -114
  78. data/lib/solargraph/pin/instance_variable.rb +34 -34
  79. data/lib/solargraph/pin/keyword.rb +20 -20
  80. data/lib/solargraph/pin/local_variable.rb +75 -75
  81. data/lib/solargraph/pin/method.rb +672 -672
  82. data/lib/solargraph/pin/method_alias.rb +34 -34
  83. data/lib/solargraph/pin/namespace.rb +115 -115
  84. data/lib/solargraph/pin/parameter.rb +275 -275
  85. data/lib/solargraph/pin/proxy_type.rb +39 -39
  86. data/lib/solargraph/pin/reference/override.rb +47 -47
  87. data/lib/solargraph/pin/reference/superclass.rb +15 -15
  88. data/lib/solargraph/pin/reference.rb +39 -39
  89. data/lib/solargraph/pin/search.rb +61 -61
  90. data/lib/solargraph/pin/signature.rb +61 -61
  91. data/lib/solargraph/pin/symbol.rb +53 -53
  92. data/lib/solargraph/pin/until.rb +18 -18
  93. data/lib/solargraph/pin/while.rb +18 -18
  94. data/lib/solargraph/pin.rb +44 -44
  95. data/lib/solargraph/pin_cache.rb +245 -245
  96. data/lib/solargraph/position.rb +132 -119
  97. data/lib/solargraph/range.rb +112 -112
  98. data/lib/solargraph/rbs_map/conversions.rb +823 -823
  99. data/lib/solargraph/rbs_map/core_map.rb +58 -58
  100. data/lib/solargraph/rbs_map/stdlib_map.rb +43 -43
  101. data/lib/solargraph/rbs_map.rb +163 -163
  102. data/lib/solargraph/shell.rb +352 -352
  103. data/lib/solargraph/source/chain/call.rb +337 -337
  104. data/lib/solargraph/source/chain/constant.rb +26 -26
  105. data/lib/solargraph/source/chain/hash.rb +34 -34
  106. data/lib/solargraph/source/chain/if.rb +28 -28
  107. data/lib/solargraph/source/chain/instance_variable.rb +13 -13
  108. data/lib/solargraph/source/chain/literal.rb +48 -48
  109. data/lib/solargraph/source/chain/or.rb +23 -23
  110. data/lib/solargraph/source/chain.rb +291 -291
  111. data/lib/solargraph/source/change.rb +82 -82
  112. data/lib/solargraph/source/cursor.rb +166 -166
  113. data/lib/solargraph/source/source_chainer.rb +194 -194
  114. data/lib/solargraph/source/updater.rb +55 -55
  115. data/lib/solargraph/source.rb +498 -498
  116. data/lib/solargraph/source_map/clip.rb +226 -226
  117. data/lib/solargraph/source_map/data.rb +34 -34
  118. data/lib/solargraph/source_map/mapper.rb +259 -259
  119. data/lib/solargraph/source_map.rb +212 -212
  120. data/lib/solargraph/type_checker/checks.rb +124 -124
  121. data/lib/solargraph/type_checker/param_def.rb +37 -37
  122. data/lib/solargraph/type_checker/problem.rb +32 -32
  123. data/lib/solargraph/type_checker/rules.rb +84 -84
  124. data/lib/solargraph/type_checker.rb +814 -814
  125. data/lib/solargraph/version.rb +1 -1
  126. data/lib/solargraph/workspace/config.rb +255 -255
  127. data/lib/solargraph/workspace/require_paths.rb +97 -97
  128. data/lib/solargraph/workspace.rb +220 -220
  129. data/lib/solargraph/yard_map/helpers.rb +44 -44
  130. data/lib/solargraph/yard_map/mapper/to_method.rb +130 -130
  131. data/lib/solargraph/yard_map/mapper/to_namespace.rb +31 -31
  132. data/lib/solargraph/yard_map/mapper.rb +79 -79
  133. data/lib/solargraph/yard_map/to_method.rb +89 -89
  134. data/lib/solargraph/yardoc.rb +87 -87
  135. data/lib/solargraph.rb +105 -105
  136. data/rbs_collection.yaml +1 -1
  137. metadata +12 -12
  138. /data/{sig → rbs}/shims/ast/0/node.rbs +0 -0
  139. /data/{sig → rbs}/shims/ast/2.4/.rbs_meta.yaml +0 -0
  140. /data/{sig → rbs}/shims/ast/2.4/ast.rbs +0 -0
  141. /data/{sig → rbs}/shims/parser/3.2.0.1/builders/default.rbs +0 -0
  142. /data/{sig → rbs}/shims/parser/3.2.0.1/manifest.yaml +0 -0
  143. /data/{sig → rbs}/shims/parser/3.2.0.1/parser.rbs +0 -0
  144. /data/{sig → rbs}/shims/parser/3.2.0.1/polyfill.rbs +0 -0
  145. /data/{sig → rbs}/shims/thor/1.2.0.1/.rbs_meta.yaml +0 -0
  146. /data/{sig → rbs}/shims/thor/1.2.0.1/manifest.yaml +0 -0
  147. /data/{sig → rbs}/shims/thor/1.2.0.1/thor.rbs +0 -0
@@ -1,878 +1,878 @@
1
- # frozen_string_literal: true
2
-
3
- require 'diff/lcs'
4
- require 'observer'
5
- require 'securerandom'
6
-
7
- module Solargraph
8
- module LanguageServer
9
- # The language server protocol's data provider. Hosts are responsible for
10
- # querying the library and processing messages. They also provide thread
11
- # safety for multi-threaded transports.
12
- #
13
- class Host
14
- autoload :Diagnoser, 'solargraph/language_server/host/diagnoser'
15
- autoload :Sources, 'solargraph/language_server/host/sources'
16
- autoload :Dispatch, 'solargraph/language_server/host/dispatch'
17
- autoload :MessageWorker, 'solargraph/language_server/host/message_worker'
18
-
19
- include UriHelpers
20
- include Logging
21
- include Dispatch
22
- include Observable
23
-
24
- attr_writer :client_capabilities
25
-
26
- def initialize
27
- @buffer_semaphore = Mutex.new
28
- @request_mutex = Mutex.new
29
- @buffer = String.new
30
- @stopped = true
31
- @next_request_id = 1
32
- @dynamic_capabilities = Set.new
33
- @registered_capabilities = Set.new
34
- end
35
-
36
- # Start asynchronous process handling.
37
- #
38
- # @return [void]
39
- def start
40
- return unless stopped?
41
- @stopped = false
42
- diagnoser.start
43
- message_worker.start
44
- end
45
-
46
- # Update the configuration options with the provided hash.
47
- #
48
- # @param update [Hash]
49
- # @return [void]
50
- def configure update
51
- return if update.nil?
52
- options.merge! update
53
- logger.level = LOG_LEVELS[options['logLevel']] || DEFAULT_LOG_LEVEL
54
- end
55
-
56
- # @return [Hash{String => [Boolean, String]}]
57
- def options
58
- @options ||= default_configuration
59
- end
60
-
61
- # Cancel the method with the specified ID.
62
- #
63
- # @param id [Integer]
64
- # @return [void]
65
- def cancel id
66
- cancelled.push id
67
- end
68
-
69
- # True if the host received a request to cancel the method with the
70
- # specified ID.
71
- #
72
- # @param id [Integer]
73
- # @return [Boolean]
74
- def cancel? id
75
- cancelled.include? id
76
- end
77
-
78
- # Delete the specified ID from the list of cancelled IDs if it exists.
79
- #
80
- # @param id [Integer]
81
- # @return [void]
82
- def clear id
83
- cancelled.delete id
84
- end
85
-
86
- # Called by adapter, to handle the request
87
- # @param request [Hash]
88
- # @return [void]
89
- def process request
90
- message_worker.queue(request)
91
- end
92
-
93
- # Start processing a request from the client. After the message is
94
- # processed, caller is responsible for sending the response.
95
- #
96
- # @param request [Hash{String => unspecified}] The contents of the message.
97
- #
98
- # @return [Solargraph::LanguageServer::Message::Base, Solargraph::LanguageServer::Request, nil] The message handler.
99
- def receive request
100
- if request['method']
101
- logger.info "Host received ##{request['id']} #{request['method']}"
102
- logger.debug request
103
- message = Message.select(request['method']).new(self, request)
104
- begin
105
- message.process unless cancel?(request['id'])
106
- rescue StandardError => e
107
- logger.warn "Error processing request: [#{e.class}] #{e.message}"
108
- logger.warn e.backtrace.join("\n")
109
- message.set_error Solargraph::LanguageServer::ErrorCodes::INTERNAL_ERROR, "[#{e.class}] #{e.message}"
110
- end
111
- message
112
- elsif request['id']
113
- if requests[request['id']]
114
- requests[request['id']].process(request['result'])
115
- requests.delete request['id']
116
- else
117
- logger.warn "Discarding client response to unrecognized message #{request['id']}"
118
- nil
119
- end
120
- else
121
- logger.warn "Invalid message received."
122
- logger.debug request
123
- nil
124
- end
125
- end
126
-
127
- # Respond to a notification that files were created in the workspace.
128
- # The libraries will determine whether the files should be merged; see
129
- # Solargraph::Library#create_from_disk.
130
- #
131
- # @param uris [Array<String>] The URIs of the files.
132
- # @return [Boolean] True if at least one library accepted at least one file.
133
- def create *uris
134
- filenames = uris.map { |uri| uri_to_file(uri) }
135
- result = false
136
- libraries.each do |lib|
137
- result = true if lib.create_from_disk(*filenames)
138
- end
139
- uris.each do |uri|
140
- diagnoser.schedule uri if open?(uri)
141
- end
142
- result
143
- end
144
-
145
- # Delete the specified files from the library.
146
- #
147
- # @param uris [Array<String>] The file uris.
148
- # @return [void]
149
- def delete *uris
150
- filenames = uris.map { |uri| uri_to_file(uri) }
151
- libraries.each do |lib|
152
- lib.delete_observer self
153
- lib.delete(*filenames)
154
- end
155
- uris.each do |uri|
156
- send_notification "textDocument/publishDiagnostics", {
157
- uri: uri,
158
- diagnostics: []
159
- }
160
- end
161
- end
162
-
163
- # Open the specified file in the library.
164
- #
165
- # @param uri [String] The file uri.
166
- # @param text [String] The contents of the file.
167
- # @param version [Integer] A version number.
168
- # @return [void]
169
- def open uri, text, version
170
- src = sources.open(uri, text, version)
171
- libraries.each do |lib|
172
- lib.merge src
173
- end
174
- diagnoser.schedule uri
175
- end
176
-
177
- # @param uri [String]
178
- # @return [void]
179
- def open_from_disk uri
180
- sources.open_from_disk(uri)
181
- diagnoser.schedule uri
182
- end
183
-
184
- # True if the specified file is currently open in the library.
185
- #
186
- # @param uri [String]
187
- # @return [Boolean]
188
- def open? uri
189
- sources.include? uri
190
- end
191
-
192
- # Close the file specified by the URI.
193
- #
194
- # @param uri [String]
195
- # @return [void]
196
- def close uri
197
- logger.info "Closing #{uri}"
198
- sources.close uri
199
- diagnoser.schedule uri
200
- end
201
-
202
- # @param uri [String]
203
- # @return [void]
204
- def diagnose uri
205
- if sources.include?(uri)
206
- library = library_for(uri)
207
- if library.mapped? && library.synchronized?
208
- logger.info "Diagnosing #{uri}"
209
- begin
210
- results = library.diagnose uri_to_file(uri)
211
- send_notification "textDocument/publishDiagnostics", {
212
- uri: uri,
213
- diagnostics: results
214
- }
215
- rescue DiagnosticsError => e
216
- logger.warn "Error in diagnostics: #{e.message}"
217
- options['diagnostics'] = false
218
- send_notification 'window/showMessage', {
219
- type: LanguageServer::MessageTypes::ERROR,
220
- message: "Error in diagnostics: #{e.message}"
221
- }
222
- rescue FileNotFoundError => e
223
- # @todo This appears to happen when an external file is open and
224
- # scheduled for diagnosis, but the file was closed (i.e., the
225
- # editor moved to a different file) before diagnosis started
226
- logger.warn "Unable to diagnose #{uri} : #{e.message}"
227
- send_notification 'textDocument/publishDiagnostics', {
228
- uri: uri,
229
- diagnostics: []
230
- }
231
- end
232
- else
233
- logger.info "Deferring diagnosis of #{uri}"
234
- diagnoser.schedule uri
235
- end
236
- else
237
- send_notification 'textDocument/publishDiagnostics', {
238
- uri: uri,
239
- diagnostics: []
240
- }
241
- end
242
- end
243
-
244
- # Update a document from the parameters of a textDocument/didChange
245
- # method.
246
- #
247
- # @param params [Hash]
248
- # @return [void]
249
- def change params
250
- updater = generate_updater(params)
251
- sources.update params['textDocument']['uri'], updater
252
- diagnoser.schedule params['textDocument']['uri']
253
- end
254
-
255
- # Queue a message to be sent to the client.
256
- #
257
- # @param message [String] The message to send.
258
- # @return [void]
259
- def queue message
260
- @buffer_semaphore.synchronize { @buffer += message }
261
- changed
262
- notify_observers
263
- end
264
-
265
- # Clear the message buffer and return the most recent data.
266
- #
267
- # @return [String] The most recent data or an empty string.
268
- def flush
269
- tmp = ''
270
- @buffer_semaphore.synchronize do
271
- tmp = @buffer.clone
272
- @buffer.clear
273
- end
274
- tmp
275
- end
276
-
277
- # Prepare a library for the specified directory.
278
- #
279
- # @param directory [String]
280
- # @param name [String, nil]
281
- # @return [void]
282
- def prepare directory, name = nil
283
- # No need to create a library without a directory. The generic library
284
- # will handle it.
285
- return if directory.nil?
286
- logger.info "Preparing library for #{directory}"
287
- path = ''
288
- path = normalize_separators(directory) unless directory.nil?
289
- begin
290
- workspace = Solargraph::Workspace.new(path, nil, options)
291
- lib = Solargraph::Library.new(workspace, name)
292
- lib.add_observer self
293
- libraries.push lib
294
- library_map lib
295
- rescue WorkspaceTooLargeError => e
296
- send_notification 'window/showMessage', {
297
- 'type' => Solargraph::LanguageServer::MessageTypes::WARNING,
298
- 'message' => e.message
299
- }
300
- end
301
- end
302
-
303
- # @return [String]
304
- def command_path
305
- options['commandPath'] || 'solargraph'
306
- end
307
-
308
- # Prepare multiple folders.
309
- #
310
- # @param array [Array<Hash{String => String}>]
311
- # @return [void]
312
- def prepare_folders array
313
- return if array.nil?
314
- array.each do |folder|
315
- prepare uri_to_file(folder['uri']), folder['name']
316
- end
317
- end
318
-
319
- # Remove a directory.
320
- #
321
- # @param directory [String]
322
- # @return [void]
323
- def remove directory
324
- logger.info "Removing library for #{directory}"
325
- # @param lib [Library]
326
- libraries.delete_if do |lib|
327
- next false if lib.workspace.directory != directory
328
- lib.delete_observer self
329
- true
330
- end
331
- end
332
-
333
- # @param array [Array<Hash>]
334
- # @return [void]
335
- def remove_folders array
336
- array.each do |folder|
337
- remove uri_to_file(folder['uri'])
338
- end
339
- end
340
-
341
- # @return [Array<String>]
342
- def folders
343
- libraries.map { |lib| lib.workspace.directory }
344
- end
345
-
346
- # Send a notification to the client.
347
- #
348
- # @param method [String] The message method
349
- # @param params [Hash] The method parameters
350
- # @return [void]
351
- def send_notification method, params
352
- response = {
353
- jsonrpc: "2.0",
354
- method: method,
355
- params: params
356
- }
357
- json = response.to_json
358
- envelope = "Content-Length: #{json.bytesize}\r\n\r\n#{json}"
359
- queue envelope
360
- logger.info "Server sent #{method}"
361
- logger.debug params
362
- end
363
-
364
- # Send a request to the client and execute the provided block to process
365
- # the response. If an ID is not provided, the host will use an auto-
366
- # incrementing integer.
367
- #
368
- # @param method [String] The message method
369
- # @param params [Hash] The method parameters
370
- # @param block [Proc] The block that processes the response
371
- # @yieldparam [Hash] The result sent by the client
372
- # @return [void]
373
- def send_request method, params, &block
374
- @request_mutex.synchronize do
375
- message = {
376
- jsonrpc: "2.0",
377
- method: method,
378
- params: params,
379
- id: @next_request_id
380
- }
381
- json = message.to_json
382
- requests[@next_request_id] = Request.new(@next_request_id, &block)
383
- envelope = "Content-Length: #{json.bytesize}\r\n\r\n#{json}"
384
- queue envelope
385
- @next_request_id += 1
386
- logger.debug params
387
- end
388
- end
389
-
390
- # Register the methods as capabilities with the client.
391
- # This method will avoid duplicating registrations and ignore methods
392
- # that were not flagged for dynamic registration by the client.
393
- #
394
- # @param methods [Array<String>] The methods to register
395
- # @return [void]
396
- def register_capabilities methods
397
- logger.debug "Registering capabilities: #{methods}"
398
- registrations = methods.select { |m| can_register?(m) and !registered?(m) }.map do |m|
399
- @registered_capabilities.add m
400
- {
401
- id: m,
402
- method: m,
403
- registerOptions: dynamic_capability_options[m]
404
- }
405
- end
406
- return if registrations.empty?
407
- send_request 'client/registerCapability', { registrations: registrations }
408
- end
409
-
410
- # Unregister the methods with the client.
411
- # This method will avoid duplicating unregistrations and ignore methods
412
- # that were not flagged for dynamic registration by the client.
413
- #
414
- # @param methods [Array<String>] The methods to unregister
415
- # @return [void]
416
- def unregister_capabilities methods
417
- logger.debug "Unregistering capabilities: #{methods}"
418
- unregisterations = methods.select{|m| registered?(m)}.map{ |m|
419
- @registered_capabilities.delete m
420
- {
421
- id: m,
422
- method: m
423
- }
424
- }
425
- return if unregisterations.empty?
426
- send_request 'client/unregisterCapability', { unregisterations: unregisterations }
427
- end
428
-
429
- # Flag a method as available for dynamic registration.
430
- #
431
- # @param method [String] The method name, e.g., 'textDocument/completion'
432
- # @return [void]
433
- def allow_registration method
434
- @dynamic_capabilities.add method
435
- end
436
-
437
- # True if the specified LSP method can be dynamically registered.
438
- #
439
- # @param method [String]
440
- # @return [Boolean]
441
- def can_register? method
442
- @dynamic_capabilities.include?(method)
443
- end
444
-
445
- # True if the specified method has been registered.
446
- #
447
- # @param method [String] The method name, e.g., 'textDocument/completion'
448
- # @return [Boolean]
449
- def registered? method
450
- @registered_capabilities.include?(method)
451
- end
452
-
453
- def synchronizing?
454
- !libraries.all?(&:synchronized?)
455
- end
456
-
457
- # @return [void]
458
- def stop
459
- return if @stopped
460
- @stopped = true
461
- message_worker.stop
462
- diagnoser.stop
463
- changed
464
- notify_observers
465
- end
466
-
467
- def stopped?
468
- @stopped
469
- end
470
-
471
- # Locate multiple pins that match a completion item. The first match is
472
- # based on the corresponding location in a library source if available.
473
- # Subsequent matches are based on path.
474
- #
475
- # @param params [Hash] A hash representation of a completion item
476
- # @return [Array<Pin::Base>]
477
- def locate_pins params
478
- return [] unless params['data'] && params['data']['uri']
479
- library = library_for(params['data']['uri'])
480
- # @type [Array<Pin::Base>]
481
- result = []
482
- if params['data']['location']
483
- location = Location.new(
484
- params['data']['location']['filename'],
485
- Range.from_to(
486
- params['data']['location']['range']['start']['line'],
487
- params['data']['location']['range']['start']['character'],
488
- params['data']['location']['range']['end']['line'],
489
- params['data']['location']['range']['end']['character']
490
- )
491
- )
492
- result.concat library.locate_pins(location).select{ |pin| pin.name == params['label'] }
493
- end
494
- if params['data']['path']
495
- result.concat library.path_pins(params['data']['path'])
496
- # @todo This exception is necessary because `Library#path_pins` does
497
- # not perform a namespace method query, so the implicit `.new` pin
498
- # might not exist.
499
- if result.empty? && params['data']['path'] =~ /\.new$/
500
- result.concat(library.path_pins(params['data']['path'].sub(/\.new$/, '#initialize')).map do |pin|
501
- next pin unless pin.name == 'initialize'
502
-
503
- Pin::Method.new(
504
- name: 'new',
505
- scope: :class,
506
- location: pin.location,
507
- # @sg-ignore Unresolved call to parameters on Solargraph::Pin::Base
508
- parameters: pin.parameters,
509
- return_type: ComplexType.try_parse(params['data']['path']),
510
- comments: pin.comments,
511
- closure: pin.closure,
512
- source: :solargraph
513
- )
514
- end)
515
- end
516
- end
517
- # Selecting by both location and path can result in duplicate pins
518
- result.uniq { |p| [p.path, p.location] }
519
- end
520
-
521
- # @param uri [String]
522
- # @return [String]
523
- def read_text uri
524
- library = library_for(uri)
525
- filename = uri_to_file(uri)
526
- library.read_text(filename)
527
- end
528
-
529
- # @param uri [String]
530
- # @return [Hash]
531
- def formatter_config uri
532
- library = library_for(uri)
533
- library.workspace.config.formatter
534
- end
535
-
536
- # @param uri [String]
537
- # @param line [Integer]
538
- # @param column [Integer]
539
- # @return [Solargraph::SourceMap::Completion, nil]
540
- def completions_at uri, line, column
541
- library = library_for(uri)
542
- library.completions_at uri_to_file(uri), line, column
543
- end
544
-
545
- # @return [Bool] if has pending completion request
546
- def has_pending_completions?
547
- message_worker.messages.reverse_each.any? { |req| req['method'] == 'textDocument/completion' }
548
- end
549
-
550
- # @param uri [String]
551
- # @param line [Integer]
552
- # @param column [Integer]
553
- # @return [Array<Solargraph::Pin::Base>, nil]
554
- def definitions_at uri, line, column
555
- library = library_for(uri)
556
- library.definitions_at(uri_to_file(uri), line, column)
557
- end
558
-
559
- # @param uri [String]
560
- # @param line [Integer]
561
- # @param column [Integer]
562
- # @return [Array<Solargraph::Pin::Base>, nil]
563
- def type_definitions_at uri, line, column
564
- library = library_for(uri)
565
- library.type_definitions_at(uri_to_file(uri), line, column)
566
- end
567
-
568
- # @param uri [String]
569
- # @param line [Integer]
570
- # @param column [Integer]
571
- # @return [Array<Solargraph::Pin::Base>]
572
- def signatures_at uri, line, column
573
- library = library_for(uri)
574
- library.signatures_at(uri_to_file(uri), line, column)
575
- end
576
-
577
- # @param uri [String]
578
- # @param line [Integer]
579
- # @param column [Integer]
580
- # @param strip [Boolean] Strip special characters from variable names
581
- # @param only [Boolean] If true, search current file only
582
- # @return [Array<Solargraph::Location>]
583
- def references_from uri, line, column, strip: true, only: false
584
- library = library_for(uri)
585
- library.references_from(uri_to_file(uri), line, column, strip: strip, only: only)
586
- rescue FileNotFoundError, InvalidOffsetError => e
587
- Solargraph.logger.warn "[#{e.class}] #{e.message}"
588
- Solargraph.logger.debug e.backtrace
589
- []
590
- end
591
-
592
- # @param query [String]
593
- # @return [Array<Solargraph::Pin::Base>]
594
- def query_symbols query
595
- result = []
596
- (libraries + [generic_library]).each { |lib| result.concat lib.query_symbols(query) }
597
- result.uniq
598
- end
599
-
600
- # @param query [String]
601
- # @return [Array<String>]
602
- def search query
603
- result = []
604
- libraries.each { |lib| result.concat lib.search(query) }
605
- result
606
- end
607
-
608
- # @param query [String]
609
- # @return [Array]
610
- def document query
611
- result = []
612
- if libraries.empty?
613
- result.concat generic_library.document(query)
614
- else
615
- libraries.each { |lib| result.concat lib.document(query) }
616
- end
617
- result
618
- end
619
-
620
- # @param uri [String]
621
- # @return [Array<Solargraph::Pin::Base>]
622
- def document_symbols uri
623
- library = library_for(uri)
624
- # At this level, document symbols should be unique; e.g., a
625
- # module_function method should return the location for Module.method
626
- # or Module#method, but not both.
627
- library.document_symbols(uri_to_file(uri)).uniq(&:location)
628
- end
629
-
630
- # Send a notification to the client.
631
- #
632
- # @param text [String]
633
- # @param type [Integer] A MessageType constant
634
- # @return [void]
635
- def show_message text, type = LanguageServer::MessageTypes::INFO
636
- send_notification 'window/showMessage', {
637
- type: type,
638
- message: text
639
- }
640
- end
641
-
642
- # Send a notification with optional responses.
643
- #
644
- # @param text [String]
645
- # @param type [Integer] A MessageType constant
646
- # @param actions [Array<String>] Response options for the client
647
- # @param block The block that processes the response
648
- # @yieldparam [String] The action received from the client
649
- # @return [void]
650
- def show_message_request text, type, actions, &block
651
- send_request 'window/showMessageRequest', {
652
- type: type,
653
- message: text,
654
- actions: actions
655
- }, &block
656
- end
657
-
658
- # Get a list of IDs for server requests that are waiting for responses
659
- # from the client.
660
- #
661
- # @return [Array<Integer>]
662
- def pending_requests
663
- requests.keys
664
- end
665
-
666
- # @return [Hash{String => [Boolean,String]}]
667
- def default_configuration
668
- {
669
- 'completion' => true,
670
- 'hover' => true,
671
- 'symbols' => true,
672
- 'definitions' => true,
673
- 'typeDefinitions' => true,
674
- 'rename' => true,
675
- 'references' => true,
676
- 'autoformat' => false,
677
- 'diagnostics' => true,
678
- 'formatting' => false,
679
- 'folding' => true,
680
- 'highlights' => true,
681
- 'logLevel' => 'warn'
682
- }
683
- end
684
-
685
- # @param uri [String]
686
- # @return [Array<Range>]
687
- def folding_ranges uri
688
- sources.find(uri).folding_ranges
689
- end
690
-
691
- # @return [void]
692
- def catalog
693
- return unless libraries.all?(&:mapped?)
694
- libraries.each(&:catalog)
695
- end
696
-
697
- # @return [Hash{String => Hash{String => Boolean}}]
698
- def client_capabilities
699
- @client_capabilities ||= {}
700
- end
701
-
702
- def client_supports_progress?
703
- client_capabilities['window'] && client_capabilities['window']['workDoneProgress']
704
- end
705
-
706
- private
707
-
708
- # @return [Array<Integer>]
709
- def cancelled
710
- @cancelled ||= []
711
- end
712
-
713
- # @return [MessageWorker]
714
- def message_worker
715
- @message_worker ||= MessageWorker.new(self)
716
- end
717
-
718
- # @return [Diagnoser]
719
- def diagnoser
720
- @diagnoser ||= Diagnoser.new(self)
721
- end
722
-
723
- # A hash of client requests by ID. The host uses this to keep track of
724
- # pending responses.
725
- #
726
- # @return [Hash{Integer => Solargraph::LanguageServer::Request}]
727
- def requests
728
- @requests ||= {}
729
- end
730
-
731
- # @param path [String]
732
- # @return [String]
733
- def normalize_separators path
734
- return path if File::ALT_SEPARATOR.nil?
735
- path.gsub(File::ALT_SEPARATOR, File::SEPARATOR)
736
- end
737
-
738
- # @param params [Hash]
739
- # @return [Source::Updater]
740
- def generate_updater params
741
- changes = []
742
- params['contentChanges'].each do |recvd|
743
- chng = check_diff(params['textDocument']['uri'], recvd)
744
- changes.push Solargraph::Source::Change.new(
745
- (chng['range'].nil? ?
746
- nil :
747
- Solargraph::Range.from_to(chng['range']['start']['line'], chng['range']['start']['character'], chng['range']['end']['line'], chng['range']['end']['character'])
748
- ),
749
- chng['text']
750
- )
751
- end
752
- Solargraph::Source::Updater.new(
753
- uri_to_file(params['textDocument']['uri']),
754
- params['textDocument']['version'],
755
- changes
756
- )
757
- end
758
-
759
- # @param uri [String]
760
- # @param change [Hash]
761
- # @return [Hash]
762
- def check_diff uri, change
763
- return change if change['range']
764
- source = sources.find(uri)
765
- return change if source.code.length + 1 != change['text'].length
766
- diffs = Diff::LCS.diff(source.code, change['text'])
767
- return change if diffs.length.zero? || diffs.length > 1 || diffs.first.length > 1
768
- # @sg-ignore push this upstream
769
- # @type [Diff::LCS::Change]
770
- diff = diffs.first.first
771
- return change unless diff.adding? && ['.', ':', '(', ',', ' '].include?(diff.element)
772
- position = Solargraph::Position.from_offset(source.code, diff.position)
773
- {
774
- 'range' => {
775
- 'start' => {
776
- 'line' => position.line,
777
- 'character' => position.character
778
- },
779
- 'end' => {
780
- 'line' => position.line,
781
- 'character' => position.character
782
- }
783
- },
784
- 'text' => diff.element
785
- }
786
- rescue Solargraph::FileNotFoundError
787
- change
788
- end
789
-
790
- # @return [Hash]
791
- def dynamic_capability_options
792
- @dynamic_capability_options ||= {
793
- # textDocumentSync: 2, # @todo What should this be?
794
- 'textDocument/completion' => {
795
- resolveProvider: true,
796
- triggerCharacters: ['.', ':', '@']
797
- },
798
- # hoverProvider: true,
799
- # definitionProvider: true,
800
- 'textDocument/signatureHelp' => {
801
- triggerCharacters: ['(', ',', ' ']
802
- },
803
- # documentFormattingProvider: true,
804
- 'textDocument/onTypeFormatting' => {
805
- firstTriggerCharacter: '{',
806
- moreTriggerCharacter: ['(']
807
- },
808
- # documentSymbolProvider: true,
809
- # workspaceSymbolProvider: true,
810
- # workspace: {
811
- # workspaceFolders: {
812
- # supported: true,
813
- # changeNotifications: true
814
- # }
815
- # }
816
- 'textDocument/definition' => {
817
- definitionProvider: true
818
- },
819
- 'textDocument/typeDefinition' => {
820
- typeDefinitionProvider: true
821
- },
822
- 'textDocument/references' => {
823
- referencesProvider: true
824
- },
825
- 'textDocument/rename' => {
826
- renameProvider: prepare_rename? ? { prepareProvider: true } : true
827
- },
828
- 'textDocument/documentSymbol' => {
829
- documentSymbolProvider: true
830
- },
831
- 'workspace/symbol' => {
832
- workspaceSymbolProvider: true
833
- },
834
- 'textDocument/formatting' => {
835
- formattingProvider: true
836
- },
837
- 'textDocument/foldingRange' => {
838
- foldingRangeProvider: true
839
- },
840
- 'textDocument/codeAction' => {
841
- codeActionProvider: true
842
- },
843
- 'textDocument/documentHighlight' => {
844
- documentHighlightProvider: true
845
- }
846
- }
847
- end
848
-
849
- def prepare_rename?
850
- client_capabilities['rename'] && client_capabilities['rename']['prepareSupport']
851
- end
852
-
853
- # @param library [Library]
854
- # @return [void]
855
- def library_map library
856
- return if library.mapped?
857
- Thread.new { sync_library_map library }
858
- end
859
-
860
- # @param library [Library]
861
- # @param uuid [String, nil]
862
- # @return [void]
863
- def sync_library_map library
864
- total = library.workspace.sources.length
865
- progress = Progress.new('Mapping workspace')
866
- progress.begin "0/#{total} files", 0
867
- progress.send self
868
- while library.next_map
869
- pct = ((library.source_map_hash.keys.length.to_f / total) * 100).to_i
870
- progress.report "#{library.source_map_hash.keys.length}/#{total} files", pct
871
- progress.send self
872
- end
873
- progress.finish 'done'
874
- progress.send self
875
- end
876
- end
877
- end
878
- end
1
+ # frozen_string_literal: true
2
+
3
+ require 'diff/lcs'
4
+ require 'observer'
5
+ require 'securerandom'
6
+
7
+ module Solargraph
8
+ module LanguageServer
9
+ # The language server protocol's data provider. Hosts are responsible for
10
+ # querying the library and processing messages. They also provide thread
11
+ # safety for multi-threaded transports.
12
+ #
13
+ class Host
14
+ autoload :Diagnoser, 'solargraph/language_server/host/diagnoser'
15
+ autoload :Sources, 'solargraph/language_server/host/sources'
16
+ autoload :Dispatch, 'solargraph/language_server/host/dispatch'
17
+ autoload :MessageWorker, 'solargraph/language_server/host/message_worker'
18
+
19
+ include UriHelpers
20
+ include Logging
21
+ include Dispatch
22
+ include Observable
23
+
24
+ attr_writer :client_capabilities
25
+
26
+ def initialize
27
+ @buffer_semaphore = Mutex.new
28
+ @request_mutex = Mutex.new
29
+ @buffer = String.new
30
+ @stopped = true
31
+ @next_request_id = 1
32
+ @dynamic_capabilities = Set.new
33
+ @registered_capabilities = Set.new
34
+ end
35
+
36
+ # Start asynchronous process handling.
37
+ #
38
+ # @return [void]
39
+ def start
40
+ return unless stopped?
41
+ @stopped = false
42
+ diagnoser.start
43
+ message_worker.start
44
+ end
45
+
46
+ # Update the configuration options with the provided hash.
47
+ #
48
+ # @param update [Hash]
49
+ # @return [void]
50
+ def configure update
51
+ return if update.nil?
52
+ options.merge! update
53
+ logger.level = LOG_LEVELS[options['logLevel']] || DEFAULT_LOG_LEVEL
54
+ end
55
+
56
+ # @return [Hash{String => [Boolean, String]}]
57
+ def options
58
+ @options ||= default_configuration
59
+ end
60
+
61
+ # Cancel the method with the specified ID.
62
+ #
63
+ # @param id [Integer]
64
+ # @return [void]
65
+ def cancel id
66
+ cancelled.push id
67
+ end
68
+
69
+ # True if the host received a request to cancel the method with the
70
+ # specified ID.
71
+ #
72
+ # @param id [Integer]
73
+ # @return [Boolean]
74
+ def cancel? id
75
+ cancelled.include? id
76
+ end
77
+
78
+ # Delete the specified ID from the list of cancelled IDs if it exists.
79
+ #
80
+ # @param id [Integer]
81
+ # @return [void]
82
+ def clear id
83
+ cancelled.delete id
84
+ end
85
+
86
+ # Called by adapter, to handle the request
87
+ # @param request [Hash]
88
+ # @return [void]
89
+ def process request
90
+ message_worker.queue(request)
91
+ end
92
+
93
+ # Start processing a request from the client. After the message is
94
+ # processed, caller is responsible for sending the response.
95
+ #
96
+ # @param request [Hash{String => unspecified}] The contents of the message.
97
+ #
98
+ # @return [Solargraph::LanguageServer::Message::Base, Solargraph::LanguageServer::Request, nil] The message handler.
99
+ def receive request
100
+ if request['method']
101
+ logger.info "Host received ##{request['id']} #{request['method']}"
102
+ logger.debug request
103
+ message = Message.select(request['method']).new(self, request)
104
+ begin
105
+ message.process unless cancel?(request['id'])
106
+ rescue StandardError => e
107
+ logger.warn "Error processing request: [#{e.class}] #{e.message}"
108
+ logger.warn e.backtrace.join("\n")
109
+ message.set_error Solargraph::LanguageServer::ErrorCodes::INTERNAL_ERROR, "[#{e.class}] #{e.message}"
110
+ end
111
+ message
112
+ elsif request['id']
113
+ if requests[request['id']]
114
+ requests[request['id']].process(request['result'])
115
+ requests.delete request['id']
116
+ else
117
+ logger.warn "Discarding client response to unrecognized message #{request['id']}"
118
+ nil
119
+ end
120
+ else
121
+ logger.warn "Invalid message received."
122
+ logger.debug request
123
+ nil
124
+ end
125
+ end
126
+
127
+ # Respond to a notification that files were created in the workspace.
128
+ # The libraries will determine whether the files should be merged; see
129
+ # Solargraph::Library#create_from_disk.
130
+ #
131
+ # @param uris [Array<String>] The URIs of the files.
132
+ # @return [Boolean] True if at least one library accepted at least one file.
133
+ def create *uris
134
+ filenames = uris.map { |uri| uri_to_file(uri) }
135
+ result = false
136
+ libraries.each do |lib|
137
+ result = true if lib.create_from_disk(*filenames)
138
+ end
139
+ uris.each do |uri|
140
+ diagnoser.schedule uri if open?(uri)
141
+ end
142
+ result
143
+ end
144
+
145
+ # Delete the specified files from the library.
146
+ #
147
+ # @param uris [Array<String>] The file uris.
148
+ # @return [void]
149
+ def delete *uris
150
+ filenames = uris.map { |uri| uri_to_file(uri) }
151
+ libraries.each do |lib|
152
+ lib.delete_observer self
153
+ lib.delete(*filenames)
154
+ end
155
+ uris.each do |uri|
156
+ send_notification "textDocument/publishDiagnostics", {
157
+ uri: uri,
158
+ diagnostics: []
159
+ }
160
+ end
161
+ end
162
+
163
+ # Open the specified file in the library.
164
+ #
165
+ # @param uri [String] The file uri.
166
+ # @param text [String] The contents of the file.
167
+ # @param version [Integer] A version number.
168
+ # @return [void]
169
+ def open uri, text, version
170
+ src = sources.open(uri, text, version)
171
+ libraries.each do |lib|
172
+ lib.merge src
173
+ end
174
+ diagnoser.schedule uri
175
+ end
176
+
177
+ # @param uri [String]
178
+ # @return [void]
179
+ def open_from_disk uri
180
+ sources.open_from_disk(uri)
181
+ diagnoser.schedule uri
182
+ end
183
+
184
+ # True if the specified file is currently open in the library.
185
+ #
186
+ # @param uri [String]
187
+ # @return [Boolean]
188
+ def open? uri
189
+ sources.include? uri
190
+ end
191
+
192
+ # Close the file specified by the URI.
193
+ #
194
+ # @param uri [String]
195
+ # @return [void]
196
+ def close uri
197
+ logger.info "Closing #{uri}"
198
+ sources.close uri
199
+ diagnoser.schedule uri
200
+ end
201
+
202
+ # @param uri [String]
203
+ # @return [void]
204
+ def diagnose uri
205
+ if sources.include?(uri)
206
+ library = library_for(uri)
207
+ if library.mapped? && library.synchronized?
208
+ logger.info "Diagnosing #{uri}"
209
+ begin
210
+ results = library.diagnose uri_to_file(uri)
211
+ send_notification "textDocument/publishDiagnostics", {
212
+ uri: uri,
213
+ diagnostics: results
214
+ }
215
+ rescue DiagnosticsError => e
216
+ logger.warn "Error in diagnostics: #{e.message}"
217
+ options['diagnostics'] = false
218
+ send_notification 'window/showMessage', {
219
+ type: LanguageServer::MessageTypes::ERROR,
220
+ message: "Error in diagnostics: #{e.message}"
221
+ }
222
+ rescue FileNotFoundError => e
223
+ # @todo This appears to happen when an external file is open and
224
+ # scheduled for diagnosis, but the file was closed (i.e., the
225
+ # editor moved to a different file) before diagnosis started
226
+ logger.warn "Unable to diagnose #{uri} : #{e.message}"
227
+ send_notification 'textDocument/publishDiagnostics', {
228
+ uri: uri,
229
+ diagnostics: []
230
+ }
231
+ end
232
+ else
233
+ logger.info "Deferring diagnosis of #{uri}"
234
+ diagnoser.schedule uri
235
+ end
236
+ else
237
+ send_notification 'textDocument/publishDiagnostics', {
238
+ uri: uri,
239
+ diagnostics: []
240
+ }
241
+ end
242
+ end
243
+
244
+ # Update a document from the parameters of a textDocument/didChange
245
+ # method.
246
+ #
247
+ # @param params [Hash]
248
+ # @return [void]
249
+ def change params
250
+ updater = generate_updater(params)
251
+ sources.update params['textDocument']['uri'], updater
252
+ diagnoser.schedule params['textDocument']['uri']
253
+ end
254
+
255
+ # Queue a message to be sent to the client.
256
+ #
257
+ # @param message [String] The message to send.
258
+ # @return [void]
259
+ def queue message
260
+ @buffer_semaphore.synchronize { @buffer += message }
261
+ changed
262
+ notify_observers
263
+ end
264
+
265
+ # Clear the message buffer and return the most recent data.
266
+ #
267
+ # @return [String] The most recent data or an empty string.
268
+ def flush
269
+ tmp = ''
270
+ @buffer_semaphore.synchronize do
271
+ tmp = @buffer.clone
272
+ @buffer.clear
273
+ end
274
+ tmp
275
+ end
276
+
277
+ # Prepare a library for the specified directory.
278
+ #
279
+ # @param directory [String]
280
+ # @param name [String, nil]
281
+ # @return [void]
282
+ def prepare directory, name = nil
283
+ # No need to create a library without a directory. The generic library
284
+ # will handle it.
285
+ return if directory.nil?
286
+ logger.info "Preparing library for #{directory}"
287
+ path = ''
288
+ path = normalize_separators(directory) unless directory.nil?
289
+ begin
290
+ workspace = Solargraph::Workspace.new(path, nil, options)
291
+ lib = Solargraph::Library.new(workspace, name)
292
+ lib.add_observer self
293
+ libraries.push lib
294
+ library_map lib
295
+ rescue WorkspaceTooLargeError => e
296
+ send_notification 'window/showMessage', {
297
+ 'type' => Solargraph::LanguageServer::MessageTypes::WARNING,
298
+ 'message' => e.message
299
+ }
300
+ end
301
+ end
302
+
303
+ # @return [String]
304
+ def command_path
305
+ options['commandPath'] || 'solargraph'
306
+ end
307
+
308
+ # Prepare multiple folders.
309
+ #
310
+ # @param array [Array<Hash{String => String}>]
311
+ # @return [void]
312
+ def prepare_folders array
313
+ return if array.nil?
314
+ array.each do |folder|
315
+ prepare uri_to_file(folder['uri']), folder['name']
316
+ end
317
+ end
318
+
319
+ # Remove a directory.
320
+ #
321
+ # @param directory [String]
322
+ # @return [void]
323
+ def remove directory
324
+ logger.info "Removing library for #{directory}"
325
+ # @param lib [Library]
326
+ libraries.delete_if do |lib|
327
+ next false if lib.workspace.directory != directory
328
+ lib.delete_observer self
329
+ true
330
+ end
331
+ end
332
+
333
+ # @param array [Array<Hash>]
334
+ # @return [void]
335
+ def remove_folders array
336
+ array.each do |folder|
337
+ remove uri_to_file(folder['uri'])
338
+ end
339
+ end
340
+
341
+ # @return [Array<String>]
342
+ def folders
343
+ libraries.map { |lib| lib.workspace.directory }
344
+ end
345
+
346
+ # Send a notification to the client.
347
+ #
348
+ # @param method [String] The message method
349
+ # @param params [Hash] The method parameters
350
+ # @return [void]
351
+ def send_notification method, params
352
+ response = {
353
+ jsonrpc: "2.0",
354
+ method: method,
355
+ params: params
356
+ }
357
+ json = response.to_json
358
+ envelope = "Content-Length: #{json.bytesize}\r\n\r\n#{json}"
359
+ queue envelope
360
+ logger.info "Server sent #{method}"
361
+ logger.debug params
362
+ end
363
+
364
+ # Send a request to the client and execute the provided block to process
365
+ # the response. If an ID is not provided, the host will use an auto-
366
+ # incrementing integer.
367
+ #
368
+ # @param method [String] The message method
369
+ # @param params [Hash] The method parameters
370
+ # @param block [Proc] The block that processes the response
371
+ # @yieldparam [Hash] The result sent by the client
372
+ # @return [void]
373
+ def send_request method, params, &block
374
+ @request_mutex.synchronize do
375
+ message = {
376
+ jsonrpc: "2.0",
377
+ method: method,
378
+ params: params,
379
+ id: @next_request_id
380
+ }
381
+ json = message.to_json
382
+ requests[@next_request_id] = Request.new(@next_request_id, &block)
383
+ envelope = "Content-Length: #{json.bytesize}\r\n\r\n#{json}"
384
+ queue envelope
385
+ @next_request_id += 1
386
+ logger.debug params
387
+ end
388
+ end
389
+
390
+ # Register the methods as capabilities with the client.
391
+ # This method will avoid duplicating registrations and ignore methods
392
+ # that were not flagged for dynamic registration by the client.
393
+ #
394
+ # @param methods [Array<String>] The methods to register
395
+ # @return [void]
396
+ def register_capabilities methods
397
+ logger.debug "Registering capabilities: #{methods}"
398
+ registrations = methods.select { |m| can_register?(m) and !registered?(m) }.map do |m|
399
+ @registered_capabilities.add m
400
+ {
401
+ id: m,
402
+ method: m,
403
+ registerOptions: dynamic_capability_options[m]
404
+ }
405
+ end
406
+ return if registrations.empty?
407
+ send_request 'client/registerCapability', { registrations: registrations }
408
+ end
409
+
410
+ # Unregister the methods with the client.
411
+ # This method will avoid duplicating unregistrations and ignore methods
412
+ # that were not flagged for dynamic registration by the client.
413
+ #
414
+ # @param methods [Array<String>] The methods to unregister
415
+ # @return [void]
416
+ def unregister_capabilities methods
417
+ logger.debug "Unregistering capabilities: #{methods}"
418
+ unregisterations = methods.select{|m| registered?(m)}.map{ |m|
419
+ @registered_capabilities.delete m
420
+ {
421
+ id: m,
422
+ method: m
423
+ }
424
+ }
425
+ return if unregisterations.empty?
426
+ send_request 'client/unregisterCapability', { unregisterations: unregisterations }
427
+ end
428
+
429
+ # Flag a method as available for dynamic registration.
430
+ #
431
+ # @param method [String] The method name, e.g., 'textDocument/completion'
432
+ # @return [void]
433
+ def allow_registration method
434
+ @dynamic_capabilities.add method
435
+ end
436
+
437
+ # True if the specified LSP method can be dynamically registered.
438
+ #
439
+ # @param method [String]
440
+ # @return [Boolean]
441
+ def can_register? method
442
+ @dynamic_capabilities.include?(method)
443
+ end
444
+
445
+ # True if the specified method has been registered.
446
+ #
447
+ # @param method [String] The method name, e.g., 'textDocument/completion'
448
+ # @return [Boolean]
449
+ def registered? method
450
+ @registered_capabilities.include?(method)
451
+ end
452
+
453
+ def synchronizing?
454
+ !libraries.all?(&:synchronized?)
455
+ end
456
+
457
+ # @return [void]
458
+ def stop
459
+ return if @stopped
460
+ @stopped = true
461
+ message_worker.stop
462
+ diagnoser.stop
463
+ changed
464
+ notify_observers
465
+ end
466
+
467
+ def stopped?
468
+ @stopped
469
+ end
470
+
471
+ # Locate multiple pins that match a completion item. The first match is
472
+ # based on the corresponding location in a library source if available.
473
+ # Subsequent matches are based on path.
474
+ #
475
+ # @param params [Hash] A hash representation of a completion item
476
+ # @return [Array<Pin::Base>]
477
+ def locate_pins params
478
+ return [] unless params['data'] && params['data']['uri']
479
+ library = library_for(params['data']['uri'])
480
+ # @type [Array<Pin::Base>]
481
+ result = []
482
+ if params['data']['location']
483
+ location = Location.new(
484
+ params['data']['location']['filename'],
485
+ Range.from_to(
486
+ params['data']['location']['range']['start']['line'],
487
+ params['data']['location']['range']['start']['character'],
488
+ params['data']['location']['range']['end']['line'],
489
+ params['data']['location']['range']['end']['character']
490
+ )
491
+ )
492
+ result.concat library.locate_pins(location).select{ |pin| pin.name == params['label'] }
493
+ end
494
+ if params['data']['path']
495
+ result.concat library.path_pins(params['data']['path'])
496
+ # @todo This exception is necessary because `Library#path_pins` does
497
+ # not perform a namespace method query, so the implicit `.new` pin
498
+ # might not exist.
499
+ if result.empty? && params['data']['path'] =~ /\.new$/
500
+ result.concat(library.path_pins(params['data']['path'].sub(/\.new$/, '#initialize')).map do |pin|
501
+ next pin unless pin.name == 'initialize'
502
+
503
+ Pin::Method.new(
504
+ name: 'new',
505
+ scope: :class,
506
+ location: pin.location,
507
+ # @sg-ignore Unresolved call to parameters on Solargraph::Pin::Base
508
+ parameters: pin.parameters,
509
+ return_type: ComplexType.try_parse(params['data']['path']),
510
+ comments: pin.comments,
511
+ closure: pin.closure,
512
+ source: :solargraph
513
+ )
514
+ end)
515
+ end
516
+ end
517
+ # Selecting by both location and path can result in duplicate pins
518
+ result.uniq { |p| [p.path, p.location] }
519
+ end
520
+
521
+ # @param uri [String]
522
+ # @return [String]
523
+ def read_text uri
524
+ library = library_for(uri)
525
+ filename = uri_to_file(uri)
526
+ library.read_text(filename)
527
+ end
528
+
529
+ # @param uri [String]
530
+ # @return [Hash]
531
+ def formatter_config uri
532
+ library = library_for(uri)
533
+ library.workspace.config.formatter
534
+ end
535
+
536
+ # @param uri [String]
537
+ # @param line [Integer]
538
+ # @param column [Integer]
539
+ # @return [Solargraph::SourceMap::Completion, nil]
540
+ def completions_at uri, line, column
541
+ library = library_for(uri)
542
+ library.completions_at uri_to_file(uri), line, column
543
+ end
544
+
545
+ # @return [Bool] if has pending completion request
546
+ def has_pending_completions?
547
+ message_worker.messages.reverse_each.any? { |req| req['method'] == 'textDocument/completion' }
548
+ end
549
+
550
+ # @param uri [String]
551
+ # @param line [Integer]
552
+ # @param column [Integer]
553
+ # @return [Array<Solargraph::Pin::Base>, nil]
554
+ def definitions_at uri, line, column
555
+ library = library_for(uri)
556
+ library.definitions_at(uri_to_file(uri), line, column)
557
+ end
558
+
559
+ # @param uri [String]
560
+ # @param line [Integer]
561
+ # @param column [Integer]
562
+ # @return [Array<Solargraph::Pin::Base>, nil]
563
+ def type_definitions_at uri, line, column
564
+ library = library_for(uri)
565
+ library.type_definitions_at(uri_to_file(uri), line, column)
566
+ end
567
+
568
+ # @param uri [String]
569
+ # @param line [Integer]
570
+ # @param column [Integer]
571
+ # @return [Array<Solargraph::Pin::Base>]
572
+ def signatures_at uri, line, column
573
+ library = library_for(uri)
574
+ library.signatures_at(uri_to_file(uri), line, column)
575
+ end
576
+
577
+ # @param uri [String]
578
+ # @param line [Integer]
579
+ # @param column [Integer]
580
+ # @param strip [Boolean] Strip special characters from variable names
581
+ # @param only [Boolean] If true, search current file only
582
+ # @return [Array<Solargraph::Location>]
583
+ def references_from uri, line, column, strip: true, only: false
584
+ library = library_for(uri)
585
+ library.references_from(uri_to_file(uri), line, column, strip: strip, only: only)
586
+ rescue FileNotFoundError, InvalidOffsetError => e
587
+ Solargraph.logger.warn "[#{e.class}] #{e.message}"
588
+ Solargraph.logger.debug e.backtrace
589
+ []
590
+ end
591
+
592
+ # @param query [String]
593
+ # @return [Array<Solargraph::Pin::Base>]
594
+ def query_symbols query
595
+ result = []
596
+ (libraries + [generic_library]).each { |lib| result.concat lib.query_symbols(query) }
597
+ result.uniq
598
+ end
599
+
600
+ # @param query [String]
601
+ # @return [Array<String>]
602
+ def search query
603
+ result = []
604
+ libraries.each { |lib| result.concat lib.search(query) }
605
+ result
606
+ end
607
+
608
+ # @param query [String]
609
+ # @return [Array]
610
+ def document query
611
+ result = []
612
+ if libraries.empty?
613
+ result.concat generic_library.document(query)
614
+ else
615
+ libraries.each { |lib| result.concat lib.document(query) }
616
+ end
617
+ result
618
+ end
619
+
620
+ # @param uri [String]
621
+ # @return [Array<Solargraph::Pin::Base>]
622
+ def document_symbols uri
623
+ library = library_for(uri)
624
+ # At this level, document symbols should be unique; e.g., a
625
+ # module_function method should return the location for Module.method
626
+ # or Module#method, but not both.
627
+ library.document_symbols(uri_to_file(uri)).uniq(&:location)
628
+ end
629
+
630
+ # Send a notification to the client.
631
+ #
632
+ # @param text [String]
633
+ # @param type [Integer] A MessageType constant
634
+ # @return [void]
635
+ def show_message text, type = LanguageServer::MessageTypes::INFO
636
+ send_notification 'window/showMessage', {
637
+ type: type,
638
+ message: text
639
+ }
640
+ end
641
+
642
+ # Send a notification with optional responses.
643
+ #
644
+ # @param text [String]
645
+ # @param type [Integer] A MessageType constant
646
+ # @param actions [Array<String>] Response options for the client
647
+ # @param block The block that processes the response
648
+ # @yieldparam [String] The action received from the client
649
+ # @return [void]
650
+ def show_message_request text, type, actions, &block
651
+ send_request 'window/showMessageRequest', {
652
+ type: type,
653
+ message: text,
654
+ actions: actions
655
+ }, &block
656
+ end
657
+
658
+ # Get a list of IDs for server requests that are waiting for responses
659
+ # from the client.
660
+ #
661
+ # @return [Array<Integer>]
662
+ def pending_requests
663
+ requests.keys
664
+ end
665
+
666
+ # @return [Hash{String => [Boolean,String]}]
667
+ def default_configuration
668
+ {
669
+ 'completion' => true,
670
+ 'hover' => true,
671
+ 'symbols' => true,
672
+ 'definitions' => true,
673
+ 'typeDefinitions' => true,
674
+ 'rename' => true,
675
+ 'references' => true,
676
+ 'autoformat' => false,
677
+ 'diagnostics' => true,
678
+ 'formatting' => false,
679
+ 'folding' => true,
680
+ 'highlights' => true,
681
+ 'logLevel' => 'warn'
682
+ }
683
+ end
684
+
685
+ # @param uri [String]
686
+ # @return [Array<Range>]
687
+ def folding_ranges uri
688
+ sources.find(uri).folding_ranges
689
+ end
690
+
691
+ # @return [void]
692
+ def catalog
693
+ return unless libraries.all?(&:mapped?)
694
+ libraries.each(&:catalog)
695
+ end
696
+
697
+ # @return [Hash{String => Hash{String => Boolean}}]
698
+ def client_capabilities
699
+ @client_capabilities ||= {}
700
+ end
701
+
702
+ def client_supports_progress?
703
+ client_capabilities['window'] && client_capabilities['window']['workDoneProgress']
704
+ end
705
+
706
+ private
707
+
708
+ # @return [Array<Integer>]
709
+ def cancelled
710
+ @cancelled ||= []
711
+ end
712
+
713
+ # @return [MessageWorker]
714
+ def message_worker
715
+ @message_worker ||= MessageWorker.new(self)
716
+ end
717
+
718
+ # @return [Diagnoser]
719
+ def diagnoser
720
+ @diagnoser ||= Diagnoser.new(self)
721
+ end
722
+
723
+ # A hash of client requests by ID. The host uses this to keep track of
724
+ # pending responses.
725
+ #
726
+ # @return [Hash{Integer => Solargraph::LanguageServer::Request}]
727
+ def requests
728
+ @requests ||= {}
729
+ end
730
+
731
+ # @param path [String]
732
+ # @return [String]
733
+ def normalize_separators path
734
+ return path if File::ALT_SEPARATOR.nil?
735
+ path.gsub(File::ALT_SEPARATOR, File::SEPARATOR)
736
+ end
737
+
738
+ # @param params [Hash]
739
+ # @return [Source::Updater]
740
+ def generate_updater params
741
+ changes = []
742
+ params['contentChanges'].each do |recvd|
743
+ chng = check_diff(params['textDocument']['uri'], recvd)
744
+ changes.push Solargraph::Source::Change.new(
745
+ (chng['range'].nil? ?
746
+ nil :
747
+ Solargraph::Range.from_to(chng['range']['start']['line'], chng['range']['start']['character'], chng['range']['end']['line'], chng['range']['end']['character'])
748
+ ),
749
+ chng['text']
750
+ )
751
+ end
752
+ Solargraph::Source::Updater.new(
753
+ uri_to_file(params['textDocument']['uri']),
754
+ params['textDocument']['version'],
755
+ changes
756
+ )
757
+ end
758
+
759
+ # @param uri [String]
760
+ # @param change [Hash]
761
+ # @return [Hash]
762
+ def check_diff uri, change
763
+ return change if change['range']
764
+ source = sources.find(uri)
765
+ return change if source.code.length + 1 != change['text'].length
766
+ diffs = Diff::LCS.diff(source.code, change['text'])
767
+ return change if diffs.length.zero? || diffs.length > 1 || diffs.first.length > 1
768
+ # @sg-ignore push this upstream
769
+ # @type [Diff::LCS::Change]
770
+ diff = diffs.first.first
771
+ return change unless diff.adding? && ['.', ':', '(', ',', ' '].include?(diff.element)
772
+ position = Solargraph::Position.from_offset(source.code, diff.position)
773
+ {
774
+ 'range' => {
775
+ 'start' => {
776
+ 'line' => position.line,
777
+ 'character' => position.character
778
+ },
779
+ 'end' => {
780
+ 'line' => position.line,
781
+ 'character' => position.character
782
+ }
783
+ },
784
+ 'text' => diff.element
785
+ }
786
+ rescue Solargraph::FileNotFoundError
787
+ change
788
+ end
789
+
790
+ # @return [Hash]
791
+ def dynamic_capability_options
792
+ @dynamic_capability_options ||= {
793
+ # textDocumentSync: 2, # @todo What should this be?
794
+ 'textDocument/completion' => {
795
+ resolveProvider: true,
796
+ triggerCharacters: ['.', ':', '@']
797
+ },
798
+ # hoverProvider: true,
799
+ # definitionProvider: true,
800
+ 'textDocument/signatureHelp' => {
801
+ triggerCharacters: ['(', ',', ' ']
802
+ },
803
+ # documentFormattingProvider: true,
804
+ 'textDocument/onTypeFormatting' => {
805
+ firstTriggerCharacter: '{',
806
+ moreTriggerCharacter: ['(']
807
+ },
808
+ # documentSymbolProvider: true,
809
+ # workspaceSymbolProvider: true,
810
+ # workspace: {
811
+ # workspaceFolders: {
812
+ # supported: true,
813
+ # changeNotifications: true
814
+ # }
815
+ # }
816
+ 'textDocument/definition' => {
817
+ definitionProvider: true
818
+ },
819
+ 'textDocument/typeDefinition' => {
820
+ typeDefinitionProvider: true
821
+ },
822
+ 'textDocument/references' => {
823
+ referencesProvider: true
824
+ },
825
+ 'textDocument/rename' => {
826
+ renameProvider: prepare_rename? ? { prepareProvider: true } : true
827
+ },
828
+ 'textDocument/documentSymbol' => {
829
+ documentSymbolProvider: true
830
+ },
831
+ 'workspace/symbol' => {
832
+ workspaceSymbolProvider: true
833
+ },
834
+ 'textDocument/formatting' => {
835
+ formattingProvider: true
836
+ },
837
+ 'textDocument/foldingRange' => {
838
+ foldingRangeProvider: true
839
+ },
840
+ 'textDocument/codeAction' => {
841
+ codeActionProvider: true
842
+ },
843
+ 'textDocument/documentHighlight' => {
844
+ documentHighlightProvider: true
845
+ }
846
+ }
847
+ end
848
+
849
+ def prepare_rename?
850
+ client_capabilities['rename'] && client_capabilities['rename']['prepareSupport']
851
+ end
852
+
853
+ # @param library [Library]
854
+ # @return [void]
855
+ def library_map library
856
+ return if library.mapped?
857
+ Thread.new { sync_library_map library }
858
+ end
859
+
860
+ # @param library [Library]
861
+ # @param uuid [String, nil]
862
+ # @return [void]
863
+ def sync_library_map library
864
+ total = library.workspace.sources.length
865
+ progress = Progress.new('Mapping workspace')
866
+ progress.begin "0/#{total} files", 0
867
+ progress.send self
868
+ while library.next_map
869
+ pct = ((library.source_map_hash.keys.length.to_f / total) * 100).to_i
870
+ progress.report "#{library.source_map_hash.keys.length}/#{total} files", pct
871
+ progress.send self
872
+ end
873
+ progress.finish 'done'
874
+ progress.send self
875
+ end
876
+ end
877
+ end
878
+ end