Module: RubyTestIDE

Defined in:
lib/ruby_test_ide/runner.rb,
lib/ruby_test_ide/server.rb,
lib/ruby_test_ide/server.rb,
lib/ruby_test_ide/version.rb

Defined Under Namespace

Classes: DocStore, Server

Constant Summary collapse

SANDBOX_PATH =
'(ruby-ide)'
MAX_TRACE_EVENTS =
50_000
MAX_ITEMS =
300
RECEIVER_TIMEOUT =

seconds for evaluating the completion receiver

2
OBS_REL =
File.join('.ruby-ide', 'observations.json')
KEYWORDS =
%w[
  BEGIN END alias and begin break case class def defined? do else elsif end
  ensure false for if in module next nil not or redo rescue retry return
  self super then true undef unless until when while yield
  require require_relative attr_accessor attr_reader attr_writer
].freeze
ROOT =
__dir__
RUNNER =
File.join(ROOT, 'runner.rb')
RUNNER_TIMEOUT =

seconds of wall clock before the worker is killed

4
WORKSPACE =

The project directory being edited. The ruby-test-ide executable sets the env var to --workspace (default: the directory it was launched from).

File.expand_path(ENV['RUBY_TEST_IDE_WORKSPACE'] || Dir.pwd)
AUTH_DISABLED =

The server executes arbitrary code from any request it accepts, so every route except /health and /vendor/* (static library assets, no user data) requires this token — set by the ruby-test-ide executable, which generates a random one per launch unless --token/--no-auth override it.

ENV['RUBY_TEST_IDE_NO_AUTH'] == '1'
TOKEN =
ENV['RUBY_TEST_IDE_TOKEN'].to_s
WORKSPACE_IGNORE =
%r{(\A|/)(\.git|node_modules|tmp|\.bundle|\.ruby-ide)(/|\z)}
RUBY_FILENAMES =

The sidebar is a Ruby IDE, not a general file browser: showing every file (Gemfile.lock, README, dotfiles) invited opening a non-Ruby file, which the editor still force-parsed as Ruby and reported bogus syntax errors on. Extensionless Ruby files are named explicitly.

%w[Gemfile Rakefile].freeze
TEST_GLOBS =
['test/**/*_test.rb', 'test/**/test_*.rb', 'spec/**/*_spec.rb'].freeze
LEARN_TIMEOUT =

whole learn commands get a bigger budget than single evals

60
OBSERVATIONS =
File.join(WORKSPACE, '.ruby-ide', 'observations.json')
OBSERVER =
File.join(ROOT, 'observer.rb')
CONFIG_FILE =
File.join(WORKSPACE, '.ruby_ide.yaml')
DOCS =
DocStore.new
VERSION =
'0.1.0'

Class Method Summary collapse

Class Method Details

.activate_bundler(dir) ⇒ Object

If the workspace has a Gemfile (in the file's directory or above it), activate it so require 'some-gem' resolves exactly as it would under bundle exec ruby file.rb. Returns an error description (surfaced to the editor) when the bundle isn't installed, nil otherwise.



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/ruby_test_ide/runner.rb', line 102

def activate_bundler(dir)
  # Walk up from the file's directory, but never above the workspace
  # root — a stray Gemfile in the user's home must not leak in.
  root = File.expand_path(@workspace_root.to_s.empty? ? dir : @workspace_root)
  gemfile = nil
  Pathname.new(File.expand_path(dir)).ascend do |p|
    candidate = p.join('Gemfile')
    if candidate.file?
      gemfile = candidate.to_s
      break
    end
    break if p.to_s == root || !p.to_s.start_with?(root)
  end
  return nil unless gemfile

  ENV['BUNDLE_GEMFILE'] = gemfile
  # Pin the already-loaded bundler: without this, a lockfile BUNDLED WITH
  # an older installed bundler makes bundler/setup RE-EXEC this process,
  # and the restarted runner finds stdin already consumed (empty request).
  require 'bundler/version'
  ENV['BUNDLER_VERSION'] ||= Bundler::VERSION
  require 'bundler/setup'
  nil
rescue Exception => e # rubocop:disable Lint/RescueException
  { 'class' => e.class.to_s,
    'message' => truncate("#{e.message} — try `bundle install` in #{File.dirname(gemfile)}", 400) }
end

.bare_items(bind, prefix) ⇒ Object



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
# File 'lib/ruby_test_ide/runner.rb', line 242

def bare_items(bind, prefix)
  items = []
  main = bind.receiver

  bind.local_variables.each do |v|
    val = bind.local_variable_get(v)
    items << { 'name' => v.to_s, 'kind' => 'variable', 'class' => class_of(val).to_s,
               'value' => safe_inspect(val), 'sort' => 0 }
  end
  bind.eval('instance_variables').each do |v|
    items << { 'name' => v.to_s, 'kind' => 'variable', 'sort' => 1 }
  end
  if prefix.start_with?('$')
    global_variables.each { |v| items << { 'name' => v.to_s, 'kind' => 'variable', 'sort' => 3 } }
  end
  (main.methods + main.private_methods).map(&:to_s).uniq.each do |n|
    next if n.start_with?('_')

    item = { 'name' => n, 'kind' => 'method', 'sort' => 4 }
    if (m = safe_method(main, n))
      item['signature'] = signature(n, m)
      item['owner'] = m.owner.to_s
    end
    items << item
  end
  Object.constants.map(&:to_s).each do |c|
    items << { 'name' => c, 'kind' => 'constant', 'sort' => 2 }
  end
  KEYWORDS.each { |k| items << { 'name' => k, 'kind' => 'keyword', 'sort' => 5 } }

  items.select! { |i| i['name'].start_with?(prefix) } unless prefix.empty?
  items.uniq { |i| i['name'] }.sort_by { |i| [i['sort'], i['name']] }.first(MAX_ITEMS)
end

.capture_locals(b) ⇒ Object



462
463
464
465
466
467
468
469
# File 'lib/ruby_test_ide/runner.rb', line 462

def capture_locals(b)
  b.local_variables.each_with_object({}) do |v, h|
    val = b.local_variable_get(v)
    h[v.to_s] = { 'class' => class_of(val).to_s, 'value' => safe_inspect(val) }
  end
rescue Exception # rubocop:disable Lint/RescueException
  {}
end

.class_of(obj) ⇒ Object



483
484
485
# File 'lib/ruby_test_ide/runner.rb', line 483

def class_of(obj)
  ::Kernel.instance_method(:class).bind_call(obj)
end

.complete(req) ⇒ Object

------------------------------------------------------------- completion



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/ruby_test_ide/runner.rb', line 201

def complete(req)
  bind, error = eval_context(req['code_before'])
  receiver = req['receiver'].to_s
  prefix = req['prefix'].to_s

  if receiver.strip.empty?
    { 'items' => bare_items(bind, prefix), 'context_error' => error }.compact
  else
    obj =
      begin
        Timeout.timeout(RECEIVER_TIMEOUT) { bind.eval(receiver, sandbox_path) }
      rescue Exception => e # rubocop:disable Lint/RescueException
        oracle = oracle_complete(bind, receiver, prefix)
        return oracle.merge('context_error' => error).compact if oracle

        return { 'items' => [], 'context_error' => error,
                 'receiver_error' => truncate("#{e.class}: #{e.message}", 200) }.compact
      end
    { 'items' => receiver_items(obj, prefix),
      'receiver_class' => class_of(obj).to_s,
      'context_error' => error }.compact
  end
end

.default_learn_commandsObject

No config? Guess: run each minitest file / the spec dir, under bundler when the workspace has a Gemfile.



88
89
90
91
92
93
94
95
# File 'lib/ruby_test_ide/server.rb', line 88

def self.default_learn_commands
  prefix = File.file?(File.join(WORKSPACE, 'Gemfile')) ? 'bundle exec ' : ''
  tests = discover_tests
  specs, minitests = tests.partition { |f| f.end_with?('_spec.rb') }
  commands = minitests.map { |f| "#{prefix}ruby #{f.delete_prefix("#{WORKSPACE}/")}" }
  commands << "#{prefix}rspec" unless specs.empty?
  commands
end

.describe_error(e) ⇒ Object



193
194
195
196
197
# File 'lib/ruby_test_ide/runner.rb', line 193

def describe_error(e)
  line = e.backtrace_locations&.find { |l| l.path == sandbox_path }&.lineno
  line ||= e.message[/#{Regexp.escape(sandbox_path)}:(\d+)/, 1]&.to_i
  { 'class' => e.class.to_s, 'message' => truncate(e.message, 500), 'line' => line }
end

.discover_testsObject



66
67
68
# File 'lib/ruby_test_ide/server.rb', line 66

def self.discover_tests
  TEST_GLOBS.flat_map { |g| Dir.glob(File.join(WORKSPACE, g)) }.uniq.sort
end

.enter_workspace(req) ⇒ Object

Evaluate "in place": chdir to the file's directory and use its real path as the eval filename, so require_relative / FILE / dir behave as they would when running the file with ruby. The buffer content still comes from the request (unsaved edits included).



86
87
88
89
90
91
92
93
94
95
96
# File 'lib/ruby_test_ide/runner.rb', line 86

def enter_workspace(req)
  @sandbox_path = req['path'].to_s.empty? ? SANDBOX_PATH : req['path']
  @workspace_root = req['root'].to_s
  dir = req['dir'].to_s
  if !dir.empty? && File.directory?(dir)
    Dir.chdir(dir)
    $LOAD_PATH.unshift(dir) unless $LOAD_PATH.include?(dir)
  end
  @bundler_error = activate_bundler(dir.empty? ? Dir.pwd : dir)
  shim_require_relative(dir.empty? ? Dir.pwd : dir)
end

.eval_context(code) ⇒ Object

Evaluate everything before the cursor. If it doesn't parse (the user is mid-edit inside a def/do block), fall back to the largest prefix of lines that does parse — partial context beats no context.



158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/ruby_test_ide/runner.rb', line 158

def eval_context(code)
  bind = fresh_binding
  error = nil
  code = largest_valid_prefix(code)
  unless code.strip.empty?
    begin
      bind.eval(code, sandbox_path)
    rescue Exception => e # rubocop:disable Lint/RescueException
      error = describe_error(e) # keep partial state assigned before raise
    end
  end
  [bind, error]
end

.fresh_bindingObject

A binding that behaves like the top of a plain ruby script: self is main, and — unlike TOPLEVEL_BINDING — a method-body binding cannot leak the runner's own local variables into completions.



151
152
153
# File 'lib/ruby_test_ide/runner.rb', line 151

def fresh_binding
  TOPLEVEL_BINDING.receiver.__send__(:__ruby_ide_sandbox__)
end

.handle(req) ⇒ Object



72
73
74
75
76
77
78
79
80
# File 'lib/ruby_test_ide/runner.rb', line 72

def handle(req)
  enter_workspace(req)
  case req['op']
  when 'complete' then complete(req)
  when 'hover'    then hover(req)
  when 'run'      then run(req)
  else { 'error' => "unknown op #{req['op'].inspect}" }
  end
end

.hover(req) ⇒ Object

------------------------------------------------------------------ hover



278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/ruby_test_ide/runner.rb', line 278

def hover(req)
  bind, error = eval_context(req['code_before'])
  receiver = req['receiver'].to_s
  name = req['name'].to_s
  res = hover_info(bind, receiver, name)
  observed = observed_for(name)
  if res
    res['observed'] = observed if observed && res['kind'] == 'method'
  elsif observed
    # Not resolvable from live objects (unreached path) — build the hover
    # entirely from what the tests saw.
    o = observed.first
    args = (o['args'] || {}).map { |n, classes| "#{n}: #{classes.keys.join(' | ')}" }.join(', ')
    res = { 'kind' => 'method', 'name' => name,
            'signature' => "#{name}(#{args})",
            'owner' => o['owner'],
            'source' => "#{o['file']}:#{o['line']}",
            'observed' => observed }
  end
  res ||= {}
  res['context_error'] = error if error
  res.empty? ? {} : res
end

.hover_info(bind, receiver, name) ⇒ Object



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/ruby_test_ide/runner.rb', line 302

def hover_info(bind, receiver, name)
  if receiver.strip.empty?
    if bind.local_variables.map(&:to_s).include?(name)
      val = bind.local_variable_get(name)
      return { 'kind' => 'variable', 'name' => name, 'class' => class_of(val).to_s,
               'value' => safe_inspect(val) }
    end
    if name.match?(/\A[A-Z]/) && bind.eval("defined?(#{name})") == 'constant'
      val = bind.eval(name, sandbox_path)
      return { 'kind' => val.is_a?(Module) ? 'class' : 'constant', 'name' => name,
               'class' => class_of(val).to_s, 'value' => safe_inspect(val),
               'ancestors' => (val.is_a?(Module) ? val.ancestors.first(8).map(&:to_s) : nil) }.compact
    end
  end

  target =
    begin
      if receiver.strip.empty?
        bind.receiver
      else
        Timeout.timeout(RECEIVER_TIMEOUT) { bind.eval(receiver, sandbox_path) }
      end
    rescue Exception # rubocop:disable Lint/RescueException
      # Receiver unreachable live (network edge, slow call) — fall back
      # to the return class the tests observed for its trailing method.
      klass, via = observed_receiver_class(bind, receiver)
      m = begin
        klass&.instance_method(name)
      rescue StandardError
        nil
      end
      return nil unless m

      return { 'kind' => 'method', 'name' => name,
               'signature' => signature(name, m),
               'arity' => m.arity,
               'owner' => m.owner.to_s,
               'receiver_class' => klass.to_s,
               'via' => via,
               'source' => m.source_location&.join(':') }.compact
    end
  m = safe_method(target, name)
  return nil unless m

  { 'kind' => 'method', 'name' => name,
    'signature' => signature(name, m),
    'arity' => m.arity,
    'owner' => m.owner.to_s,
    'receiver_class' => class_of(target).to_s,
    'source' => m.source_location&.join(':'),
    'doc' => nil }.compact
end

.largest_valid_prefix(code) ⇒ Object



172
173
174
175
176
177
178
179
180
181
# File 'lib/ruby_test_ide/runner.rb', line 172

def largest_valid_prefix(code)
  lines = code.to_s.lines
  until lines.empty?
    candidate = lines.join
    return candidate if valid_syntax?(candidate)

    lines.pop
  end
  ''
end

.load_configObject

.ruby_ide.yaml in the workspace root, e.g. learn: # any commands that execute your code - bundle exec rspec - bundle exec rake test - ruby scripts/exercise.rb timeout: 120 # optional, seconds per command



76
77
78
79
80
81
82
83
84
# File 'lib/ruby_test_ide/server.rb', line 76

def self.load_config
  return {} unless File.file?(CONFIG_FILE)

  require 'yaml'
  config = YAML.safe_load(File.read(CONFIG_FILE))
  config.is_a?(Hash) ? config : {}
rescue StandardError => e
  { 'config_error' => "#{File.basename(CONFIG_FILE)}: #{e.message}" }
end

.mainObject



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
63
64
65
66
67
68
69
70
# File 'lib/ruby_test_ide/runner.rb', line 37

def main
  # Results go out on fd 3 when the server provides it, so user code
  # printing to stdout can never corrupt the JSON protocol. Fallback to
  # stdout (with capture) when run by hand: `echo '{...}' | ruby runner.rb`
  channel = begin
    IO.new(3, 'w')
  rescue StandardError
    nil
  end
  request = JSON.parse($stdin.read)
  captured = nil
  unless channel
    real_stdout = $stdout
    $stdout = StringIO.new
  end
  response =
    begin
      handle(request)
    rescue Exception => e # rubocop:disable Lint/RescueException
      { 'error' => "#{e.class}: #{e.message}"[0, 1000] }
    end
  response['bundler_error'] = @bundler_error if @bundler_error
  unless channel
    captured = $stdout.string
    $stdout = real_stdout
  end
  response['stdout'] = truncate(captured, 20_000) if captured && !captured.empty?
  out = channel || $stdout
  out.puts JSON.generate(response)
  out.flush
  # exit! skips at_exit hooks — minitest/autorun must not re-run the
  # suite after the response has been written.
  Process.exit!(0)
end

.matching_open(text, close_idx) ⇒ Object



320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/ruby_test_ide/server.rb', line 320

def self.matching_open(text, close_idx)
  pairs = { ')' => '(', ']' => '[', '}' => '{' }
  close = text[close_idx]
  open = pairs[close]
  depth = 0
  close_idx.downto(0) do |k|
    depth += 1 if text[k] == close
    depth -= 1 if text[k] == open
    return k if depth.zero?
  end
  nil
end

.merge_observations(files) ⇒ Object

Merge the per-process observation dumps into one map (a suite may spawn several ruby processes; each writes its own file).



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/ruby_test_ide/server.rb', line 141

def self.merge_observations(files)
  merged = {}
  files.each do |f|
    JSON.parse(File.read(f)).each do |key, entry|
      if (existing = merged[key])
        existing['calls'] += entry['calls'].to_i
        entry['args'].each do |name, classes|
          (existing['args'][name] ||= {}).merge!(classes) { |_, mine, _| mine }
        end
        existing['returns'].merge!(entry['returns']) { |_, mine, _| mine }
      else
        merged[key] = entry
      end
    end
  rescue StandardError
    next
  end
  merged
end

.observationsObject

Observations persisted by the server after the last learn run.



356
357
358
359
360
361
362
363
# File 'lib/ruby_test_ide/runner.rb', line 356

def observations
  return @observations if defined?(@observations)

  file = @workspace_root.to_s.empty? ? nil : File.join(@workspace_root, OBS_REL)
  @observations = file && File.file?(file) ? JSON.parse(File.read(file)) : nil
rescue StandardError
  @observations = nil
end

.observed_for(name) ⇒ Object



365
366
367
368
369
370
# File 'lib/ruby_test_ide/runner.rb', line 365

def observed_for(name)
  return nil unless observations

  list = observations.values.select { |o| o['method'] == name.to_s }
  list.empty? ? nil : list.first(5)
end

.observed_receiver_class(bind, receiver) ⇒ Object

The class tests observed the receiver's trailing method returning, or nil. [Class, "Weather#summary → String (observed in unit tests)"]



379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# File 'lib/ruby_test_ide/runner.rb', line 379

def observed_receiver_class(bind, receiver)
  name = trailing_call_name(receiver)
  entries = name && observed_for(name)
  return nil unless entries

  ret = entries.flat_map { |o| o['returns'].keys }.tally.max_by { |_, count| count }&.first
  klass = begin
    ret && bind.eval(ret)
  rescue Exception # rubocop:disable Lint/RescueException
    nil
  end
  return nil unless klass.is_a?(Module)

  [klass, "#{entries.first['owner']}##{name}#{ret} (observed in unit tests)"]
end

.oracle_complete(bind, receiver, prefix) ⇒ Object

Completion fallback when the receiver can't be evaluated (mocked network, unreached code path): if tests observed the trailing method of the receiver expression, complete on its most-seen return class.



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/ruby_test_ide/runner.rb', line 398

def oracle_complete(bind, receiver, prefix)
  klass, via = observed_receiver_class(bind, receiver)
  return nil unless klass

  ancestors = klass.ancestors
  names = klass.instance_methods.map(&:to_s)
  names.select! { |n| n.start_with?(prefix) } unless prefix.empty?
  items = names.sort.first(MAX_ITEMS).map do |n|
    item = { 'name' => n, 'kind' => 'method' }
    m = begin
      klass.instance_method(n)
    rescue StandardError
      nil
    end
    if m
      item['signature'] = signature(n, m)
      item['owner'] = m.owner.to_s
      item['sort'] = ancestors.index(m.owner) || 98
    end
    item
  end
  { 'items' => items, 'receiver_class' => klass.to_s, 'oracle' => true,
    'oracle_source' => via }
end

.parse_syntax_error(message) ⇒ Object



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/ruby_test_ide/server.rb', line 352

def self.parse_syntax_error(message)
  diagnostics = []
  current_line = nil
  message.split("\n").each do |line|
    if (m = line.match(/\A>\s*(\d+)\s*\|/)) # prism: marked source line
      current_line = m[1].to_i
    elsif current_line && (m = line.match(/\A\s*\|\s*\^+\s*(.+)/)) # prism: caret detail
      diagnostics << { 'line' => current_line, 'message' => m[1],
                       'severity' => 'error', 'source' => 'syntax' }
    elsif (m = line.match(/\A\(buffer\):(\d+):\s*(.+)/)) # parse.y, or prism header
      diagnostics << { 'line' => m[1].to_i, 'message' => m[2],
                       'severity' => 'error', 'source' => 'syntax' }
    end
  end
  # prefer prism's detailed caret messages over its generic header line
  detailed = diagnostics.reject { |d| d['message'].start_with?('syntax error') && diagnostics.size > 1 }
  detailed.empty? ? diagnostics : detailed
end

.receiver_items(obj, prefix) ⇒ Object



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/ruby_test_ide/runner.rb', line 225

def receiver_items(obj, prefix)
  klass = class_of(obj)
  ancestors = klass.ancestors
  names = obj.methods.map(&:to_s).uniq
  names.select! { |n| n.start_with?(prefix) } unless prefix.empty?
  names.sort.first(MAX_ITEMS).map do |n|
    item = { 'name' => n, 'kind' => 'method' }
    if (m = safe_method(obj, n))
      item['signature'] = signature(n, m)
      item['arity'] = m.arity
      item['owner'] = m.owner.to_s
      item['sort'] = ancestors.index(m.owner) || 98
    end
    item
  end
end

.receiver_start(text, pos) ⇒ Object

Scan backwards from the trailing '.' to find where the receiver expression starts, honouring balanced brackets and string literals.



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/ruby_test_ide/server.rb', line 289

def self.receiver_start(text, pos)
  i = pos
  while i.positive?
    c = text[i - 1]
    case c
    when /[A-Za-z0-9_?!@$]/
      i -= 1
    when ')', ']', '}'
      open = matching_open(text, i - 1)
      return i unless open

      i = open
    when '"', "'"
      k = i - 2
      k -= 1 while k >= 0 && !(text[k] == c && (k.zero? || text[k - 1] != '\\'))
      return i if k.negative?

      i = k
    when '.'
      return i if i >= 2 && text[i - 2] == '.' # don't cross a range operator

      i -= 1
    when ':'
      i -= 1
    else
      return i
    end
  end
  0
end

.run(req) ⇒ Object

Execute the whole buffer under a TracePoint, capturing local-variable state per line — the "as if you were sitting in a debugger" view.



427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
# File 'lib/ruby_test_ide/runner.rb', line 427

def run(req)
  code = req['code'].to_s
  bind = fresh_binding
  line_states = {}
  prev_line = nil
  events = 0

  tp = TracePoint.new(:line) do |t|
    next unless t.path == sandbox_path

    events += 1
    next if events > MAX_TRACE_EVENTS

    # A :line event fires *before* its line runs, so its state describes
    # the world *after* the previously-seen line.
    line_states[prev_line] = capture_locals(t.binding) if prev_line
    prev_line = t.lineno
  end

  error = nil
  begin
    tp.enable { bind.eval(code, sandbox_path) }
  rescue Exception => e # rubocop:disable Lint/RescueException
    error = describe_error(e)
  ensure
    tp.disable
  end
  line_states[prev_line] = capture_locals(bind) if prev_line

  { 'line_states' => line_states,
    'final_locals' => capture_locals(bind),
    'error' => error,
    'truncated' => events > MAX_TRACE_EVENTS || nil }.compact
end

.run_learn_command(cmd, obs_dir, timeout) ⇒ Object

Run one learn command with the observer preloaded into every ruby process it starts. Output is captured; the process group is killed on timeout, exactly like eval workers.



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/ruby_test_ide/server.rb', line 100

def self.run_learn_command(cmd, obs_dir, timeout)
  out_r, out_w = IO.pipe
  env = {
    'RUBYOPT' => [ENV['RUBYOPT'], "-r#{OBSERVER}"].compact.reject(&:empty?).join(' '),
    'RUBY_IDE_OBS_DIR' => obs_dir,
    'RUBY_IDE_OBS_ROOT' => WORKSPACE,
  }
  pid = spawn(env, cmd.to_s, chdir: WORKSPACE,
              in: File::NULL, out: out_w, err: out_w, pgroup: true)
  out_w.close
  out_thread = Thread.new { out_r.read }
  status, killed = wait_or_kill(pid, timeout)
  output = out_thread.value
  out_r.close
  { 'command' => cmd, 'exit' => status&.exitstatus, 'ok' => !killed && status&.success? == true,
    'timeout' => killed || nil, 'output' => output.to_s[-4000..] || output.to_s }.compact
rescue StandardError => e
  { 'command' => cmd, 'ok' => false, 'output' => "#{e.class}: #{e.message}" }
end

.run_worker(payload, timeout: RUNNER_TIMEOUT) ⇒ Object

Spawn lib/runner.rb, hand it one JSON request on stdin, read the JSON reply from fd 3 (so user code writing to stdout can't corrupt it), and kill the whole process group if it blows the time budget.



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/ruby_test_ide/server.rb', line 223

def self.run_worker(payload, timeout: RUNNER_TIMEOUT)
  stdin_r, stdin_w = IO.pipe
  out_r, out_w = IO.pipe
  result_r, result_w = IO.pipe
  pid = spawn(RbConfig.ruby, '--disable-gems', RUNNER,
              in: stdin_r, out: out_w, err: out_w, 3 => result_w,
              pgroup: true, rlimit_cpu: timeout * 2)
  stdin_r.close
  out_w.close
  result_w.close
  stdin_w.write(JSON.generate(payload))
  stdin_w.close

  out_thread = Thread.new { out_r.read }
  result_thread = Thread.new { result_r.read }

  _status, killed = wait_or_kill(pid, timeout)

  user_output = out_thread.value
  raw = result_thread.value
  out_r.close
  result_r.close

  if killed
    return { 'error' => "evaluation timed out after #{timeout}s (infinite loop?)",
             'timeout' => true, 'stdout' => user_output }
  end

  response = begin
    JSON.parse(raw)
  rescue StandardError
    { 'error' => "runner crashed: #{user_output.to_s[0, 500]}" }
  end
  response['stdout'] = user_output[0, 20_000] unless user_output.to_s.empty?
  response
end

.safe_inspect(val) ⇒ Object



514
515
516
517
518
# File 'lib/ruby_test_ide/runner.rb', line 514

def safe_inspect(val)
  truncate(val.inspect, 140)
rescue Exception # rubocop:disable Lint/RescueException
  "#<#{class_of(val)} (uninspectable)>"
end

.safe_method(obj, name) ⇒ Object

---------------------------------------------------------------- helpers



473
474
475
476
477
478
479
480
481
# File 'lib/ruby_test_ide/runner.rb', line 473

def safe_method(obj, name)
  obj.method(name)
rescue Exception # rubocop:disable Lint/RescueException
  begin
    class_of(obj).instance_method(name)
  rescue Exception # rubocop:disable Lint/RescueException
    nil
  end
end

.sandbox_pathObject



142
143
144
# File 'lib/ruby_test_ide/runner.rb', line 142

def sandbox_path
  @sandbox_path || SANDBOX_PATH
end

.seed_workspaceObject



184
185
186
187
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
# File 'lib/ruby_test_ide/server.rb', line 184

def self.seed_workspace
  require 'fileutils'
  FileUtils.mkdir_p(WORKSPACE)
  return unless Dir.empty?(WORKSPACE)

  FileUtils.mkdir_p(File.join(WORKSPACE, 'lib'))
  File.write(File.join(WORKSPACE, 'main.rb'), <<~RUBY)
    # Files here are real: open them from the sidebar, edit, save with Cmd+S.
    # require_relative works — and so does reflection ACROSS files:
    # type  greeter.  below and methods from lib/greeter.rb appear.

    require_relative 'lib/greeter'

    greeter = Greeter.new('Sam')
    message = greeter.greet
    puts message
  RUBY
  File.write(File.join(WORKSPACE, 'lib', 'greeter.rb'), <<~RUBY)
    # Edit this class, save, and completions in main.rb update on the
    # next keystroke — the runtime is the single source of truth.
    class Greeter
      attr_reader :name

      def initialize(name)
        @name = name
      end

      def greet(punctuation = '!')
        "Hello, \#{name}\#{punctuation}"
      end
    end
  RUBY
end

.shim_require_relative(base) ⇒ Object

require_relative raises "cannot infer basepath" inside eval'd code. Resolve against the calling file's real directory when there is one (files loaded via require keep normal semantics), otherwise against the buffer's directory.



134
135
136
137
138
139
140
# File 'lib/ruby_test_ide/runner.rb', line 134

def shim_require_relative(base)
  Object.__send__(:define_method, :require_relative) do |rel|
    from = caller_locations(1, 1)&.first&.absolute_path
    require(File.expand_path(rel.to_s, from ? File.dirname(from) : base))
  end
  Object.__send__(:private, :require_relative)
end

.signature(name, method) ⇒ Object

"gsub(pattern, replacement = …, &block)" from Method#parameters. C-implemented methods often report anonymous params — synthesise names.



489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/ruby_test_ide/runner.rb', line 489

def signature(name, method)
  params = method.parameters
  counter = 0
  parts = params.map do |type, pname|
    counter += 1
    n = pname || "arg#{counter}"
    case type
    when :req    then n.to_s
    when :opt    then "#{n} = …"
    when :rest   then "*#{pname || 'args'}"
    when :keyreq then "#{n}:"
    when :key    then "#{n}: …"
    when :keyrest then "**#{pname || 'opts'}"
    when :block  then "&#{pname || 'block'}"
    when :nokey  then '**nil'
    end
  end.compact
  if parts.empty? && method.arity != 0
    n = method.arity.abs - (method.arity.negative? ? 1 : 0)
    parts = (1..n).map { |i| "arg#{i}" }
    parts << '*args' if method.arity.negative?
  end
  parts.empty? ? name.to_s : "#{name}(#{parts.join(', ')})"
end

.split_target(text) ⇒ Object

Split "everything on the line before the cursor" into [receiver, prefix]:

"t.st"            -> ["t",        "st"]
"x = 'foo'.up"    -> ["'foo'",    "up"]
"arr[0].e"        -> ["arr[0]",   "e"]
"t.strip.rev"     -> ["t.strip",  "rev"]
"pu"              -> [nil,        "pu"]


268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/ruby_test_ide/server.rb', line 268

def self.split_target(text)
  i = text.length
  j = i
  j -= 1 while j.positive? && text[j - 1].match?(/[A-Za-z0-9_]/)
  prefix = text[j...i]

  if j.positive? && text[j - 1] == '.' && !(j > 1 && text[j - 2] == '.')
    recv_end = j - 1
    recv_start = receiver_start(text, recv_end)
    return [nil, prefix] if recv_start >= recv_end

    [text[recv_start...recv_end], prefix]
  else
    # pull sigils (@, @@, $) into the prefix for ivar/gvar completion
    j -= 1 while j.positive? && text[j - 1].match?(/[@$]/)
    [nil, text[j...i]]
  end
end

.start(port: 3000) ⇒ Object



720
721
722
723
# File 'lib/ruby_test_ide/server.rb', line 720

def self.start(port: 3000)
  seed_workspace
  Server.new(port).start
end

.syntax_diagnostics(code) ⇒ Object

Compile (never execute) the buffer to catch syntax errors — on 3.2, AbstractSyntaxTree.parse omits line numbers. Two message formats exist:

<= 3.3 (parse.y): "(buffer):3: syntax error, unexpected end-of-input"
>= 3.4 (prism):   "(buffer):3: syntax errors found" followed by a
                source listing with "> 3 | puts 1" markers and
                "    |       ^ expected an `end` ..." caret lines


341
342
343
344
345
346
347
348
349
350
# File 'lib/ruby_test_ide/server.rb', line 341

def self.syntax_diagnostics(code)
  stderr = $stderr
  $stderr = StringIO.new
  RubyVM::InstructionSequence.compile(code, '(buffer)')
  []
rescue SyntaxError => e
  parse_syntax_error(e.message)
ensure
  $stderr = stderr
end

.token_matches?(candidate) ⇒ Boolean

Constant-time compare — cheap insurance on localhost, real insurance if this ever ends up reachable from elsewhere (e.g. --workspace over a VPN).

Returns:

  • (Boolean)


42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/ruby_test_ide/server.rb', line 42

def self.token_matches?(candidate)
  return true if AUTH_DISABLED
  return false if candidate.nil? || TOKEN.empty?

  a = candidate.to_s.b
  b = TOKEN.b
  return false unless a.bytesize == b.bytesize

  result = 0
  a.bytes.each_with_index { |byte, i| result |= byte ^ b.getbyte(i) }
  result.zero?
end

.trailing_call_name(expr) ⇒ Object

"w.summary('London')" -> "summary"; "fetch(1)" -> "fetch"



373
374
375
# File 'lib/ruby_test_ide/runner.rb', line 373

def trailing_call_name(expr)
  expr[/(?:\.|\A)\s*([a-zA-Z_]\w*[?!]?)\s*(?:\([^()]*\))?\s*\z/, 1]
end

.truncate(s, len) ⇒ Object



520
521
522
523
# File 'lib/ruby_test_ide/runner.rb', line 520

def truncate(s, len)
  s = s.to_s
  s.length > len ? "#{s[0, len - 1]}" : s
end

.valid_syntax?(code) ⇒ Boolean

Returns:

  • (Boolean)


183
184
185
186
187
188
189
190
191
# File 'lib/ruby_test_ide/runner.rb', line 183

def valid_syntax?(code)
  stderr, $stderr = $stderr, StringIO.new
  RubyVM::AbstractSyntaxTree.parse(code)
  true
rescue SyntaxError
  false
ensure
  $stderr = stderr
end

.wait_or_kill(pid, timeout) ⇒ Object



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/ruby_test_ide/server.rb', line 120

def self.wait_or_kill(pid, timeout)
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
  loop do
    _, status = Process.waitpid2(pid, Process::WNOHANG)
    return [status, false] if status

    if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
      begin
        Process.kill('-KILL', pid)
      rescue StandardError
        nil
      end
      _, status = Process.waitpid2(pid)
      return [status, true]
    end
    sleep 0.01
  end
end

.workspace_filesObject

NB: no Dir.chdir here — the cwd is process-wide and this server is multi-threaded, so relative globbing would race between requests.



174
175
176
177
178
179
180
181
182
# File 'lib/ruby_test_ide/server.rb', line 174

def self.workspace_files
  Dir.glob(File.join(WORKSPACE, '**', '*'))
     .select { |f| File.file?(f) }
     .map { |f| f.delete_prefix("#{WORKSPACE}/") }
     .reject { |f| f.match?(WORKSPACE_IGNORE) }
     .select { |f| f.end_with?('.rb') || RUBY_FILENAMES.include?(File.basename(f)) }
     .sort
     .map { |f| { 'path' => f, 'size' => File.size(File.join(WORKSPACE, f)) } }
end

.workspace_path(rel) ⇒ Object

Files the editor lists / opens / saves all live under WORKSPACE. Every relative path from the browser is resolved and fenced here.

Raises:

  • (ArgumentError)


163
164
165
166
167
168
169
170
# File 'lib/ruby_test_ide/server.rb', line 163

def self.workspace_path(rel)
  raise ArgumentError, 'path required' if rel.to_s.empty?

  abs = File.expand_path(rel.to_s, WORKSPACE)
  raise ArgumentError, 'path escapes workspace' unless abs == WORKSPACE || abs.start_with?("#{WORKSPACE}/")

  abs
end