Class: Solargraph::Library

Inherits:
Object
  • Object
show all
Includes:
Observable, Logging
Defined in:
lib/solargraph/library.rb

Overview

A Library handles coordination between a Workspace and an ApiMap.

Constant Summary

Constants included from Logging

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Logging

logger

Constructor Details

#initialize(workspace = Solargraph::Workspace.new, name = nil) ⇒ Library

Returns a new instance of Library.

Parameters:

  • workspace (Solargraph::Workspace) (defaults to: Solargraph::Workspace.new)
  • name (String, nil) (defaults to: nil)


27
28
29
30
31
32
33
34
35
# File 'lib/solargraph/library.rb', line 27

def initialize workspace = Solargraph::Workspace.new, name = nil
  @workspace = workspace
  @name = name
  # @type [Integer, nil]
  @total = nil
  # @type [Source, nil]
  @current = nil
  @sync_count = 0
end

Instance Attribute Details

#cache_progressLanguageServer::Progress? (readonly)

Returns:



23
24
25
# File 'lib/solargraph/library.rb', line 23

def cache_progress
  @cache_progress
end

#currentSource? (readonly)

Returns:



20
21
22
# File 'lib/solargraph/library.rb', line 20

def current
  @current
end

#nameString? (readonly)

Returns:

  • (String, nil)


17
18
19
# File 'lib/solargraph/library.rb', line 17

def name
  @name
end

#workspaceSolargraph::Workspace (readonly)



14
15
16
# File 'lib/solargraph/library.rb', line 14

def workspace
  @workspace
end

Class Method Details

.load(directory = '', name = nil) ⇒ Solargraph::Library

Create a library from a directory.

Parameters:

  • directory (String) (defaults to: '')

    The path to be used for the workspace

  • name (String, nil) (defaults to: nil)

Returns:



455
456
457
# File 'lib/solargraph/library.rb', line 455

def self.load directory = '', name = nil
  Solargraph::Library.new(Solargraph::Workspace.new(directory), name)
end

Instance Method Details

#attach(source) ⇒ void

This method returns an undefined value.

Attach a source to the library.

The attached source does not need to be a part of the workspace. The library will include it in the ApiMap while it’s attached. Only one source can be attached to the library at a time.

Parameters:



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/solargraph/library.rb', line 58

def attach source
  if @current && (!source || @current.filename != source.filename) && source_map_hash.key?(@current.filename) && !workspace.has_file?(@current.filename)
    source_map_hash.delete @current.filename
    source_map_external_require_hash.delete @current.filename
    @external_requires = nil
  end
  changed = source && @current != source
  @current = source
  maybe_map @current
  catalog if changed
end

#attached?(filename) ⇒ Boolean Also known as: open?

True if the specified file is currently attached.

Parameters:

  • filename (String)

Returns:

  • (Boolean)


74
75
76
# File 'lib/solargraph/library.rb', line 74

def attached? filename
  !@current.nil? && @current.filename == filename
end

#benchBench

Returns:



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

def bench
  Bench.new(
    source_maps: source_map_hash.values,
    workspace: workspace,
    external_requires: external_requires,
    live_map: @current ? source_map_hash[@current.filename] : nil
  )
end

#catalogvoid

This method returns an undefined value.

Update the ApiMap from the library’s workspace and open files.



425
426
427
# File 'lib/solargraph/library.rb', line 425

def catalog
  @sync_count += 1
end

#close(filename) ⇒ void

This method returns an undefined value.

Close a file in the library. Closing a file will make it unavailable for checkout although it may still exist in the workspace.

Parameters:

  • filename (String)


146
147
148
149
150
151
# File 'lib/solargraph/library.rb', line 146

def close filename
  return unless @current&.filename == filename

  @current = nil
  catalog unless workspace.has_file?(filename)
end

#completions_at(filename, line, column) ⇒ SourceMap::Completion?

TODO:

Take a Location instead of filename/line/column

Get completion suggestions at the specified file and location.

Parameters:

  • filename (String)

    The file to analyze

  • line (Integer)

    The zero-based line number

  • column (Integer)

    The zero-based column number

Returns:



160
161
162
163
164
165
166
167
# File 'lib/solargraph/library.rb', line 160

def completions_at filename, line, column
  sync_catalog
  position = Position.new(line, column)
  cursor = Source::Cursor.new(read(filename), position)
  mutex.synchronize { api_map.clip(cursor).complete }
rescue FileNotFoundError => e
  handle_file_not_found filename, e
end

#contain?(filename) ⇒ Boolean

True if the specified file is included in the workspace (but not necessarily open).

Parameters:

  • filename (String)

Returns:

  • (Boolean)


94
95
96
# File 'lib/solargraph/library.rb', line 94

def contain? filename
  workspace.has_file?(filename)
end

#create(filename, text) ⇒ Boolean

Create a source to be added to the workspace. The file is ignored if it is neither open in the library nor included in the workspace.

Parameters:

  • filename (String)
  • text (String)

    The contents of the file

Returns:

  • (Boolean)

    True if the file was added to the workspace.



104
105
106
107
108
109
# File 'lib/solargraph/library.rb', line 104

def create filename, text
  return false unless contain?(filename) || open?(filename)
  source = Solargraph::Source.load_string(text, filename)
  workspace.merge(source)
  true
end

#create_from_disk(*filenames) ⇒ Boolean

Create file sources from files on disk. A file is ignored if it is neither open in the library nor included in the workspace.

Parameters:

  • filenames (Array<String>)

Returns:

  • (Boolean)

    True if at least one file was added to the workspace.



116
117
118
119
120
121
122
123
# File 'lib/solargraph/library.rb', line 116

def create_from_disk *filenames
  sources = filenames
    .reject { |filename| File.directory?(filename) || !File.exist?(filename) }
    .map { |filename| Solargraph::Source.load_string(File.read(filename), filename) }
  result = workspace.merge(*sources)
  sources.each { |source| maybe_map source }
  result
end

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

TODO:

Take filename/position instead of filename/line/column

Get definition suggestions for the expression at the specified file and location.

Parameters:

  • filename (String)

    The file to analyze

  • line (Integer)

    The zero-based line number

  • column (Integer)

    The zero-based column number

Returns:



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/solargraph/library.rb', line 177

def definitions_at filename, line, column
  sync_catalog
  position = Position.new(line, column)
  cursor = Source::Cursor.new(read(filename), position)
  if cursor.comment?
    source = read(filename)
    offset = Solargraph::Position.to_offset(source.code, Solargraph::Position.new(line, column))
    lft = source.code[0..offset-1].match(/\[[a-z0-9_:<, ]*?([a-z0-9_:]*)\z/i)
    rgt = source.code[offset..-1].match(/^([a-z0-9_]*)(:[a-z0-9_:]*)?[\]>, ]/i)
    if lft && rgt
      tag = (lft[1] + rgt[1]).sub(/:+$/, '')
      clip = mutex.synchronize { api_map.clip(cursor) }
      clip.translate tag
    else
      []
    end
  else
    mutex.synchronize do
      clip = api_map.clip(cursor)
      clip.define.map { |pin| pin.realize(api_map) }
    end
  end
rescue FileNotFoundError => e
  handle_file_not_found(filename, e)
end

#delete(*filenames) ⇒ Boolean

Delete files from the library. Deleting a file will make it unavailable for checkout and optionally remove it from the workspace unless the workspace configuration determines that it should still exist.

Parameters:

  • filenames (Array<String>)

Returns:

  • (Boolean)

    True if any file was deleted



131
132
133
134
135
136
137
138
139
# File 'lib/solargraph/library.rb', line 131

def delete *filenames
  result = false
  filenames.each do |filename|
    detach filename
    source_map_hash.delete(filename)
    result ||= workspace.remove(filename)
  end
  result
end

#detach(filename) ⇒ Boolean

Detach the specified file if it is currently attached to the library.

Parameters:

  • filename (String)

Returns:

  • (Boolean)

    True if the specified file was detached



83
84
85
86
87
# File 'lib/solargraph/library.rb', line 83

def detach filename
  return false if @current.nil? || @current.filename != filename
  attach nil
  true
end

#diagnose(filename) ⇒ Array<Hash>

Get diagnostics about a file.

Parameters:

  • filename (String)

Returns:

  • (Array<Hash>)


390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/solargraph/library.rb', line 390

def diagnose filename
  # @todo Only open files get diagnosed. Determine whether anything or
  #   everything in the workspace should get diagnosed, or if there should
  #   be an option to do so.
  #
  sync_catalog
  return [] unless open?(filename)
  result = []
  source = read(filename)

  # @type [Hash{Class<Solargraph::Diagnostics::Base> => Array<String>}]
  repargs = {}
  workspace.config.reporters.each do |line|
    if line == 'all!'
      Diagnostics.reporters.each do |reporter|
        repargs[reporter] ||= []
      end
    else
      args = line.split(':').map(&:strip)
      name = args.shift
      reporter = Diagnostics.reporter(name)
      raise DiagnosticsError, "Diagnostics reporter #{name} does not exist" if reporter.nil?
      repargs[reporter] ||= []
      repargs[reporter].concat args
    end
  end
  repargs.each_pair do |reporter, args|
    result.concat reporter.new(*args.uniq).diagnose(source, api_map)
  end
  result
end

#document(query) ⇒ Enumerable<YARD::CodeObjects::Base>, Array(ApiMap, Enumerable<Pin::Base>)

Parameters:

  • query (String)

Returns:

  • (Enumerable<YARD::CodeObjects::Base>)
  • (Array(ApiMap, Enumerable<Pin::Base>))


331
332
333
334
# File 'lib/solargraph/library.rb', line 331

def document query
  sync_catalog
  mutex.synchronize { [api_map, api_map.get_path_pins(query)] }
end

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

Get an array of document symbols.

Document symbols are composed of namespace, method, and constant pins. The results of this query are appropriate for building the response to a textDocument/documentSymbol message in the language server protocol.

Parameters:

  • filename (String)

Returns:



360
361
362
363
# File 'lib/solargraph/library.rb', line 360

def document_symbols filename
  sync_catalog
  mutex.synchronize { api_map.document_symbols(filename) }
end

#external_requiresSet<String>

Returns:

  • (Set<String>)


507
508
509
# File 'lib/solargraph/library.rb', line 507

def external_requires
  @external_requires ||= source_map_external_require_hash.values.flatten.to_set
end

#folding_ranges(filename) ⇒ Array<Range>

Deprecated.

The library should not need to handle folding ranges. The source itself has all the information it needs.

Get an array of foldable ranges for the specified file.

Parameters:

  • filename (String)

Returns:



446
447
448
# File 'lib/solargraph/library.rb', line 446

def folding_ranges filename
  read(filename).folding_ranges
end

#get_path_pins(path) ⇒ Enumerable<Solargraph::Pin::Base>

Get an array of pins that match a path.

Parameters:

  • path (String)

Returns:



323
324
325
326
# File 'lib/solargraph/library.rb', line 323

def get_path_pins path
  sync_catalog
  mutex.synchronize { api_map.get_path_suggestions(path) }
end

#inspectObject



37
38
39
40
# File 'lib/solargraph/library.rb', line 37

def inspect
  # Let's not deal with insane data dumps in spec failures
  to_s
end

#locate_pins(location) ⇒ Array<Solargraph::Pin::Base>

Get the pins at the specified location or nil if the pin does not exist.

Parameters:

Returns:



289
290
291
292
# File 'lib/solargraph/library.rb', line 289

def locate_pins location
  sync_catalog
  mutex.synchronize { api_map.locate_pins(location).map { |pin| pin.realize(api_map) } }
end

#locate_ref(location) ⇒ Location?

Match a require reference to a file.

Parameters:

Returns:



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/solargraph/library.rb', line 298

def locate_ref location
  map = source_map_hash[location.filename]
  return if map.nil?
  pin = map.requires.select { |p| p.location.range.contain?(location.range.start) }.first
  return nil if pin.nil?
  # @param full [String]
  return_if_match = proc do |full|
    if source_map_hash.key?(full)
      return Location.new(full, Solargraph::Range.from_to(0, 0, 0, 0))
    end
  end
  workspace.require_paths.each do |path|
    full = File.join path, pin.name
    return_if_match.(full)
    return_if_match.(full << ".rb")
  end
  nil
rescue FileNotFoundError
  nil
end

#map!self

Returns:

  • (self)


493
494
495
496
497
498
499
# File 'lib/solargraph/library.rb', line 493

def map!
  workspace.sources.each do |src|
    source_map_hash[src.filename] = Solargraph::SourceMap.map(src)
    find_external_requires source_map_hash[src.filename]
  end
  self
end

#mapped?Boolean

Returns:

  • (Boolean)


475
476
477
# File 'lib/solargraph/library.rb', line 475

def mapped?
  (workspace.filenames - source_map_hash.keys).empty?
end

#merge(source) ⇒ Boolean

Try to merge a source into the library’s workspace. If the workspace is not configured to include the source, it gets ignored.

Parameters:

Returns:

  • (Boolean)

    True if the source was merged into the workspace.



464
465
466
467
468
# File 'lib/solargraph/library.rb', line 464

def merge source
  result = workspace.merge(source)
  maybe_map source
  result
end

#next_mapSourceMap, Boolean

Returns:



480
481
482
483
484
485
486
487
488
489
490
# File 'lib/solargraph/library.rb', line 480

def next_map
  return false if mapped?
  src = workspace.sources.find { |s| !source_map_hash.key?(s.filename) }
  if src
    Logging.logger.debug "Mapping #{src.filename}"
    source_map_hash[src.filename] = Solargraph::SourceMap.map(src)
    source_map_hash[src.filename]
  else
    false
  end
end

#path_pins(path) ⇒ Enumerable<Solargraph::Pin::Base>

Parameters:

  • path (String)

Returns:



367
368
369
370
# File 'lib/solargraph/library.rb', line 367

def path_pins path
  sync_catalog
  mutex.synchronize { api_map.get_path_suggestions(path) }
end

#pinsArray<Solargraph::Pin::Base>

Returns:



502
503
504
# File 'lib/solargraph/library.rb', line 502

def pins
  @pins ||= []
end

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

Get an array of all symbols in the workspace that match the query.

Parameters:

  • query (String)

Returns:



347
348
349
350
# File 'lib/solargraph/library.rb', line 347

def query_symbols query
  sync_catalog
  mutex.synchronize { api_map.query_symbols query }
end

#read_text(filename) ⇒ String

Get the current text of a file in the library.

Parameters:

  • filename (String)

Returns:

  • (String)


381
382
383
384
# File 'lib/solargraph/library.rb', line 381

def read_text filename
  source = read(filename)
  source.code
end

#references_from(filename, line, column, strip: false, only: false) ⇒ Array<Solargraph::Location>

TODO:

Take a Location instead of filename/line/column

Parameters:

  • filename (String)
  • line (Integer)
  • column (Integer)
  • strip (Boolean) (defaults to: false)

    Strip special characters from variable names

  • only (Boolean) (defaults to: false)

    Search for references in the current file only

Returns:



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/solargraph/library.rb', line 242

def references_from filename, line, column, strip: false, only: false
  sync_catalog
  cursor = Source::Cursor.new(read(filename), [line, column])
  clip = mutex.synchronize { api_map.clip(cursor) }
  pin = clip.define.first
  return [] unless pin
  result = []
  files = if only
    [api_map.source_map(filename)]
  else
    (workspace.sources + (@current ? [@current] : []))
  end
  files.uniq(&:filename).each do |source|
    found = source.references(pin.name)
    found.select! do |loc|
      referenced = definitions_at(loc.filename, loc.range.ending.line, loc.range.ending.character).first
      referenced&.path == pin.path
    end
    if pin.path == 'Class#new'
      caller = cursor.chain.base.infer(api_map, clip.send(:block), clip.locals).first
      if caller.defined?
        found.select! do |loc|
          clip = api_map.clip_at(loc.filename, loc.range.start)
          other = clip.send(:cursor).chain.base.infer(api_map, clip.send(:block), clip.locals).first
          caller == other
        end
      else
        found.clear
      end
    end
    # HACK: for language clients that exclude special characters from the start of variable names
    if strip && match = cursor.word.match(/^[^a-z0-9_]+/i)
      found.map! do |loc|
        Solargraph::Location.new(loc.filename, Solargraph::Range.from_to(loc.range.start.line, loc.range.start.column + match[0].length, loc.range.ending.line, loc.range.ending.column))
      end
    end
    result.concat(found.sort do |a, b|
      a.range.start.line <=> b.range.start.line
    end)
  end
  result.uniq
end

#search(query) ⇒ Array<String>

Parameters:

  • query (String)

Returns:

  • (Array<String>)


338
339
340
341
# File 'lib/solargraph/library.rb', line 338

def search query
  sync_catalog
  mutex.synchronize { api_map.search query }
end

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

TODO:

Take filename/position instead of filename/line/column

Get signature suggestions for the method at the specified file and location.

Parameters:

  • filename (String)

    The file to analyze

  • line (Integer)

    The zero-based line number

  • column (Integer)

    The zero-based column number

Returns:



228
229
230
231
232
233
# File 'lib/solargraph/library.rb', line 228

def signatures_at filename, line, column
  sync_catalog
  position = Position.new(line, column)
  cursor = Source::Cursor.new(read(filename), position)
  mutex.synchronize { api_map.clip(cursor).signify }
end

#source_map_hashHash{String => SourceMap}

Returns:



471
472
473
# File 'lib/solargraph/library.rb', line 471

def source_map_hash
  @source_map_hash ||= {}
end

#source_mapsArray<SourceMap>

Returns:



373
374
375
# File 'lib/solargraph/library.rb', line 373

def source_maps
  source_map_hash.values
end

#synchronized?Boolean

True if the ApiMap is up to date with the library’s workspace and open files.

Returns:

  • (Boolean)


46
47
48
# File 'lib/solargraph/library.rb', line 46

def synchronized?
  @sync_count < 2
end

#type_definitions_at(filename, line, column) ⇒ Array<Solargraph::Pin::Base>?

TODO:

Take filename/position instead of filename/line/column

Get type definition suggestions for the expression at the specified file and location.

Parameters:

  • filename (String)

    The file to analyze

  • line (Integer)

    The zero-based line number

  • column (Integer)

    The zero-based column number

Returns:



211
212
213
214
215
216
217
218
# File 'lib/solargraph/library.rb', line 211

def type_definitions_at filename, line, column
  sync_catalog
  position = Position.new(line, column)
  cursor = Source::Cursor.new(read(filename), position)
  mutex.synchronize { api_map.clip(cursor).types }
rescue FileNotFoundError => e
  handle_file_not_found filename, e
end