solargraph 0.58.1 → 0.59.0.dev.1

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