Class: RubyIndexer::Index

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/ruby_indexer/lib/ruby_indexer/index.rb

Defined Under Namespace

Classes: UnresolvableAliasError

Constant Summary collapse

ENTRY_SIMILARITY_THRESHOLD =

The minimum Jaro-Winkler similarity score for an entry to be considered a match for a given fuzzy search query

0.7

Instance Method Summary collapse

Constructor Details

#initializeIndex

Returns a new instance of Index.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/ruby_indexer/lib/ruby_indexer/index.rb', line 14

def initialize
  # Holds all entries in the index using the following format:
  # {
  #  "Foo" => [#<Entry::Class>, #<Entry::Class>],
  #  "Foo::Bar" => [#<Entry::Class>],
  # }
  @entries = T.let({}, T::Hash[String, T::Array[Entry]])

  # Holds all entries in the index using a prefix tree for searching based on prefixes to provide autocompletion
  @entries_tree = T.let(PrefixTree[T::Array[Entry]].new, PrefixTree[T::Array[Entry]])

  # Holds references to where entries where discovered so that we can easily delete them
  # {
  #  "/my/project/foo.rb" => [#<Entry::Class>, #<Entry::Class>],
  #  "/my/project/bar.rb" => [#<Entry::Class>],
  # }
  @files_to_entries = T.let({}, T::Hash[String, T::Array[Entry]])

  # Holds all require paths for every indexed item so that we can provide autocomplete for requires
  @require_paths_tree = T.let(PrefixTree[IndexablePath].new, PrefixTree[IndexablePath])
end

Instance Method Details

#<<(entry) ⇒ Object



65
66
67
68
69
70
71
# File 'lib/ruby_indexer/lib/ruby_indexer/index.rb', line 65

def <<(entry)
  name = entry.name

  (@entries[name] ||= []) << entry
  (@files_to_entries[entry.file_path] ||= []) << entry
  @entries_tree.insert(name, T.must(@entries[name]))
end

#[](fully_qualified_name) ⇒ Object



74
75
76
# File 'lib/ruby_indexer/lib/ruby_indexer/index.rb', line 74

def [](fully_qualified_name)
  @entries[fully_qualified_name.delete_prefix("::")]
end

#delete(indexable) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/ruby_indexer/lib/ruby_indexer/index.rb', line 37

def delete(indexable)
  # For each constant discovered in `path`, delete the associated entry from the index. If there are no entries
  # left, delete the constant from the index.
  @files_to_entries[indexable.full_path]&.each do |entry|
    name = entry.name
    entries = @entries[name]
    next unless entries

    # Delete the specific entry from the list for this name
    entries.delete(entry)

    # If all entries were deleted, then remove the name from the hash and from the prefix tree. Otherwise, update
    # the prefix tree with the current entries
    if entries.empty?
      @entries.delete(name)
      @entries_tree.delete(name)
    else
      @entries_tree.insert(name, entries)
    end
  end

  @files_to_entries.delete(indexable.full_path)

  require_path = indexable.require_path
  @require_paths_tree.delete(require_path) if require_path
end

#follow_aliased_namespace(name) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/ruby_indexer/lib/ruby_indexer/index.rb', line 203

def follow_aliased_namespace(name)
  return name if @entries[name]

  parts = name.split("::")
  real_parts = []

  (parts.length - 1).downto(0).each do |i|
    current_name = T.must(parts[0..i]).join("::")
    entry = @entries[current_name]&.first

    case entry
    when Entry::Alias
      target = entry.target
      return follow_aliased_namespace("#{target}::#{real_parts.join("::")}")
    when Entry::UnresolvedAlias
      resolved = resolve_alias(entry)

      if resolved.is_a?(Entry::UnresolvedAlias)
        raise UnresolvableAliasError, "The constant #{resolved.name} is an alias to a non existing constant"
      end

      target = resolved.target
      return follow_aliased_namespace("#{target}::#{real_parts.join("::")}")
    else
      real_parts.unshift(T.must(parts[i]))
    end
  end

  real_parts.join("::")
end

#fuzzy_search(query) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/ruby_indexer/lib/ruby_indexer/index.rb', line 110

def fuzzy_search(query)
  return @entries.flat_map { |_name, entries| entries } unless query

  normalized_query = query.gsub("::", "").downcase

  results = @entries.filter_map do |name, entries|
    similarity = DidYouMean::JaroWinkler.distance(name.gsub("::", "").downcase, normalized_query)
    [entries, -similarity] if similarity > ENTRY_SIMILARITY_THRESHOLD
  end
  results.sort_by!(&:last)
  results.flat_map(&:first)
end

#index_all(indexable_paths: RubyIndexer.configuration.indexables, &block) ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/ruby_indexer/lib/ruby_indexer/index.rb', line 165

def index_all(indexable_paths: RubyIndexer.configuration.indexables, &block)
  # Calculate how many paths are worth 1% of progress
  progress_step = (indexable_paths.length / 100.0).ceil

  indexable_paths.each_with_index do |path, index|
    if block && index % progress_step == 0
      progress = (index / progress_step) + 1
      break unless block.call(progress)
    end

    index_single(path)
  end
end

#index_single(indexable_path, source = nil) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
# File 'lib/ruby_indexer/lib/ruby_indexer/index.rb', line 180

def index_single(indexable_path, source = nil)
  content = source || File.read(indexable_path.full_path)
  result = Prism.parse(content)
  visitor = IndexVisitor.new(self, result, indexable_path.full_path)
  result.value.accept(visitor)

  require_path = indexable_path.require_path
  @require_paths_tree.insert(require_path, indexable_path) if require_path
rescue Errno::EISDIR
  # If `path` is a directory, just ignore it and continue indexing
end

#prefix_search(query, nesting) ⇒ Object



97
98
99
100
101
102
103
104
105
106
# File 'lib/ruby_indexer/lib/ruby_indexer/index.rb', line 97

def prefix_search(query, nesting)
  results = nesting.length.downto(0).flat_map do |i|
    prefix = T.must(nesting[0...i]).join("::")
    namespaced_query = prefix.empty? ? query : "#{prefix}::#{query}"
    @entries_tree.search(namespaced_query)
  end

  results.uniq!
  results
end

#resolve(name, nesting) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/ruby_indexer/lib/ruby_indexer/index.rb', line 129

def resolve(name, nesting)
  if name.start_with?("::")
    name = name.delete_prefix("::")
    results = @entries[name] || @entries[follow_aliased_namespace(name)]
    return results&.map { |e| e.is_a?(Entry::UnresolvedAlias) ? resolve_alias(e) : e }
  end

  nesting.length.downto(0).each do |i|
    namespace = T.must(nesting[0...i]).join("::")
    full_name = namespace.empty? ? name : "#{namespace}::#{name}"

    # If we find an entry with `full_name` directly, then we can already return it, even if it contains aliases -
    # because the user might be trying to jump to the alias definition.
    #
    # However, if we don't find it, then we need to search for possible aliases in the namespace. For example, in
    # the LSP itself we alias `RubyLsp::Interface` to `LanguageServer::Protocol::Interface`, which means doing
    # `RubyLsp::Interface::Location` is allowed. For these cases, we need some way to realize that the
    # `RubyLsp::Interface` part is an alias, that has to be resolved
    entries = @entries[full_name] || @entries[follow_aliased_namespace(full_name)]
    return entries.map { |e| e.is_a?(Entry::UnresolvedAlias) ? resolve_alias(e) : e } if entries
  end

  nil
rescue UnresolvableAliasError
  nil
end

#search_require_paths(query) ⇒ Object



79
80
81
# File 'lib/ruby_indexer/lib/ruby_indexer/index.rb', line 79

def search_require_paths(query)
  @require_paths_tree.search(query)
end