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.
data/README.md CHANGED
@@ -1,4 +1,5 @@
1
1
  ![Build Status](https://github.com/kwerle/ruby_language_server/actions/workflows/test.yml/badge.svg)
2
+ ![Coverage](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/kwerle/ruby_language_server/develop/.github/badges/coverage.json)
2
3
  # Overview
3
4
 
4
5
  https://github.com/kwerle/ruby_language_server
@@ -15,7 +16,7 @@ Help welcome.
15
16
 
16
17
  * Definitions
17
18
  * Completions
18
- * Lint - thanks to [RuboCop](https://github.com/bbatsov/rubocop)
19
+ * Document symbols
19
20
  * Please see the [FAQ_ROADMAP.md](./FAQ_ROADMAP.md)
20
21
 
21
22
  # Editor Integrations
@@ -29,6 +30,32 @@ You probably want to use one of the developed integrations:
29
30
 
30
31
  `ruby_language_server` will start the program and wait for activity using LSP's STDIO interface
31
32
 
33
+ The Docker image runs as an unprivileged user (UID 1000) and writes only to `/data`
34
+ (the SQLite database, and the ActiveRecord log when `LOG_LEVEL=DEBUG`). Set
35
+ `RUBY_LANGUAGE_SERVER_DATA_DIR` to use a different directory. So it can run locked down,
36
+ with the project mounted read-only:
37
+
38
+ ```sh
39
+ docker run --rm -i --read-only --tmpfs /data:uid=1000,gid=1000 \
40
+ --mount type=bind,source="$PWD",target=/project,readonly \
41
+ kwerle/ruby_language_server
42
+ ```
43
+
44
+ Docker mounts a plain `--tmpfs` as root-owned and not writable by other users, so the
45
+ `uid=1000,gid=1000` options are needed.
46
+
47
+ # Compatibility
48
+
49
+ The server stays backward compatible with the protocol clients use today. Removing or
50
+ changing a capability, a result's shape, or a default that clients rely on is a breaking
51
+ change. Breaking changes get a major version bump, announced in advance in
52
+ [CHANGELOG.txt](CHANGELOG.txt) and a GitHub issue. While the version is 0.x, the first
53
+ breaking change will be 1.0.0, so clients can treat any 0.x release as compatible.
54
+
55
+ Clients can read the running version from `serverInfo` in the `initialize` result, for example
56
+ `{ "name": "ruby_language_server", "version": "0.9.8" }`. Servers older than the release
57
+ that added it don't send `serverInfo`.
58
+
32
59
  # Development
33
60
 
34
61
  Master branch is for releases. Develop branch is for ongoing development. Fork off develop;
@@ -43,6 +70,33 @@ I use vscode with the "Ruby Language Server" extension install. I edit the sett
43
70
  the docker image local_ruby_language_server. Quitting and restarting vscode to load the next
44
71
  iteration.
45
72
 
73
+ ## Debugging the server
74
+
75
+ You can debug this checkout's code with breakpoints, through a client in an Extension
76
+ Development Host window. You need the [rdbg extension](https://marketplace.visualstudio.com/items?itemName=KoichiSasada.vscode-rdbg)
77
+ and a checkout of [vscode_ruby_language_server](https://github.com/kwerle/vscode_ruby_language_server).
78
+
79
+ 1. Check out vscode_ruby_language_server next to this repo (`../vscode_ruby_language_server`).
80
+ 2. Set breakpoints in `lib/`.
81
+ 3. In this repo's window, Run and Debug "Debug server + client". It runs `make debug_server`,
82
+ which starts the server in Docker with this checkout mounted (no image rebuild needed), LSP
83
+ on TCP port 7658 and rdbg on 12345, and attaches the debugger. It also builds the client and
84
+ opens an Extension Development Host window on this repo whose client connects to port 7658.
85
+ 4. Open a Ruby file in that new window. Breakpoints hit once the client sends requests; until
86
+ then the server just waits for the connection.
87
+
88
+ Notes:
89
+
90
+ * The project the client opens must be the one mounted at `/project`. Both default to this
91
+ repo; to use another, run `make debug_server PROJECT=/path/to/project` and open that folder.
92
+ * The server accepts one connection per run and exits when it closes, so closing the client
93
+ window ends the session. Run "Debug server + client" again to start over.
94
+ * The background scanner runs in a forked process, which isn't debugged
95
+ (`RUBY_DEBUG_FORK_MODE=parent`).
96
+ * Rebuild the image (`make image`) only after changing the Gemfile.
97
+ * No Ruby is needed on the host. The rdbg extension checks `rdbg --version` even when attaching,
98
+ so "Debug server" sets `rdbgPath` to `bin/rdbg`, which runs rdbg in the debug container.
99
+
46
100
  # Similar
47
101
 
48
102
  * [mtsmfm/language_server-ruby](https://github.com/mtsmfm/language_server-ruby)
@@ -50,14 +104,30 @@ iteration.
50
104
 
51
105
  # Release instructions to self
52
106
 
53
- For gem release
107
+ Images and the gem are published only by the [release workflow](.github/workflows/release.yml),
108
+ when a `v*` tag is pushed for a commit on master. Never push `kwerle/ruby_language_server` from a
109
+ laptop: the VS Code client runs `:latest` on every start.
110
+
54
111
  * bump version in [version.rb](lib/ruby_language_server/version.rb) file and [Gemfile.lock](Gemfile.lock)
55
112
  * [CHANGELOG.txt](CHANGELOG.txt)
56
- * merge to master, etc
57
- * `make gem_release`
58
-
59
- For docker release
60
- * `make publish_cross_platform_image`
113
+ * `git flow release start 0.9.8` ... `git flow release finish 0.9.8`
114
+ (with `git config gitflow.prefix.versiontag v`, this tags master as `v0.9.8`)
115
+ * `git push origin master develop v0.9.8`
116
+ * CI checks the tag matches `version.rb`, builds and pushes `:latest` and `:0.9.8`
117
+ for amd64 and arm64, signs the image with cosign, pushes the gem to RubyGems, and creates
118
+ the GitHub release.
119
+ * The gem is pushed with RubyGems [trusted publishing](https://guides.rubygems.org/trusted-publishing/),
120
+ so the repo holds no RubyGems key. On rubygems.org, ruby_language_server's trusted publisher is
121
+ repository `kwerle/ruby_language_server`, workflow `release.yml`, environment `release`.
122
+ `make gem_release` still works by hand if CI can't push.
123
+
124
+ To verify a published image:
125
+
126
+ ```sh
127
+ cosign verify kwerle/ruby_language_server:latest \
128
+ --certificate-identity-regexp '^https://github.com/kwerle/ruby_language_server/.github/workflows/release.yml@refs/tags/v' \
129
+ --certificate-oidc-issuer https://token.actions.githubusercontent.com
130
+ ```
61
131
 
62
132
  # Authors
63
133
 
data/bin/rdbg ADDED
@@ -0,0 +1,8 @@
1
+ #!/bin/sh
2
+ # rdbg from the Docker image, for the VS Code rdbg extension ("rdbgPath" in .vscode/launch.json).
3
+ # The extension runs `rdbg --version` on the host even when attaching over TCP; host Ruby
4
+ # isn't used for this project, so answer from the debug container (or the image if it isn't up).
5
+ if docker container inspect rls-debug >/dev/null 2>&1; then
6
+ exec docker exec -i rls-debug bundle exec rdbg "$@"
7
+ fi
8
+ exec docker run --rm -i ruby_language_server bundle exec rdbg "$@"
data/bin/run_in_shell ADDED
@@ -0,0 +1,5 @@
1
+ #!/bin/sh
2
+ # Mostly so AI can run commands in a consistent environment
3
+ SHELL_COMMAND="$*"
4
+ export SHELL_COMMAND
5
+ make run_in_shell
@@ -1,4 +1,4 @@
1
- #!/usr/local/bin/ruby
1
+ #!/usr/bin/env ruby
2
2
  # frozen_string_literal: true
3
3
 
4
4
  $LOAD_PATH << File.join(__dir__, '..', 'lib')
@@ -1,28 +1,28 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ extension_path = if Gem.win_platform?
4
+ 'liblevenshtein.dll'
5
+ else
6
+ '/usr/local/lib/liblevenshtein.so.0.0.0'
7
+ end
8
+
9
+ # Everything the server writes goes in one directory, so the container can run with
10
+ # --read-only --tmpfs /data:uid=1000,gid=1000.
11
+ data_dir = ENV.fetch('RUBY_LANGUAGE_SERVER_DATA_DIR', '/data')
12
+
3
13
  ActiveRecord::Base.establish_connection(
4
14
  adapter: 'sqlite3',
5
- database: '/database',
15
+ database: File.join(data_dir, 'database'),
6
16
  pool: 5,
7
- timeout: 30.seconds # does not seem to help
17
+ timeout: 5000, # milliseconds SQLite waits for a lock held by the background scanner
18
+ extensions: [extension_path]
8
19
  )
9
20
 
10
- ActiveSupport.on_load(:active_record) do
11
- database = ActiveRecord::Base.connection.raw_connection
12
- database.enable_load_extension(1)
13
- if Gem.win_platform?
14
- # load DLL from PATH
15
- database.load_extension('liblevenshtein.dll')
16
- else
17
- database.load_extension('/usr/local/lib/liblevenshtein.so.0.0.0')
18
- end
19
- database.enable_load_extension(0)
20
- end
21
-
22
21
  if ENV['LOG_LEVEL'] == 'DEBUG'
23
22
  begin
24
- warn('Turning on active record logging to active_record.log')
25
- ActiveRecord::Base.logger = Logger.new(File.open('/active_record.log', 'w'))
23
+ log_path = File.join(data_dir, 'active_record.log')
24
+ warn("Turning on active record logging to #{log_path}")
25
+ ActiveRecord::Base.logger = Logger.new(File.open(log_path, 'w'))
26
26
  rescue Exception => e
27
27
  ActiveRecord::Base.logger = Logger.new($stderr)
28
28
  ActiveRecord::Base.logger.error(e)
data/lib/db/schema.rb CHANGED
@@ -18,6 +18,8 @@ module Schema
18
18
  t.string :superclass_name
19
19
  t.string :path
20
20
  t.string :class_type, null: false
21
+ t.text :parameters # JSON string of method parameters
22
+ t.boolean :class_method, default: false # true for class methods (def self.method)
21
23
  end
22
24
 
23
25
  add_index :scopes, :name
@@ -41,6 +43,8 @@ module Schema
41
43
  t.string :uri
42
44
  t.boolean :refresh_root_scope, default: true
43
45
  t.text :text
46
+ t.float :parsed_at # Process::CLOCK_MONOTONIC seconds of the last parse
47
+ t.integer :parsed_line_count # lines in the text that was last parsed
44
48
  end
45
49
 
46
50
  add_index :code_files, :uri
@@ -53,7 +57,7 @@ module Schema
53
57
  def already_initialized
54
58
  response = ActiveRecord::Base.connection_pool.with_connection { |con| con.exec_query "SELECT name FROM sqlite_master WHERE type='table'" }
55
59
  response.rows.flatten.member?('code_files')
56
- rescue ExceptionName
60
+ rescue ActiveRecord::StatementInvalid
57
61
  false
58
62
  end
59
63
 
@@ -8,7 +8,6 @@ require_relative '../config/initializers/active_record'
8
8
  require_relative '../db/schema'
9
9
 
10
10
  require_relative 'version'
11
- require_relative 'gem_installer'
12
11
  require_relative 'io'
13
12
  require_relative 'location'
14
13
  require_relative 'code_file'
@@ -17,13 +16,13 @@ require_relative 'project_manager'
17
16
  require_relative 'server'
18
17
  require_relative 'line_context'
19
18
  require_relative 'completion'
19
+ require_relative 'hover'
20
20
 
21
21
  module RubyLanguageServer
22
22
  class Application
23
23
  def start
24
- update_mutex = Monitor.new
25
- server = RubyLanguageServer::Server.new(update_mutex)
26
- RubyLanguageServer::IO.new(server, update_mutex)
24
+ server = RubyLanguageServer::Server.new
25
+ RubyLanguageServer::IO.new(server)
27
26
  end
28
27
  end
29
28
  end
@@ -55,12 +55,10 @@ module RubyLanguageServer
55
55
 
56
56
  def tags
57
57
  RubyLanguageServer.logger.debug("Asking about tags for #{uri}")
58
- @tags ||= [{}]
59
- return @tags if text.nil?
60
- return @tags = [{}] if text == ''
58
+ return [] if text.blank?
61
59
 
62
60
  refresh_scopes_if_needed # cause root scope to reset
63
- return @tags if scopes.reload.count <= 1 # just the root
61
+ return [] if scopes.reload.count <= 1 # just the root
64
62
 
65
63
  tags = scopes.reload.map do |scope|
66
64
  next if scope.class_type == ScopeData::Base::TYPE_BLOCK
@@ -71,7 +69,7 @@ module RubyLanguageServer
71
69
  scope_hash = {
72
70
  name: scope.name,
73
71
  kind:,
74
- location: Location.hash(uri, scope.top_line)
72
+ location: Location.hash(uri, scope.top_line, scope.column, scope.bottom_line)
75
73
  }
76
74
  container_name = ancestor_scope_name(scope)
77
75
  scope_hash[:containerName] = container_name unless container_name.blank?
@@ -82,22 +80,21 @@ module RubyLanguageServer
82
80
  {
83
81
  name:,
84
82
  kind: SYMBOL_KIND[:constant],
85
- location: Location.hash(uri, variable.line - 1),
83
+ location: Location.hash(uri, variable.line, variable.column),
86
84
  containerName: variable.scope.name
87
85
  }
88
86
  end
89
- tags = tags.compact.reject { |tag| tag[:name].nil? || tag[:name] == RubyLanguageServer::ScopeData::Scope::TYPE_BLOCK }
87
+ # Clients reject a symbol with a blank name, and fail the whole request (task '', attr_accessor '').
88
+ tags = tags.compact.reject { |tag| tag[:name].blank? || tag[:name] == RubyLanguageServer::ScopeData::Scope::TYPE_BLOCK }
90
89
  # RubyLanguageServer.logger.debug("Raw tags for #{uri}: #{tags}")
91
90
  # If you don't reverse the list then atom? won't be able to find the
92
91
  # container and containers will get duplicated.
93
- @tags = tags.reverse_each do |tag|
92
+ tags.reverse_each do |tag|
94
93
  child_tags = tags.select { |child_tag| child_tag[:containerName] == tag[:name] }
95
94
  max_line = child_tags.map { |child_tag| child_tag[:location][:range][:end][:line].to_i }.max || 0
96
95
  tag[:location][:range][:end][:line] = [tag[:location][:range][:end][:line], max_line].max
97
96
  end
98
- # RubyLanguageServer.logger.debug("Done with tags for #{uri}: #{@tags}")
99
- # RubyLanguageServer.logger.debug("tags caller #{caller * ','}")
100
- @tags
97
+ tags
101
98
  end
102
99
 
103
100
  def update_text(new_text)
@@ -108,8 +105,15 @@ module RubyLanguageServer
108
105
  update(text: new_text, refresh_root_scope: true)
109
106
  end
110
107
 
111
- def refresh_scopes_if_needed(shallow: false)
108
+ # While someone types within a line, re-parse at most this often. An edit that
109
+ # changes the number of lines is re-parsed at once, so stored line ranges stay valid.
110
+ # 0 re-parses on every request (the specs use that).
111
+ REPARSE_INTERVAL = Float(ENV.fetch('RUBY_LANGUAGE_SERVER_REPARSE_INTERVAL', '1.0')) # seconds
112
+
113
+ def refresh_scopes_if_needed
114
+ return if new_record? # nothing stored yet, so nothing to parse
112
115
  return unless refresh_root_scope
116
+ return if reparse_can_wait?
113
117
 
114
118
  RubyLanguageServer.logger.debug("Asking about root_scope for #{uri}")
115
119
  RubyLanguageServer::ScopeData::Variable.where(code_file_id: self).scoping do
@@ -117,24 +121,45 @@ module RubyLanguageServer
117
121
  self.class.transaction do
118
122
  scopes.clear
119
123
  variables.clear
120
- new_root = ScopeParser.new(text, shallow).root_scope
124
+ new_root = ScopeParser.new(text).root_scope
121
125
  RubyLanguageServer.logger.debug("new_root.children #{new_root.children.as_json}") if new_root&.children
122
126
  raise ActiveRecord::Rollback if new_root.nil? || new_root.children.blank?
123
127
 
124
- update_attribute(:refresh_root_scope, false)
128
+ update_columns(refresh_root_scope: false, parsed_at: monotonic_now, parsed_line_count: line_count)
125
129
  new_root
126
130
  end
127
131
  end
128
132
  end
129
133
  end
130
134
 
135
+ # True when the last parse was recent and the edits since then kept the line count,
136
+ # so its scopes still line up with the text. The next request after the interval
137
+ # re-parses.
138
+ def reparse_can_wait?
139
+ return false if parsed_at.nil?
140
+
141
+ parsed_line_count == line_count && monotonic_now - parsed_at < reparse_interval
142
+ end
143
+
144
+ def reparse_interval
145
+ REPARSE_INTERVAL
146
+ end
147
+
148
+ def line_count
149
+ text.to_s.count("\n")
150
+ end
151
+
152
+ def monotonic_now
153
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
154
+ end
155
+
131
156
  # Returns the context of what is being typed in the given line
132
157
  def context_at_location(position)
133
- lines = text.split("\n")
158
+ lines = text.to_s.split("\n")
134
159
  line = lines[position.line]
135
160
  return [] if line.nil? || line.strip.empty?
136
161
 
137
- LineContext.for(line, position.character)
162
+ LineContext.for(line, LineContext.character_index(line, position.character))
138
163
  end
139
164
  end
140
165
  end
@@ -24,39 +24,115 @@ module RubyLanguageServer
24
24
  }.freeze
25
25
 
26
26
  class << self
27
- def completion(context, context_scope, position_scopes)
27
+ # _context_scope is unused, and kept so callers don't change.
28
+ def completion(context, _context_scope, position_scopes)
28
29
  RubyLanguageServer.logger.debug("completion(#{context}, #{position_scopes.map(&:name)})")
29
30
  completions =
30
31
  if context.length < 2
31
32
  scope_completions(context.first, position_scopes)
32
33
  else
33
- scope_completions_in_target_context(context, context_scope, position_scopes)
34
+ scope_completions_in_target_context(context, position_scopes)
34
35
  end
35
36
  # RubyLanguageServer.logger.debug("completions: #{completions.as_json}")
36
37
  {
37
38
  isIncomplete: true,
38
39
  items: completions.uniq.map do |word, hash|
39
- {
40
+ item = {
40
41
  label: word,
41
42
  kind: COMPLETION_ITEM_KIND[hash[:type]&.to_sym]
42
43
  }
44
+
45
+ # Add snippet and parameter info for methods with parameters
46
+ if hash[:type] == 'method' && hash[:parameters]&.any?
47
+ item[:label] = generate_method_label(word, hash[:parameters])
48
+ item[:insertText] = generate_method_snippet(word, hash[:parameters])
49
+ item[:insertTextFormat] = 2 # Snippet format
50
+ item[:detail] = format_parameter_details(hash[:parameters])
51
+ end
52
+
53
+ item
43
54
  end
44
55
  }
45
56
  end
46
57
 
47
58
  private
48
59
 
60
+ def generate_method_label(method_name, parameters)
61
+ return method_name if parameters.empty?
62
+
63
+ param_labels = parameters.map do |param|
64
+ case param['type']
65
+ when 'keyword'
66
+ "#{param['name'].delete_suffix(':')}:"
67
+ when 'optional'
68
+ "[#{param['name']}]"
69
+ else
70
+ # rest, keyword_rest, block, and required params all use the name as-is
71
+ param['name']
72
+ end
73
+ end
74
+
75
+ "#{method_name}(#{param_labels.join(', ')})"
76
+ end
77
+
78
+ def format_parameter_details(parameters)
79
+ return '' if parameters.empty?
80
+
81
+ param_details = parameters.map do |param|
82
+ case param['type']
83
+ when 'keyword'
84
+ "#{param['name'].delete_suffix(':')}: (keyword)"
85
+ when 'optional'
86
+ "#{param['name']} = ... (optional)"
87
+ when 'rest'
88
+ "#{param['name']} (rest)"
89
+ when 'keyword_rest'
90
+ "#{param['name']} (keyword_rest)"
91
+ when 'block'
92
+ "#{param['name']} (block)"
93
+ else
94
+ "#{param['name']} (required)"
95
+ end
96
+ end
97
+
98
+ param_details.join(', ')
99
+ end
100
+
101
+ def generate_method_snippet(method_name, parameters)
102
+ return method_name if parameters.empty?
103
+
104
+ # Build snippet with tab stops
105
+ param_snippets = []
106
+ tab_index = 1
107
+
108
+ parameters.each do |param|
109
+ param_snippets << case param['type']
110
+ when 'keyword'
111
+ # Keyword args with placeholder for value
112
+ # Remove trailing colon from param['name'] if present, then add it back
113
+ key_name = param['name'].delete_suffix(':')
114
+ "#{key_name}: ${#{tab_index}:value}"
115
+ else
116
+ # For all other types (rest, keyword_rest, block, required, optional)
117
+ # use the parameter name with a snippet placeholder
118
+ "${#{tab_index}:#{param['name']}}"
119
+ end
120
+ tab_index += 1
121
+ end
122
+
123
+ "#{method_name}(#{param_snippets.join(', ')})"
124
+ end
125
+
49
126
  def scopes_with_name(name, scopes)
50
127
  return scopes.where(name:) if scopes.respond_to?(:where)
51
128
 
52
129
  scopes.select { |scope| scope.name == name }
53
130
  end
54
131
 
55
- def scope_completions_in_target_context(context, context_scope, scopes)
132
+ def scope_completions_in_target_context(context, scopes)
56
133
  context_word = context[-2]
57
134
  context_word = context_word.split('_').map(&:capitalize).join unless context_word.match?(/^[A-Z]/)
58
135
  context_scopes = RubyLanguageServer::ScopeData::Scope.where(name: context_word)
59
- context_scopes ||= context_scope
60
136
  RubyLanguageServer.logger.debug("context_scopes: #{context_scopes.to_json}")
61
137
  # scope_completions(context.last, Array(context_scopes) + scopes.includes(:variables))
62
138
  (scope_completions(context.last, Array(context_scopes)).to_a + scope_completions(context.last, scopes.includes(:variables)).to_a).uniq.to_h
@@ -65,28 +141,31 @@ module RubyLanguageServer
65
141
  def module_completions(word)
66
142
  class_and_module_types = [RubyLanguageServer::ScopeData::Base::TYPE_CLASS, RubyLanguageServer::ScopeData::Base::TYPE_MODULE]
67
143
 
68
- # scope_words = RubyLanguageServer::ScopeData::Scope.where(class_type: class_and_module_types).sort_by(&:depth).map { |scope| [scope.name, scope] }
69
- # words = scope_words.to_h
70
- # good_words = FuzzyMatch.new(words.keys, threshold: 0.01).find_all(word).slice(0..10) || []
71
- # words = good_words.each_with_object({}) { |w, hash| hash[w] = {depth: words[w].depth, type: words[w].class_type} }.to_h
72
-
73
144
  words = RubyLanguageServer::ScopeData::Scope.where(class_type: class_and_module_types).closest_to(word).limit(20)
74
- RubyLanguageServer.logger.error("module_completions: #{words.as_json}")
145
+ RubyLanguageServer.logger.debug { "module_completions: #{words.as_json}" }
75
146
  # words.to_a.sort_by(&:depth).each_with_object({}){|a_word, hash| hash[a_word.name] = {depth: a_word.depth, type: a_word.class_type} }
76
147
  good_words = FuzzyMatch.new(words.to_a, read: :name, threshold: 0.01).find_all(word).slice(0..10) || []
77
- good_words.each_with_object({}) { |w, hash| hash[w.name] = {depth: w.depth, type: w.class_type} }.to_h
148
+ good_words.to_h { |w| [w.name, {depth: w.depth, type: w.class_type}] }
78
149
  end
79
150
 
80
151
  def scope_completions(word, scopes)
81
152
  return module_completions(word) if word.match?(/\A[A-Z][a-z]/)
82
153
 
83
154
  scope_ids = scopes.map(&:id)
155
+ # Members inherited from superclasses are candidates too.
156
+ inherited_ids = scopes.select(&:class_scope?).flat_map(&:ancestor_class_scopes).map(&:id)
84
157
  word_scopes = scopes.to_a + RubyLanguageServer::ScopeData::Scope.where(parent_id: scope_ids).closest_to(word).limit(5)
158
+ word_scopes += RubyLanguageServer::ScopeData::Scope.where(parent_id: inherited_ids).closest_to(word).limit(5) if inherited_ids.any?
85
159
  scope_words = word_scopes.select(&:named_scope?).sort_by(&:depth).map { |scope| [scope.name, scope] }
86
160
  variable_words = RubyLanguageServer::ScopeData::Variable.where(scope_id: scope_ids).closest_to(word).limit(5).map { |variable| [variable.name, variable.scope] }
87
161
  words = (scope_words + variable_words).to_h
88
162
  good_words = FuzzyMatch.new(words.keys, threshold: 0.01).find_all(word).slice(0..10) || []
89
- words = good_words.each_with_object({}) { |w, hash| hash[w] = {depth: words[w].depth, type: words[w].class_type} }.to_h
163
+ good_words.each_with_object({}) do |w, hash|
164
+ scope = words[w]
165
+ hash[w] = {depth: scope.depth, type: scope.class_type}
166
+ # Include parameters for methods
167
+ hash[w][:parameters] = scope.parsed_parameters if scope.method? && scope.parameters.present?
168
+ end
90
169
  end
91
170
  end
92
171
  end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyLanguageServer
4
+ # Markdown for textDocument/hover, built from what the index already stores.
5
+ module Hover
6
+ class << self
7
+ # A Scope (class, module or method) or a Variable.
8
+ def markdown(record)
9
+ case record
10
+ when ScopeData::Variable then variable_markdown(record)
11
+ when ScopeData::Scope then scope_markdown(record)
12
+ end
13
+ end
14
+
15
+ private
16
+
17
+ def scope_markdown(scope)
18
+ case scope.class_type
19
+ when ScopeData::Base::TYPE_METHOD then method_markdown(scope)
20
+ when ScopeData::Base::TYPE_CLASS then code_block(['class', scope.path, superclass(scope)].compact.join(' '))
21
+ when ScopeData::Base::TYPE_MODULE then code_block("module #{scope.path}")
22
+ end
23
+ end
24
+
25
+ def superclass(scope)
26
+ "< #{scope.superclass_name}" if scope.superclass_name.present?
27
+ end
28
+
29
+ def method_markdown(scope)
30
+ receiver = scope.class_method ? 'self.' : ''
31
+ parameters = scope.parsed_parameters.map { |parameter| parameter_text(parameter) }
32
+ signature = "def #{receiver}#{scope.name}"
33
+ signature += "(#{parameters.join(', ')})" if parameters.any?
34
+ [code_block(signature), container_line(scope.parent)].compact.join("\n\n")
35
+ end
36
+
37
+ # Parameters are stored as { 'name' => ..., 'type' => ... } (see PrismProcessor).
38
+ # Rest, keyword rest and block names already carry their *, ** or &, and keyword
39
+ # names their trailing colon.
40
+ def parameter_text(parameter)
41
+ parameter['type'] == 'optional' ? "#{parameter['name']} = …" : parameter['name']
42
+ end
43
+
44
+ def variable_markdown(variable)
45
+ [code_block(variable.name), "Defined in `#{variable.scope&.path.presence || 'top level'}`, line #{variable.line}"].join("\n\n")
46
+ end
47
+
48
+ def container_line(scope)
49
+ return nil if scope.nil? || scope.path.blank?
50
+
51
+ "In `#{scope.path}`"
52
+ end
53
+
54
+ def code_block(code)
55
+ "```ruby\n#{code}\n```"
56
+ end
57
+ end
58
+ end
59
+ end