solargraph 0.54.4 → 0.58.3

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