Class: Solargraph::LanguageServer::Host

Inherits:
Object
  • Object
show all
Includes:
Observable, Dispatch, UriHelpers, Solargraph::Logging
Defined in:
lib/solargraph/language_server/host.rb,
lib/solargraph/language_server/host/sources.rb,
lib/solargraph/language_server/host/dispatch.rb,
lib/solargraph/language_server/host/cataloger.rb,
lib/solargraph/language_server/host/diagnoser.rb

Overview

The language server protocol's data provider. Hosts are responsible for querying the library and processing messages. They also provide thread safety for multi-threaded transports.

Defined Under Namespace

Modules: Dispatch Classes: Cataloger, Diagnoser, Sources

Constant Summary

Constants included from Solargraph::Logging

Solargraph::Logging::DEFAULT_LOG_LEVEL, Solargraph::Logging::LOG_LEVELS

Instance Method Summary collapse

Methods included from Dispatch

#explicit_library_for, #generic_library, #generic_library_for, #implicit_library_for, #libraries, #library_for, #sources, #update_libraries

Methods included from Solargraph::Logging

logger

Methods included from UriHelpers

file_to_uri, uri_to_file

Constructor Details

#initializeHost


21
22
23
24
25
26
27
28
29
30
31
# File 'lib/solargraph/language_server/host.rb', line 21

def initialize
  @cancel_semaphore = Mutex.new
  @buffer_semaphore = Mutex.new
  @register_semaphore = Mutex.new
  @cancel = []
  @buffer = ''
  @stopped = true
  @next_request_id = 0
  @dynamic_capabilities = Set.new
  @registered_capabilities = Set.new
end

Instance Method Details

#allow_registration(method) ⇒ void

This method returns an undefined value.

Flag a method as available for dynamic registration.


402
403
404
405
406
# File 'lib/solargraph/language_server/host.rb', line 402

def allow_registration method
  @register_semaphore.synchronize do
    @dynamic_capabilities.add method
  end
end

#can_register?(method) ⇒ Boolean

True if the specified LSP method can be dynamically registered.


412
413
414
# File 'lib/solargraph/language_server/host.rb', line 412

def can_register? method
  @dynamic_capabilities.include?(method)
end

#cancel(id) ⇒ void

This method returns an undefined value.

Cancel the method with the specified ID.


63
64
65
# File 'lib/solargraph/language_server/host.rb', line 63

def cancel id
  @cancel_semaphore.synchronize { @cancel.push id }
end

#cancel?(id) ⇒ Boolean

True if the host received a request to cancel the method with the specified ID.


72
73
74
75
76
# File 'lib/solargraph/language_server/host.rb', line 72

def cancel? id
  result = false
  @cancel_semaphore.synchronize { result = @cancel.include? id }
  result
end

#catalogvoid


610
611
612
# File 'lib/solargraph/language_server/host.rb', line 610

def catalog
  libraries.each(&:catalog)
end

#change(params) ⇒ void

This method returns an undefined value.

Update a document from the parameters of a textDocument/didChange method.


224
225
226
227
228
# File 'lib/solargraph/language_server/host.rb', line 224

def change params
  updater = generate_updater(params)
  sources.async_update params['textDocument']['uri'], updater
  diagnoser.schedule params['textDocument']['uri']
end

#clear(id) ⇒ void

This method returns an undefined value.

Delete the specified ID from the list of cancelled IDs if it exists.


82
83
84
# File 'lib/solargraph/language_server/host.rb', line 82

def clear id
  @cancel_semaphore.synchronize { @cancel.delete id }
end

#close(uri) ⇒ void

This method returns an undefined value.

Close the file specified by the URI.


180
181
182
183
184
# File 'lib/solargraph/language_server/host.rb', line 180

def close uri
  logger.info "Closing #{uri}"
  sources.close uri
  diagnoser.schedule uri
end

#completions_at(uri, line, column) ⇒ Solargraph::SourceMap::Completion


483
484
485
486
# File 'lib/solargraph/language_server/host.rb', line 483

def completions_at uri, line, column
  library = library_for(uri)
  library.completions_at uri_to_file(uri), line, column
end

#configure(update) ⇒ void

This method returns an undefined value.

Update the configuration options with the provided hash.


48
49
50
51
52
# File 'lib/solargraph/language_server/host.rb', line 48

def configure update
  return if update.nil?
  options.merge! update
  logger.level = LOG_LEVELS[options['logLevel']] || DEFAULT_LOG_LEVEL
end

#create(uri) ⇒ Boolean

Respond to a notification that a file was created in the workspace. The libraries will determine whether the file should be merged; see Solargraph::Library#create_from_disk.


120
121
122
123
124
125
126
127
128
# File 'lib/solargraph/language_server/host.rb', line 120

def create uri
  filename = uri_to_file(uri)
  result = false
  libraries.each do |lib|
    result = true if lib.create_from_disk(filename)
  end
  diagnoser.schedule uri if open?(uri)
  result
end

#default_configurationHash{String => Object}


587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# File 'lib/solargraph/language_server/host.rb', line 587

def default_configuration
  {
    'completion' => true,
    'hover' => true,
    'symbols' => true,
    'definitions' => true,
    'rename' => true,
    'references' => true,
    'autoformat' => false,
    'diagnostics' => false,
    'formatting' => false,
    'folding' => true,
    'logLevel' => 'warn'
  }
end

#definitions_at(uri, line, column) ⇒ Array<Solargraph::Pin::Base>


492
493
494
495
# File 'lib/solargraph/language_server/host.rb', line 492

def definitions_at uri, line, column
  library = library_for(uri)
  library.definitions_at(uri_to_file(uri), line, column)
end

#delete(uri) ⇒ void

This method returns an undefined value.

Delete the specified file from the library.


134
135
136
137
138
139
140
141
142
143
# File 'lib/solargraph/language_server/host.rb', line 134

def delete uri
  filename = uri_to_file(uri)
  libraries.each do |lib|
    lib.delete(filename)
  end
  send_notification "textDocument/publishDiagnostics", {
    uri: uri,
    diagnostics: []
  }
end

#diagnose(uri) ⇒ void


188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/solargraph/language_server/host.rb', line 188

def diagnose uri
  if sources.include?(uri)
    library = library_for(uri)
    if library.synchronized?
      logger.info "Diagnosing #{uri}"
      begin
        results = library.diagnose uri_to_file(uri)
        send_notification "textDocument/publishDiagnostics", {
          uri: uri,
          diagnostics: results
        }
      rescue DiagnosticsError => e
        logger.warn "Error in diagnostics: #{e.message}"
        options['diagnostics'] = false
        send_notification 'window/showMessage', {
          type: LanguageServer::MessageTypes::ERROR,
          message: "Error in diagnostics: #{e.message}"
        }
      end
    else
      logger.info "Deferring diagnosis of #{uri}"
      diagnoser.schedule uri
    end
  else
    send_notification 'textDocument/publishDiagnostics', {
      uri: uri,
      diagnostics: []
    }
  end
end

#document(query) ⇒ String


534
535
536
537
538
# File 'lib/solargraph/language_server/host.rb', line 534

def document query
  result = []
  libraries.each { |lib| result.concat lib.document(query) }
  result
end

#document_symbols(uri) ⇒ Array<Solargraph::Pin::Base>


542
543
544
545
546
547
548
# File 'lib/solargraph/language_server/host.rb', line 542

def document_symbols uri
  library = library_for(uri)
  # At this level, document symbols should be unique; e.g., a
  # module_function method should return the location for Module.method
  # or Module#method, but not both.
  library.document_symbols(uri_to_file(uri)).uniq(&:location)
end

#flushString

Clear the message buffer and return the most recent data.


243
244
245
246
247
248
249
250
# File 'lib/solargraph/language_server/host.rb', line 243

def flush
  tmp = nil
  @buffer_semaphore.synchronize do
    tmp = @buffer.clone
    @buffer.clear
  end
  tmp
end

#foldersArray<String>


308
309
310
# File 'lib/solargraph/language_server/host.rb', line 308

def folders
  libraries.map { |lib| lib.workspace.directory }
end

#folding_ranges(uri) ⇒ Array<Range>


605
606
607
# File 'lib/solargraph/language_server/host.rb', line 605

def folding_ranges uri
  sources.find(uri).folding_ranges
end

#locate_pins(params) ⇒ Array<Pin::Base>

Locate multiple pins that match a completion item. The first match is based on the corresponding location in a library source if available. Subsequent matches are based on path.


449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
# File 'lib/solargraph/language_server/host.rb', line 449

def locate_pins params
  return [] unless params['data'] && params['data']['uri']
  library = library_for(params['data']['uri'])
  result = []
  if params['data']['location']
    location = Location.new(
      params['data']['location']['filename'],
      Range.from_to(
        params['data']['location']['range']['start']['line'],
        params['data']['location']['range']['start']['character'],
        params['data']['location']['range']['end']['line'],
        params['data']['location']['range']['end']['character']
      )
    )
    result.concat library.locate_pins(location).select{ |pin| pin.name == params['label'] }
  end
  if params['data']['path']
    result.concat library.path_pins(params['data']['path'])
  end
  result.uniq
end

#open(uri, text, version) ⇒ void

This method returns an undefined value.

Open the specified file in the library.


151
152
153
154
155
156
157
# File 'lib/solargraph/language_server/host.rb', line 151

def open uri, text, version
  src = sources.open(uri, text, version)
  libraries.each do |lib|
    lib.merge src
  end
  diagnoser.schedule uri
end

#open?(uri) ⇒ Boolean

True if the specified file is currently open in the library.


172
173
174
# File 'lib/solargraph/language_server/host.rb', line 172

def open? uri
  sources.include? uri
end

#open_from_disk(uri) ⇒ void


161
162
163
164
165
166
# File 'lib/solargraph/language_server/host.rb', line 161

def open_from_disk uri
  sources.open_from_disk(uri)
  library = library_for(uri)
  # library.open_from_disk uri_to_file(uri)
  diagnoser.schedule uri
end

#optionsHash


55
56
57
# File 'lib/solargraph/language_server/host.rb', line 55

def options
  @options ||= default_configuration
end

#pending_requestsArray<Integer>

Get a list of IDs for server requests that are waiting for responses from the client.


582
583
584
# File 'lib/solargraph/language_server/host.rb', line 582

def pending_requests
  requests.keys
end

#prepare(directory, name = nil) ⇒ void

This method returns an undefined value.

Prepare a library for the specified directory.


257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/solargraph/language_server/host.rb', line 257

def prepare directory, name = nil
  # No need to create a library without a directory. The generic library
  # will handle it.
  return if directory.nil?
  logger.info "Preparing library for #{directory}"
  path = ''
  path = normalize_separators(directory) unless directory.nil?
  begin
    lib = Solargraph::Library.load(path, name)
    libraries.push lib
  rescue WorkspaceTooLargeError => e
    send_notification 'window/showMessage', {
      'type' => Solargraph::LanguageServer::MessageTypes::WARNING,
      'message' => e.message
    }
  end
end

#prepare_folders(array) ⇒ void

This method returns an undefined value.

Prepare multiple folders.


279
280
281
282
283
284
# File 'lib/solargraph/language_server/host.rb', line 279

def prepare_folders array
  return if array.nil?
  array.each do |folder|
    prepare uri_to_file(folder['uri']), folder['name']
  end
end

#query_symbols(query) ⇒ Array<Solargraph::Pin::Base>


518
519
520
521
522
# File 'lib/solargraph/language_server/host.rb', line 518

def query_symbols query
  result = []
  (libraries + [generic_library]).each { |lib| result.concat lib.query_symbols(query) }
  result.uniq
end

#queue(message) ⇒ void

This method returns an undefined value.

Queue a message to be sent to the client.


234
235
236
237
238
# File 'lib/solargraph/language_server/host.rb', line 234

def queue message
  @buffer_semaphore.synchronize { @buffer += message }
  changed
  notify_observers
end

#read_text(uri) ⇒ String


473
474
475
476
477
# File 'lib/solargraph/language_server/host.rb', line 473

def read_text uri
  library = library_for(uri)
  filename = uri_to_file(uri)
  library.read_text(filename)
end

#receive(request) ⇒ Solargraph::LanguageServer::Message::Base

Start processing a request from the client. After the message is processed, the transport is responsible for sending the response.


91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/solargraph/language_server/host.rb', line 91

def receive request
  if request['method']
    logger.info "Server received #{request['method']}"
    logger.debug request
    message = Message.select(request['method']).new(self, request)
    begin
      message.process
    rescue Exception => e
      logger.warn "Error processing request: [#{e.class}] #{e.message}"
      logger.warn e.backtrace.join("\n")
      message.set_error Solargraph::LanguageServer::ErrorCodes::INTERNAL_ERROR, "[#{e.class}] #{e.message}"
    end
    message
  elsif request['id']
    # @todo What if the id is invalid?
    requests[request['id']].process(request['result'])
    requests.delete request['id']
  else
    logger.warn "Invalid message received."
    logger.debug request
  end
end

#references_from(uri, line, column, strip: true) ⇒ Array<Solargraph::Range>


511
512
513
514
# File 'lib/solargraph/language_server/host.rb', line 511

def references_from uri, line, column, strip: true
  library = library_for(uri)
  library.references_from(uri_to_file(uri), line, column, strip: strip)
end

#register_capabilities(methods) ⇒ void

This method returns an undefined value.

Register the methods as capabilities with the client. This method will avoid duplicating registrations and ignore methods that were not flagged for dynamic registration by the client.


361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/solargraph/language_server/host.rb', line 361

def register_capabilities methods
  logger.debug "Registering capabilities: #{methods}"
  @register_semaphore.synchronize do
    send_request 'client/registerCapability', {
      registrations: methods.select{|m| can_register?(m) and !registered?(m)}.map { |m|
        @registered_capabilities.add m
        {
          id: m,
          method: m,
          registerOptions: dynamic_capability_options[m]
        }
      }
    }
  end
end

#registered?(method) ⇒ Boolean

True if the specified method has been registered.


420
421
422
# File 'lib/solargraph/language_server/host.rb', line 420

def registered? method
  @registered_capabilities.include?(method)
end

#remove(directory) ⇒ void

This method returns an undefined value.

Remove a directory.


290
291
292
293
294
295
296
297
# File 'lib/solargraph/language_server/host.rb', line 290

def remove directory
  logger.info "Removing library for #{directory}"
  # @param lib [Library]
  libraries.delete_if do |lib|
    next false if lib.workspace.directory != directory
    true
  end
end

#remove_folders(array) ⇒ void


301
302
303
304
305
# File 'lib/solargraph/language_server/host.rb', line 301

def remove_folders array
  array.each do |folder|
    remove uri_to_file(folder['uri'])
  end
end

#search(query) ⇒ Array<String>


526
527
528
529
530
# File 'lib/solargraph/language_server/host.rb', line 526

def search query
  result = []
  libraries.each { |lib| result.concat lib.search(query) }
  result
end

#send_notification(method, params) ⇒ void

This method returns an undefined value.

Send a notification to the client.


317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/solargraph/language_server/host.rb', line 317

def send_notification method, params
  response = {
    jsonrpc: "2.0",
    method: method,
    params: params
  }
  json = response.to_json
  envelope = "Content-Length: #{json.bytesize}\r\n\r\n#{json}"
  queue envelope
  logger.info "Server sent #{method}"
  logger.debug params
end

#send_request(method, params, &block) {|The| ... } ⇒ void

This method returns an undefined value.

Send a request to the client and execute the provided block to process the response. If an ID is not provided, the host will use an auto- incrementing integer.

Yield Parameters:

  • The (Hash)

    result sent by the client


339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/solargraph/language_server/host.rb', line 339

def send_request method, params, &block
  message = {
    jsonrpc: "2.0",
    method: method,
    params: params,
    id: @next_request_id
  }
  json = message.to_json
  requests[@next_request_id] = Request.new(@next_request_id, &block)
  envelope = "Content-Length: #{json.bytesize}\r\n\r\n#{json}"
  queue envelope
  @next_request_id += 1
  logger.info "Server sent #{method}"
  logger.debug params
end

#show_message(text, type = LanguageServer::MessageTypes::INFO) ⇒ void

This method returns an undefined value.

Send a notification to the client.


555
556
557
558
559
560
# File 'lib/solargraph/language_server/host.rb', line 555

def show_message text, type = LanguageServer::MessageTypes::INFO
  send_notification 'window/showMessage', {
    type: type,
    message: text
  }
end

#show_message_request(text, type, actions, &block) {|The| ... } ⇒ void

This method returns an undefined value.

Send a notification with optional responses.

Yield Parameters:

  • The (String)

    action received from the client


570
571
572
573
574
575
576
# File 'lib/solargraph/language_server/host.rb', line 570

def show_message_request text, type, actions, &block
  send_request 'window/showMessageRequest', {
    type: type,
    message: text,
    actions: actions
  }, &block
end

#signatures_at(uri, line, column) ⇒ Array<Solargraph::Pin::Base>


501
502
503
504
# File 'lib/solargraph/language_server/host.rb', line 501

def signatures_at uri, line, column
  library = library_for(uri)
  library.signatures_at(uri_to_file(uri), line, column)
end

#startvoid

This method returns an undefined value.

Start asynchronous process handling.


36
37
38
39
40
41
42
# File 'lib/solargraph/language_server/host.rb', line 36

def start
  return unless stopped?
  @stopped = false
  diagnoser.start
  cataloger.start
  sources.start
end

#stopvoid


429
430
431
432
433
434
435
436
437
# File 'lib/solargraph/language_server/host.rb', line 429

def stop
  return if @stopped
  @stopped = true
  cataloger.stop
  diagnoser.stop
  sources.stop
  changed
  notify_observers
end

#stopped?Boolean


439
440
441
# File 'lib/solargraph/language_server/host.rb', line 439

def stopped?
  @stopped
end

#synchronizing?Boolean


424
425
426
# File 'lib/solargraph/language_server/host.rb', line 424

def synchronizing?
  !libraries.all?(&:synchronized?)
end

#unregister_capabilities(methods) ⇒ void

This method returns an undefined value.

Unregister the methods with the client. This method will avoid duplicating unregistrations and ignore methods that were not flagged for dynamic registration by the client.


383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/solargraph/language_server/host.rb', line 383

def unregister_capabilities methods
  logger.debug "Unregistering capabilities: #{methods}"
  @register_semaphore.synchronize do
    send_request 'client/unregisterCapability', {
      unregisterations: methods.select{|m| registered?(m)}.map{ |m|
        @registered_capabilities.delete m
        {
          id: m,
          method: m
        }
      }
    }
  end
end