ruby_language_server 0.4.2 → 0.9.9

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.
@@ -1,13 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'uri'
3
4
  require 'fuzzy_match'
4
5
  require 'amatch' # NOTE: that you have to require this... fuzzy_match won't require it for you
5
6
  FuzzyMatch.engine = :amatch # This should be in a config somewhere
6
7
 
7
8
  module RubyLanguageServer
8
9
  class ProjectManager
9
- attr_reader :uri_code_file_hash
10
-
11
10
  # GoodCop wants to know where to find its config. So here we are.
12
11
  ROOT_PATH_MUTEX = Mutex.new
13
12
  @_root_path = nil
@@ -40,6 +39,17 @@ module RubyLanguageServer
40
39
  def root_uri
41
40
  @_root_uri || "file://#{root_path}"
42
41
  end
42
+
43
+ # Let's not preload spec/test files or vendor - yet.
44
+ # Matches foo_spec.rb, foo_test.rb, spec.rb and test.rb, and anything in a vendor
45
+ # directory, but not files that merely contain those words, like latest.rb.
46
+ SKIP_SCAN_PATTERN = %r{(?:\A|/|_)(?:spec|test)\.rb\z|(?:\A|/)vendor/}
47
+
48
+ # relative_path is relative to the project root, so a root inside a directory named
49
+ # vendor doesn't skip everything.
50
+ def skip_scan?(relative_path)
51
+ relative_path.match?(SKIP_SCAN_PATTERN)
52
+ end
43
53
  end
44
54
 
45
55
  def initialize(path, uri = nil)
@@ -47,7 +57,8 @@ module RubyLanguageServer
47
57
  self.class.root_path = path if self.class.root_path.nil?
48
58
  self.class.root_uri = uri if uri
49
59
 
50
- @root_uri = "file://#{path}"
60
+ # The URI the editor uses for the project root. The scan maps container paths onto it.
61
+ @root_uri = uri || "file://#{path}"
51
62
  # This is {uri: code_file} where content stuff is like
52
63
  # @additional_gems_installed = false
53
64
  # @additional_gem_mutex = Mutex.new
@@ -57,6 +68,12 @@ module RubyLanguageServer
57
68
  # @additional_gem_mutex.synchronize { @additional_gems_installed }
58
69
  # end
59
70
 
71
+ # The prefix the background scan puts in front of each file's path relative to the
72
+ # project root: the client's rootUri, or file:// + rootPath, with a trailing slash.
73
+ def scan_root_uri
74
+ @root_uri.end_with?('/') ? @root_uri : "#{@root_uri}/"
75
+ end
76
+
60
77
  def text_for_uri(uri)
61
78
  code_file = code_file_for_uri(uri)
62
79
  code_file&.text || ''
@@ -64,138 +81,79 @@ module RubyLanguageServer
64
81
 
65
82
  def tags_for_uri(uri)
66
83
  code_file = code_file_for_uri(uri)
67
- return {} if code_file.nil?
84
+ return [] if code_file.nil?
68
85
 
69
86
  code_file.tags
70
87
  end
71
88
 
72
89
  def root_scope_for(uri)
73
- code_file = code_file_for_uri(uri)
74
- RubyLanguageServer.logger.error('code_file.nil?!!!!!!!!!!!!!!') if code_file.nil?
75
- code_file&.root_scope
76
- end
77
-
78
- def all_scopes
79
- RubyLanguageServer::ScopeData::Scope.all
90
+ code_file_for_uri(uri).scopes.root_scope
80
91
  end
81
92
 
82
93
  # Return the list of scopes [deepest, parent, ..., Object]
83
94
  def scopes_at(uri, position)
84
95
  code_file = code_file_for_uri(uri)
85
96
  code_file.refresh_scopes_if_needed
86
- code_file.scopes.for_line(position.line).where.not(path: nil).by_path_length
97
+ code_file.scopes.for_line(position.line + 1).where.not(path: nil).by_path_length
87
98
  end
88
99
 
89
100
  def completion_at(uri, position)
90
101
  context = context_at_location(uri, position)
91
- return {} if context.blank?
102
+ return nil if context.blank? # null: no completions
92
103
 
93
- RubyLanguageServer.logger.debug("scopes_at(uri, position) #{scopes_at(uri, position).map(&:name)}")
94
- position_scopes = scopes_at(uri, position) || RubyLanguageServer::ScopeData::Scope.where(id: root_scope_for(uri).id)
104
+ position_scopes = scopes_at(uri, position)
105
+ RubyLanguageServer.logger.debug("scopes_at(uri, position) #{position_scopes.map(&:name)}")
106
+ # Outside every class, module, method and block, complete from the file's top level.
107
+ position_scopes = RubyLanguageServer::ScopeData::Scope.where(id: root_scope_for(uri)&.id) if position_scopes.empty?
95
108
  context_scope = position_scopes.first
96
109
  RubyLanguageServer::Completion.completion(context, context_scope, position_scopes)
97
110
  end
98
111
 
99
- # interface CompletionItem {
100
- # /**
101
- # * The label of this completion item. By default
102
- # * also the text that is inserted when selecting
103
- # * this completion.
104
- # */
105
- # label: string;
106
- # /**
107
- # * The kind of this completion item. Based of the kind
108
- # * an icon is chosen by the editor.
109
- # */
110
- # kind?: number;
111
- # /**
112
- # * A human-readable string with additional information
113
- # * about this item, like type or symbol information.
114
- # */
115
- # detail?: string;
116
- # /**
117
- # * A human-readable string that represents a doc-comment.
118
- # */
119
- # documentation?: string;
120
- # /**
121
- # * A string that shoud be used when comparing this item
122
- # * with other items. When `falsy` the label is used.
123
- # */
124
- # sortText?: string;
125
- # /**
126
- # * A string that should be used when filtering a set of
127
- # * completion items. When `falsy` the label is used.
128
- # */
129
- # filterText?: string;
130
- # /**
131
- # * A string that should be inserted a document when selecting
132
- # * this completion. When `falsy` the label is used.
133
- # */
134
- # insertText?: string;
135
- # /**
136
- # * The format of the insert text. The format applies to both the `insertText` property
137
- # * and the `newText` property of a provided `textEdit`.
138
- # */
139
- # insertTextFormat?: InsertTextFormat;
140
- # /**
141
- # * An edit which is applied to a document when selecting this completion. When an edit is provided the value of
142
- # * `insertText` is ignored.
143
- # *
144
- # * *Note:* The range of the edit must be a single line range and it must contain the position at which completion
145
- # * has been requested.
146
- # */
147
- # textEdit?: TextEdit;
148
- # /**
149
- # * An optional array of additional text edits that are applied when
150
- # * selecting this completion. Edits must not overlap with the main edit
151
- # * nor with themselves.
152
- # */
153
- # additionalTextEdits?: TextEdit[];
154
- # /**
155
- # * An optional set of characters that when pressed while this completion is active will accept it first and
156
- # * then type that character. *Note* that all commit characters should have `length=1` and that superfluous
157
- # * characters will be ignored.
158
- # */
159
- # commitCharacters?: string[];
160
- # /**
161
- # * An optional command that is executed *after* inserting this completion. *Note* that
162
- # * additional modifications to the current document should be described with the
163
- # * additionalTextEdits-property.
164
- # */
165
- # command?: Command;
166
- # /**
167
- # * An data entry field that is preserved on a completion item between
168
- # * a completion and a completion resolve request.
169
- # */
170
- # data?: any
171
- # }
112
+ # How many times the background scan retries a file when the database is locked.
113
+ SCAN_BUSY_RETRIES = 3
114
+ SCAN_BUSY_RETRY_DELAY = 1 # seconds
115
+
116
+ # Stores and parses one file for the background scan. Only a locked database is
117
+ # retried, briefly; any other error is raised for the caller to log.
118
+ def index_file(uri, text)
119
+ attempts = 0
120
+ begin
121
+ ActiveRecord::Base.connection_pool.with_connection do
122
+ update_document_content(uri, text)
123
+ code_file_for_uri(uri).refresh_scopes_if_needed
124
+ end
125
+ rescue ActiveRecord::StatementTimeout => e
126
+ attempts += 1
127
+ raise if attempts > SCAN_BUSY_RETRIES
128
+
129
+ RubyLanguageServer.logger.warn("Database busy indexing #{uri}, retrying: #{e.message}")
130
+ sleep scan_busy_retry_delay
131
+ retry
132
+ end
133
+ end
134
+
135
+ def scan_busy_retry_delay
136
+ SCAN_BUSY_RETRY_DELAY
137
+ end
172
138
 
173
139
  def scan_all_project_files
174
140
  project_ruby_files = Dir.glob("#{self.class.root_path}**/*.rb")
175
141
  RubyLanguageServer.logger.debug('Threading up!')
176
- root_uri = @root_uri
177
- root_uri += '/' unless root_uri.end_with? '/'
142
+ root_uri = scan_root_uri
178
143
  # Using fork because this is run in a docker container that has fork.
179
144
  # If you want to run this on some platform without fork, fork the code and PR it :-)
180
145
  fork_id = fork do
181
146
  project_ruby_files.each do |container_path|
182
- # Let's not preload spec/test files or vendor - yet..
183
- next if container_path.match?(/(spec\.rb|test\.rb|vendor)/)
147
+ relative_path = container_path.delete_prefix(self.class.root_path)
148
+ next if self.class.skip_scan?(relative_path)
184
149
 
185
150
  text = File.read(container_path)
186
- relative_path = container_path.delete_prefix(self.class.root_path)
187
151
  host_uri = root_uri + relative_path
188
152
  RubyLanguageServer.logger.debug("Threading #{host_uri}")
189
- begin
190
- ActiveRecord::Base.connection_pool.with_connection do |_connection|
191
- update_document_content(host_uri, text)
192
- code_file_for_uri(host_uri).refresh_scopes_if_needed(shallow: true)
193
- end
194
- rescue StandardError => e
195
- RubyLanguageServer.logger.warn("Error updating: #{e}\n#{e.backtrace * "\n"}")
196
- sleep 5
197
- retry
198
- end
153
+ index_file(host_uri, text)
154
+ rescue StandardError => e
155
+ # One bad file mustn't stall the scan: log it and go on to the next.
156
+ RubyLanguageServer.logger.error("Skipping #{container_path}: #{e.class}: #{e}\n#{e.backtrace * "\n"}")
199
157
  end
200
158
  end
201
159
  RubyLanguageServer.logger.debug("Forked process id to look at other files: #{fork_id}")
@@ -213,68 +171,309 @@ module RubyLanguageServer
213
171
  # diagnostics_ready? ? updated_diagnostics_for_codefile(code_file) : []
214
172
  end
215
173
 
216
- # def updated_diagnostics_for_codefile(code_file)
217
- # # Maybe we should be sharing this GoodCop across instances
218
- # RubyLanguageServer.logger.debug("updated_diagnostics_for_codefile: #{code_file.uri}")
219
- # project_relative_filename = filename_relative_to_project(code_file.uri)
220
- # # code_file.diagnostics = GoodCop.instance&.diagnostics(code_file.text, project_relative_filename)
221
- # RubyLanguageServer.logger.debug("code_file.diagnostics: #{code_file.diagnostics}")
222
- # code_file.diagnostics
223
- # end
224
-
225
174
  # Returns the context of what is being typed in the given line
226
175
  def context_at_location(uri, position)
227
176
  code_file = code_file_for_uri(uri)
228
177
  code_file&.context_at_location(position)
229
178
  end
230
179
 
180
+ # FileChangeType values in workspace/didChangeWatchedFiles.
181
+ FILE_CREATED = 1
182
+ FILE_CHANGED = 2
183
+ FILE_DELETED = 3
184
+
185
+ # Keeps the index in step with files created, changed or deleted outside the editor.
186
+ def watched_files_changed(changes)
187
+ changes.each do |change|
188
+ uri = change['uri']
189
+ case change['type']
190
+ when FILE_DELETED then forget_uri(uri)
191
+ when FILE_CREATED, FILE_CHANGED then reload_from_disk(uri)
192
+ end
193
+ rescue StandardError => e
194
+ RubyLanguageServer.logger.error("Error handling watched file change #{change}: #{e.class}: #{e}")
195
+ end
196
+ end
197
+
198
+ # Drops a file from the index. If uri is a directory, drops everything under it.
199
+ def forget_uri(uri)
200
+ under_directory = "#{ActiveRecord::Base.sanitize_sql_like(uri.delete_suffix('/'))}/%"
201
+ CodeFile.where(uri:).or(CodeFile.where('uri LIKE ?', under_directory)).destroy_all
202
+ end
203
+
204
+ def reload_from_disk(uri)
205
+ path = container_path_for(uri)
206
+ return if path.nil? || !path.end_with?('.rb') || !File.file?(path)
207
+
208
+ update_document_content(uri, File.read(path))
209
+ end
210
+
211
+ # Maps an editor URI under the project root to the path this server reads it from.
212
+ # Returns nil for URIs outside the project.
213
+ def container_path_for(uri)
214
+ prefix = self.class.root_uri
215
+ return nil if self.class.root_path.nil? || !uri.start_with?(prefix)
216
+
217
+ File.join(self.class.root_path, URI.decode_uri_component(uri.delete_prefix(prefix)))
218
+ end
219
+
231
220
  def word_at_location(uri, position)
232
221
  context_at_location(uri, position)&.last
233
222
  end
234
223
 
235
224
  def possible_definitions(uri, position)
236
- name = word_at_location(uri, position)
237
- return {} if name.blank?
225
+ context = context_at_location(uri, position)
226
+ name = context&.last
227
+ return [] if name.blank?
238
228
 
229
+ # Special case: "new" should find "initialize" (instance method, not class method)
239
230
  name = 'initialize' if name == 'new'
240
- scope = scopes_at(uri, position).first
231
+
232
+ # Get current scopes for context
233
+ current_scopes = scopes_at(uri, position)
234
+
235
+ # If context has more than one element it could be a method call or namespace reference
236
+ if context.length > 1
237
+ # Find the rightmost class/module reference in the context (excluding the last element which is the name)
238
+ # Examples:
239
+ # - foo.Bar::Baz.something -> find Baz (index 2), build scope from Bar::Baz
240
+ # - Bar.foo.Baz.something -> find Baz (index 2), use Baz as scope
241
+ class_module_indices = []
242
+ (0...(context.length - 1)).each do |i|
243
+ class_module_indices << i if likely_class_name?(context[i])
244
+ end
245
+
246
+ if class_module_indices.any?
247
+ # Find the continuous chain of class/module names ending at the rightmost one
248
+ # For "Foo::Bar.method", we want both Foo and Bar, not just Bar
249
+ # For "foo.Bar::Baz.method", we want Bar and Baz, not just Baz
250
+ rightmost_class_index = class_module_indices.last
251
+
252
+ # Find the leftmost index of the continuous chain ending at rightmost_class_index
253
+ leftmost_continuous_index = rightmost_class_index
254
+ class_module_indices.reverse.each_cons(2) do |right, left|
255
+ break unless right == left + 1 # Break if not continuous
256
+
257
+ leftmost_continuous_index = left
258
+ end
259
+
260
+ scope_path_parts = context[leftmost_continuous_index..-2]
261
+ # A leading :: (::Foo::Bar) splits into an empty first element: top level only.
262
+ top_level = leftmost_continuous_index.positive? && context[leftmost_continuous_index - 1] == ''
263
+
264
+ # Resolve the receiver the way Ruby does: inside the enclosing namespaces first.
265
+ receiver_scopes = resolve_constant_scopes(scope_path_parts.join('::'), current_scopes, top_level:)
266
+
267
+ # Determine if it's a class/module lookup or a method call
268
+ # If the name also looks like a class/module name, it's a namespace lookup (Foo::Bar)
269
+ # Otherwise it's a method call (Foo.method or Foo::Bar.method)
270
+ return receiver_definitions_for(name, receiver_scopes) if likely_class_name?(name) || constant_name?(name)
271
+
272
+ # Method call - determine if it's a class method or instance method
273
+ class_method_filter = name != 'initialize'
274
+ return receiver_definitions_for(name, receiver_scopes, class_method_filter)
275
+
276
+ end
277
+
278
+ # No class/module found in chain, treat as instance method call on unknown type
279
+ # Search project-wide for all instance methods with this name
280
+ return project_definitions_for(name, [], false)
281
+ end
282
+
283
+ # No receiver - search in scope chain first, then project-wide
284
+ scope = current_scopes.first
241
285
  results = scope_definitions_for(name, scope, uri)
242
286
  return results unless results.empty?
243
287
 
244
- project_definitions_for(name)
288
+ # Always return an array
289
+ project_definitions_for(name, current_scopes) || []
290
+ end
291
+
292
+ # Hover for the word at position: the signature of the first definition that
293
+ # possible_definitions finds, or nil.
294
+ def hover_at(uri, position)
295
+ name = context_at_location(uri, position)&.last
296
+ return nil if name.blank?
297
+
298
+ name = 'initialize' if name == 'new'
299
+ definition = possible_definitions(uri, position).first
300
+ record = definition && record_at(definition, name)
301
+ markdown = record && Hover.markdown(record)
302
+ return nil if markdown.blank?
303
+
304
+ { contents: { kind: 'markdown', value: markdown } }
305
+ end
306
+
307
+ # The scope or variable named name that a definition location points at.
308
+ def record_at(location, name)
309
+ code_file = CodeFile.find_by(uri: location[:uri])
310
+ return nil if code_file.nil?
311
+
312
+ line = location[:range][:start][:line] + 1 # stored lines are 1-based
313
+ code_file.scopes.find_by(top_line: line, name:) || code_file.variables.find_by(line:, name:)
245
314
  end
246
315
 
247
316
  # Return variables found in the current scope. After all, those are the important ones.
248
317
  # Should probably be private...
249
318
  def scope_definitions_for(name, scope, uri)
250
319
  check_scope = scope
251
- return_array = []
320
+ matches = []
252
321
  while check_scope
253
- scope.variables.each do |variable|
254
- return_array << Location.hash(uri, variable.line, 1) if variable.name == name
322
+ check_scope.variables.each do |variable|
323
+ matches << Location.hash(uri, variable.line, variable.column.to_i) if variable.name == name
255
324
  end
256
325
  check_scope = check_scope.parent
257
326
  end
258
- RubyLanguageServer.logger.debug("==============>> scope_definitions_for(#{name}, #{scope.to_json}, #{uri}: #{return_array.uniq})")
259
- return_array.uniq
327
+ RubyLanguageServer.logger.debug("==============>> scope_definitions_for(#{name}, #{scope.to_json}, #{uri}: #{matches.inspect} )")
328
+ matches
260
329
  end
261
330
 
262
- def project_definitions_for(name)
263
- scopes = RubyLanguageServer::ScopeData::Scope.where(name:)
264
- variables = RubyLanguageServer::ScopeData::Variable.constant_variables.where(name:)
265
- (scopes + variables).reject { |scope| scope.code_file.nil? }.map do |scope|
266
- Location.hash(scope.code_file.uri, scope.top_line, 1)
267
- end
331
+ # class_method_filter is for new -> initialize
332
+ def project_definitions_for(name, parent_scopes = [], class_method_filter = nil)
333
+ # If no parent scope, search project-wide
334
+ return search_project_wide(name, class_method_filter) if parent_scopes.empty?
335
+
336
+ supplied_scope = parent_scopes.first
337
+
338
+ # First pass: Look for variables (constants) in the scope chain
339
+ result = search_variables_in_scope_chain(name, supplied_scope)
340
+ return result if result.any?
341
+
342
+ # Second pass: Look for child scopes in the scope chain
343
+ result = search_child_scopes_in_chain(name, supplied_scope, class_method_filter)
344
+ return result if result.any?
345
+
346
+ # Fall back to project-wide search
347
+ search_project_wide(name, class_method_filter)
268
348
  end
269
349
 
270
350
  private
271
351
 
272
- def code_file_for_uri(uri)
273
- CodeFile.find_by_uri(uri) || CodeFile.build(uri, nil)
352
+ # Convert a collection of scopes or variables to location hashes
353
+ def scope_or_variable_to_locations(items)
354
+ items = items.to_a
355
+ # One query for all the items' files, not one per item.
356
+ ActiveRecord::Associations::Preloader.new(records: items, associations: :code_file).call
357
+ items.reject { |item| item.code_file.nil? }.map do |item|
358
+ line = item.respond_to?(:top_line) ? item.top_line : item.line
359
+ Location.hash(item.code_file.uri, line, item.column.to_i)
360
+ end
361
+ end
362
+
363
+ # Search for a variable/constant up the scope chain (first pass)
364
+ # Variables in scope chain take priority over child scopes
365
+ def search_variables_in_scope_chain(name, supplied_scope)
366
+ current = supplied_scope
367
+ while current
368
+ # For constants, skip method scopes and keep searching up to class/module scopes
369
+ if current.class_type == RubyLanguageServer::ScopeData::Scope::TYPE_METHOD
370
+ current = current.parent
371
+ next
372
+ end
373
+
374
+ # Check variables (constants) in the current scope
375
+ matching_variable = current.variables.where(name: name).includes(:code_file).find(&:code_file)
376
+ if matching_variable
377
+ line = matching_variable.respond_to?(:top_line) ? matching_variable.top_line : matching_variable.line
378
+ return [Location.hash(matching_variable.code_file.uri, line, matching_variable.column.to_i)]
379
+ end
380
+
381
+ current = current.parent
382
+ end
383
+ []
274
384
  end
275
385
 
276
- def filename_relative_to_project(filename)
277
- filename.gsub(self.class.root_uri, self.class.root_path)
386
+ # Search for child scopes up the scope chain (second pass)
387
+ def search_child_scopes_in_chain(name, supplied_scope, class_method_filter)
388
+ current = supplied_scope
389
+ while current
390
+ # For constants, skip method scopes and keep searching up to class/module scopes
391
+ if current.class_type == RubyLanguageServer::ScopeData::Scope::TYPE_METHOD
392
+ current = current.parent
393
+ next
394
+ end
395
+
396
+ # Check child scopes (classes/modules/methods) with this name, then, for a class,
397
+ # its superclasses' before moving out to the enclosing scope, as Ruby does.
398
+ [current, *(current.class_scope? ? current.ancestor_class_scopes : [])].each do |scope|
399
+ child_scopes = scope.children.where(name: name)
400
+ child_scopes = child_scopes.where(class_method: class_method_filter) unless class_method_filter.nil?
401
+ return scope_or_variable_to_locations(child_scopes) if child_scopes.any?
402
+ end
403
+
404
+ current = current.parent
405
+ end
406
+ []
407
+ end
408
+
409
+ # Search for a name project-wide (fallback)
410
+ def search_project_wide(name, class_method_filter)
411
+ all_scopes = RubyLanguageServer::ScopeData::Scope.where(name: name)
412
+ all_scopes = all_scopes.where(class_method: class_method_filter) unless class_method_filter.nil?
413
+ all_variables = RubyLanguageServer::ScopeData::Variable.where(name: name)
414
+ all_matches = all_scopes.to_a + all_variables.to_a
415
+ scope_or_variable_to_locations(all_matches)
416
+ end
417
+
418
+ # The scopes a constant path like "Bar" or "Bar::Baz" refers to from the cursor.
419
+ # Like Ruby, try each enclosing class or module, innermost first, then the top
420
+ # level. Inside Outer::Other, "Inner" tries Outer::Other::Inner, Outer::Inner, Inner.
421
+ # Returns every scope with the first path that exists: a class reopened in several
422
+ # files has one scope per file. Returns [] if nothing matches.
423
+ #
424
+ # This uses the nesting of scope paths, so `class Outer::Other` counts as being
425
+ # inside Outer, which Ruby's lexical scope doesn't do.
426
+ def resolve_constant_scopes(path, current_scopes, top_level: false)
427
+ return [] if path.blank?
428
+
429
+ namespaces = top_level ? [] : current_scopes.select { |scope| type_is_class_or_module?(scope) }.map(&:path)
430
+ candidates = namespaces.map { |namespace| "#{namespace}::#{path}" } + [path]
431
+ candidates.each do |candidate|
432
+ scopes = RubyLanguageServer::ScopeData::Scope.where(path: candidate).to_a
433
+ return scopes if scopes.any?
434
+ end
435
+ []
436
+ end
437
+
438
+ def type_is_class_or_module?(scope)
439
+ [RubyLanguageServer::ScopeData::Base::TYPE_CLASS, RubyLanguageServer::ScopeData::Base::TYPE_MODULE].include?(scope.class_type)
440
+ end
441
+
442
+ # Definitions of name inside the receiver's scopes (and their parents), or anywhere
443
+ # in the project if there are none.
444
+ def receiver_definitions_for(name, receiver_scopes, class_method_filter = nil)
445
+ return search_project_wide(name, class_method_filter) if receiver_scopes.empty?
446
+
447
+ results = receiver_scopes.flat_map { |scope| search_variables_in_scope_chain(name, scope) }
448
+ results = receiver_scopes.flat_map { |scope| search_child_scopes_in_chain(name, scope, class_method_filter) } if results.empty?
449
+ results = search_project_wide(name, class_method_filter) if results.empty?
450
+ results.uniq
451
+ end
452
+
453
+ # Check if a name looks like a constant (all uppercase)
454
+ def constant_name?(name)
455
+ # Must start with uppercase letter and contain no lowercase letters
456
+ return false unless /\A[A-Z]/.match?(name)
457
+
458
+ !/[a-z]/.match?(name)
459
+ end
460
+
461
+ # Guess if a receiver name is likely a class name based on idiomatic Ruby conventions.
462
+ # This is a heuristic and not 100% accurate (e.g., FOO could be a constant holding an instance).
463
+ # Returns true for names like "Foo" or "FooBar" (starts with uppercase, has lowercase letters).
464
+ # Returns false for "FOO" (all uppercase constant) or "foo" (variable/method).
465
+ def likely_class_name?(name)
466
+ # Must start with uppercase letter
467
+ return false unless /[A-Z]/.match?(name[0])
468
+
469
+ # Must contain at least one lowercase letter to distinguish from constants like FOO
470
+ name =~ /[a-z]/
471
+ end
472
+
473
+ # The stored file for uri. For a URI the server hasn't seen, an unsaved, empty
474
+ # CodeFile, so lookups don't write to the database; CodeFile#update_text saves it.
475
+ def code_file_for_uri(uri)
476
+ CodeFile.find_by(uri:) || CodeFile.new(uri:)
278
477
  end
279
478
  end
280
479
  end
@@ -25,19 +25,27 @@ module RubyLanguageServer
25
25
  TYPE_VARIABLE => '^'
26
26
  }.freeze
27
27
 
28
- attr_accessor :type # Type of this scope (module, class, block)
28
+ # Return the class_type as a symbol for easier testing
29
+ def type
30
+ class_type&.to_sym
31
+ end
29
32
 
30
33
  # bar should be closer to Bar than Far. Adding the UPPER version accomplishes this.
34
+ # The word is always passed as a bound value, never interpolated into the SQL.
31
35
  scope :with_distance_from, lambda { |word|
32
- sanitized_word = sanitize_sql(word)
33
- where("LENGTH(name) >= LENGTH('#{sanitized_word}')").select("*, LEVENSHTEIN(SUBSTR(name, 1, #{word.length}), '#{sanitized_word}') + LEVENSHTEIN(SUBSTR(UPPER(name), 1, #{word.length}), UPPER('#{sanitized_word}')) as levenshtein_distance")
36
+ length = word.length
37
+ distance = sanitize_sql_array([
38
+ '*, LEVENSHTEIN(SUBSTR(name, 1, ?), ?) + LEVENSHTEIN(SUBSTR(UPPER(name), 1, ?), UPPER(?)) AS levenshtein_distance',
39
+ length, word, length, word
40
+ ])
41
+ where('LENGTH(name) >= ?', length).select(distance)
34
42
  }
35
43
  scope :closest_to, ->(word) { with_distance_from(word).order(:levenshtein_distance) }
36
44
 
37
45
  # RubyLanguageServer::ScopeData::Scope.connection.exec_query("SELECT LEVENSHTEIN( 'This is not correct', 'This is correct' )")
38
46
 
39
47
  def method?
40
- type == TYPE_METHOD
48
+ class_type == TYPE_METHOD
41
49
  end
42
50
  end
43
51
  end