mutineer 1.8.1 → 1.9.0

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.
Files changed (52) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +733 -0
  3. data/README.md +85 -50
  4. data/lib/mutineer/changed_lines.rb +2 -1
  5. data/lib/mutineer/child_cause.rb +149 -0
  6. data/lib/mutineer/child_stdout.rb +12 -1
  7. data/lib/mutineer/cli.rb +540 -59
  8. data/lib/mutineer/command_redact.rb +38 -0
  9. data/lib/mutineer/concern_blocks.rb +95 -24
  10. data/lib/mutineer/config.rb +112 -6
  11. data/lib/mutineer/coverage_map.rb +1345 -156
  12. data/lib/mutineer/daemon_backend.rb +41 -18
  13. data/lib/mutineer/daemon_client.rb +104 -21
  14. data/lib/mutineer/daemon_server.rb +85 -14
  15. data/lib/mutineer/database_urls.rb +189 -0
  16. data/lib/mutineer/external_backend.rb +93 -6
  17. data/lib/mutineer/fs_path.rb +125 -0
  18. data/lib/mutineer/isolation.rb +380 -25
  19. data/lib/mutineer/job_plan.rb +352 -41
  20. data/lib/mutineer/minitest_integration/file_order.rb +56 -0
  21. data/lib/mutineer/minitest_integration/in_test_database_error.rb +243 -19
  22. data/lib/mutineer/minitest_integration.rb +26 -58
  23. data/lib/mutineer/mutant_id.rb +4 -1
  24. data/lib/mutineer/mutation.rb +10 -4
  25. data/lib/mutineer/mutator_registry.rb +6 -3
  26. data/lib/mutineer/mutators/collection_method.rb +195 -6
  27. data/lib/mutineer/mutators/literal_mutation.rb +33 -3
  28. data/lib/mutineer/mutators/range_literal.rb +78 -29
  29. data/lib/mutineer/mutators/rescue_body.rb +126 -0
  30. data/lib/mutineer/mutators/return_nil.rb +23 -6
  31. data/lib/mutineer/output_filter.rb +451 -0
  32. data/lib/mutineer/pairing.rb +463 -31
  33. data/lib/mutineer/parser.rb +53 -0
  34. data/lib/mutineer/project_path.rb +15 -8
  35. data/lib/mutineer/rails_worker_db.rb +366 -6
  36. data/lib/mutineer/reach_probe.rb +229 -0
  37. data/lib/mutineer/redaction.rb +301 -41
  38. data/lib/mutineer/reload_guards.rb +985 -0
  39. data/lib/mutineer/reporter.rb +467 -58
  40. data/lib/mutineer/result.rb +6 -7
  41. data/lib/mutineer/run_seed.rb +16 -0
  42. data/lib/mutineer/runner.rb +194 -55
  43. data/lib/mutineer/source_bytes.rb +187 -0
  44. data/lib/mutineer/statement_lines.rb +108 -14
  45. data/lib/mutineer/test_runners/rspec.rb +118 -10
  46. data/lib/mutineer/test_runners/rspec_seed.rb +151 -0
  47. data/lib/mutineer/test_runners.rb +3 -2
  48. data/lib/mutineer/triage.rb +55 -10
  49. data/lib/mutineer/version.rb +1 -1
  50. data/lib/mutineer.rb +1 -0
  51. data/skills/mutineer/SKILL.md +12 -4
  52. metadata +13 -1
@@ -3,11 +3,14 @@
3
3
  require "tempfile"
4
4
  require_relative "result"
5
5
  require_relative "parser"
6
+ require_relative "source_bytes"
6
7
  require_relative "child_stdout"
7
8
  require_relative "child_coverage"
8
9
  require_relative "kill_channel"
9
10
  require_relative "concern_blocks"
10
11
  require_relative "redaction"
12
+ require_relative "child_cause"
13
+ require_relative "reach_probe"
11
14
 
12
15
  module Mutineer
13
16
  # Fork-based isolation for running one mutant. The block runs in a child
@@ -30,9 +33,15 @@ module Mutineer
30
33
  # Seconds between the parent's checks on a running child.
31
34
  POLL_INTERVAL = 0.005
32
35
 
36
+ # Byte scan for a path anchor. A snippet without one skips the parse that
37
+ # {anchor_paths} would do (#339). `send(:__dir__)` and
38
+ # `send(:require_relative)` contain the same tokens.
39
+ ANCHOR_PATTERN = /__dir__|__FILE__|require_relative/
40
+
33
41
  # Runs the block in a forked child. The block's return value (an Integer
34
42
  # exit code) or any explicit `exit` is honoured; an unhandled exception
35
- # becomes exit 2 with the cause written to STDERR.
43
+ # becomes exit 2 with the cause written to STDERR. The cause also reaches
44
+ # the Result's `details` through a {ChildCause} pipe.
36
45
  #
37
46
  # The child silences its stdout (see {ChildStdout.silence}) before the
38
47
  # block runs, so test output never reaches the user. Stderr stays open.
@@ -51,8 +60,13 @@ module Mutineer
51
60
  def self.run(timeout: DEFAULT_TIMEOUT, channel: false)
52
61
  rd, wr = IO.pipe if channel
53
62
  wr&.sync = true
63
+ cause_rd, cause_wr = IO.pipe
64
+ cause_wr.sync = true
54
65
  pid = fork do
66
+ child = Process.pid
55
67
  rd&.close
68
+ cause_rd.close
69
+ ChildCause.arm!(cause_wr, child)
56
70
  # Own process group so a timeout kill can reap grandchildren (match
57
71
  # daemon/external backends). Best-effort: if setpgid fails, kill the pid.
58
72
  Process.setpgid(0, 0) rescue nil # rubocop:disable Style/RescueModifier
@@ -68,7 +82,10 @@ module Mutineer
68
82
  rescue Exception => e # rubocop:disable Lint/RescueException
69
83
  # STDERR, not `warn`: a test may have left `$stderr` as a StringIO.
70
84
  STDERR.puts "[mutineer-child] #{Redaction.describe(e)}"
85
+ ChildCause.write(cause_wr, e, child)
71
86
  code = 2
87
+ ensure
88
+ ChildCause.disarm!
72
89
  end
73
90
  STDERR.flush
74
91
  # exit! skips at_exit handlers — critical, since a child forked from
@@ -78,6 +95,7 @@ module Mutineer
78
95
  end
79
96
 
80
97
  wr&.close
98
+ cause_wr.close
81
99
  buffer = +"" if rd
82
100
  reading = !rd.nil?
83
101
 
@@ -87,7 +105,7 @@ module Mutineer
87
105
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
88
106
  loop do
89
107
  reaped, status = Process.waitpid2(pid, Process::WNOHANG)
90
- return finish(decode(status), rd, buffer, finished: true) if reaped
108
+ return finish(decode(status, ChildCause.read(cause_rd)), rd, buffer, finished: true) if reaped
91
109
 
92
110
  if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
93
111
  begin
@@ -98,7 +116,7 @@ module Mutineer
98
116
  begin
99
117
  _reaped, status = Process.waitpid2(pid)
100
118
  # Child may have finished cleanly between WNOHANG and kill; honor it.
101
- return finish(decode(status), rd, buffer, finished: true) if status && status.exited? && !status.signaled?
119
+ return finish(decode(status, ChildCause.read(cause_rd)), rd, buffer, finished: true) if status && status.exited? && !status.signaled?
102
120
  rescue Errno::ECHILD
103
121
  # already reaped
104
122
  end
@@ -113,8 +131,10 @@ module Mutineer
113
131
  end
114
132
  ensure
115
133
  rd&.close
134
+ cause_rd&.close
116
135
  # Closed after the fork in the normal path; still open if fork raised.
117
136
  wr.close if wr && !wr.closed?
137
+ cause_wr.close if cause_wr && !cause_wr.closed?
118
138
  end
119
139
 
120
140
  # Reads what the channel holds now, without blocking.
@@ -169,7 +189,11 @@ module Mutineer
169
189
  return result.with(kills: Kills.new(killed_by: [], ran: [], complete: false)) if report.invalid
170
190
 
171
191
  result = Result.killed if report.started && report.serial_kill && report.skipping.positive?
172
- result = Result.error if report.started && report.serial_error && report.skipping.positive?
192
+ # Early end after a serial DB error: the child never reached the naming
193
+ # code that would write the exception class (#417 / KTD5).
194
+ if report.started && report.serial_error && report.skipping.positive?
195
+ result = Result.error(ChildCause::MATRIX_EARLY_END)
196
+ end
173
197
  agrees = result.killed? ? report.killed.any? : result.survived? && report.killed.empty?
174
198
  complete = finished && report.started && report.finished && report.lost.zero? && agrees
175
199
  result.with(kills: Kills.new(killed_by: report.killed, ran: report.ran, complete: complete))
@@ -193,8 +217,8 @@ module Mutineer
193
217
  # A concern's stored `included` and `prepended` blocks from the source file
194
218
  # are forgotten around the load, so ActiveSupport accepts the blocks the
195
219
  # temp file stores (#256). For a def in such a block, the caller passes the
196
- # text from {JobPlan.hook_mutant} and then calls
197
- # {ConcernBlocks.place_hook_def} (#297).
220
+ # text and `hook_def` from {JobPlan.hook_mutant}, and the load places the
221
+ # mutated def (#297, #348).
198
222
  #
199
223
  # {ConcernBlocks.load_mutant} turns Ruby's warnings off for the load, so
200
224
  # the constants it assigns again do not warn (#364).
@@ -202,9 +226,10 @@ module Mutineer
202
226
  # @api private
203
227
  # @param mutated [String] mutated source text.
204
228
  # @param source_file [String] original source file path.
229
+ # @param hook_def [Hash{Symbol => Object}, nil] see {ConcernBlocks.load_mutant}.
205
230
  # @return [Object] whatever `load` returns.
206
- def self.apply_whole_file(mutated, source_file)
207
- write_beside(mutated, source_file) { |path| ConcernBlocks.load_mutant(source_file, path) }
231
+ def self.apply_whole_file(mutated, source_file, hook_def: nil)
232
+ write_beside(mutated, source_file) { |path| ConcernBlocks.load_mutant(source_file, path, hook_def: hook_def) }
208
233
  end
209
234
 
210
235
  # Writes `code` to a hidden `.mutineer_mutant` file beside `source_file`,
@@ -229,7 +254,12 @@ module Mutineer
229
254
  dir = Dir.tmpdir if fallback && !File.writable?(dir)
230
255
  Tempfile.create([".mutineer_mutant", ".rb"], dir) do |f|
231
256
  f.flock(File::LOCK_EX) rescue nil # rubocop:disable Style/RescueModifier
232
- f.write(code)
257
+ # Binary: a text write would follow the locale and could change
258
+ # the bytes. SourceBytes encodes the text to the encoding its
259
+ # magic comment names, and adds one when a redefine snippet has
260
+ # none (#346).
261
+ f.binmode
262
+ f.write(SourceBytes.for_file(code))
233
263
  f.flush
234
264
  yield f.path
235
265
  end
@@ -248,8 +278,12 @@ module Mutineer
248
278
  # @param mutation [Mutineer::Mutation] mutation to apply.
249
279
  # @param subject [Mutineer::Subject] subject being mutated.
250
280
  # @param source [String] full source text.
281
+ # @param reach_path [String, nil] sentinel for a `:maybe` mutant (#345).
282
+ # The loaded def records a run of the mutated expression. Nil leaves
283
+ # the def as the mutation alone.
284
+ # @param reach_key [String, nil] fiber-local key for `reach_path`.
251
285
  # @return [Object] whatever `load` returns.
252
- def self.apply_surgical(mutation, subject, source)
286
+ def self.apply_surgical(mutation, subject, source, reach_path: nil, reach_key: nil)
253
287
  # Rebuild the FULL namespace nesting textually so unqualified enclosing-
254
288
  # namespace constants resolve exactly as the reload strategy would. A
255
289
  # bare redefinition on the owner would collapse Module.nesting to [owner]
@@ -265,7 +299,7 @@ module Mutineer
265
299
  # falsely survives. Re-open the singleton class so the redefinition lands on
266
300
  # the same method the test calls. `def self.foo` already carries its
267
301
  # receiver, so it is left as-is (wrapping it would mis-target).
268
- inner = mutated_def(mutation, subject, source)
302
+ inner = mutated_def(mutation, subject, source, reach_path: reach_path, reach_key: reach_key)
269
303
  inner = "#{subject.block_owner}.class_eval do\n#{inner}\nend" if subject.block_owner
270
304
  wrapped = "#{prefix}#{inner}#{"\nend" * keywords.size}"
271
305
 
@@ -273,7 +307,7 @@ module Mutineer
273
307
  # running the ORIGINAL method (C2 false-survived). Raise -> the fork
274
308
  # block aborts before any test runs -> Result.error, never a bogus
275
309
  # `survived`.
276
- raise "surgical snippet failed to reparse" if Parser.parse_string(wrapped).errors.any?
310
+ raise "surgical snippet failed to reparse" if Parser.invalid?(wrapped)
277
311
 
278
312
  # Preserve original visibility — class/module bodies define methods
279
313
  # public, but 7a's `load` would re-apply the file's private/protected
@@ -288,20 +322,136 @@ module Mutineer
288
322
  # scanners to flag. The input is the project's OWN source (the enclosing
289
323
  # method, textually mutated), loaded only in this forked child.
290
324
  #
291
- # The file sits beside the source, as in apply_whole_file, so `__dir__`
292
- # and `require_relative` in the method resolve against its real
293
- # neighbours (#279). In the temp dir they raise ENOENT or LoadError, and
294
- # every mutant of the method dies whatever it changes. The hidden
295
- # `.mutineer_mutant` name keeps Zeitwerk away (#253) and lets the parent
296
- # sweep an orphan after a timeout kill.
297
- #
298
- # A read-only source dir keeps the 1.x system-temp location, so redefine
299
- # still runs there (only path-relative methods mis-score, as before: #339).
300
- write_beside(wrapped, subject.file, fallback: true) { |path| load path }
325
+ # The file sits beside the source, as in apply_whole_file (#279). A
326
+ # read-only source directory keeps the 1.x system-temp location, so
327
+ # redefine still runs there. Either file is a different path from the
328
+ # source, so {anchor_paths} rewrites `__FILE__`, `__dir__`, and
329
+ # `require_relative` to the original file before the load. Without that,
330
+ # a temp-dir load raises ENOENT or LoadError and every mutant of the
331
+ # method scores `killed` (#339). The hidden `.mutineer_mutant` name
332
+ # keeps Zeitwerk away (#253) and lets the parent sweep an orphan after a
333
+ # timeout kill.
334
+ anchored = anchor_paths(wrapped, subject)
335
+ # The anchored text is what `load` runs. A rewrite that does not reparse
336
+ # must take the same error path as the unanchored snippet above.
337
+ raise "surgical snippet failed to reparse" if anchored != wrapped && Parser.invalid?(anchored)
338
+
339
+ write_beside(anchored, subject.file, fallback: true) { |path| load path }
301
340
 
302
341
  target.send(vis, subject.name) if vis && vis != :public
303
342
  end
304
343
 
344
+ # Rewrites path anchors in a redefine snippet so they resolve against the
345
+ # original source file when `load` runs a different file (#339).
346
+ #
347
+ # The hidden snippet is never the source file. Beside the source, `__dir__`
348
+ # still names that directory, but `__FILE__` names the hidden file, and a
349
+ # symlinked source makes `__dir__` and `require_relative` follow the link's
350
+ # directory. In the system temp directory every one of them follows the
351
+ # temp directory, so each mutant raises and scores `killed`. The rewrite
352
+ # uses the live method's `source_location` when that file is `subject.file`,
353
+ # so a symlink keeps the path the program loaded. `__dir__` and
354
+ # `require_relative` use `File.realpath`, as Ruby does.
355
+ #
356
+ # Calls with an implicit receiver, literal `self`, or `Kernel` / `::Kernel`
357
+ # are rewritten, including `send` and `__send__` whose name is a literal.
358
+ # A call on any other receiver is left alone: `other.__dir__` is a private
359
+ # call and raises.
360
+ #
361
+ # @api private
362
+ # @param code [String] the wrapped snippet.
363
+ # @param subject [Mutineer::Subject] the method being redefined.
364
+ # @return [String] `code`, or a copy with the anchors rewritten.
365
+ def self.anchor_paths(code, subject)
366
+ return code unless code.match?(ANCHOR_PATTERN)
367
+
368
+ file_path = anchor_file(subject)
369
+ dir_literal = anchor_directory(file_path).dump
370
+ PathAnchor.rewrite(code, file_path.dump, dir_literal, bare_kernel: bare_kernel_builtin?(subject))
371
+ end
372
+
373
+ # Whether a bare `Kernel` in `subject` is `::Kernel`. A class or enclosing
374
+ # module that defines its own `Kernel` must keep that constant: rewriting
375
+ # `Kernel.__dir__` would turn a `NoMethodError` into a path.
376
+ #
377
+ # @api private
378
+ # @param subject [Mutineer::Subject] the method being redefined.
379
+ # @return [Boolean]
380
+ def self.bare_kernel_builtin?(subject)
381
+ cursor = Object
382
+ modules = subject.lexical_namespace.map do |element|
383
+ cursor = element.start_with?("::") ? Object.const_get(element.delete_prefix("::")) : cursor.const_get(element)
384
+ end
385
+ lookup = []
386
+ modules.reverse_each { |mod| mod.ancestors.each { |ancestor| lookup << ancestor if ancestor.is_a?(Module) } }
387
+ lookup.each do |candidate|
388
+ next unless candidate.const_defined?(:Kernel, false)
389
+
390
+ return candidate.const_get(:Kernel, false).equal?(::Kernel)
391
+ end
392
+ true
393
+ rescue NameError
394
+ false
395
+ end
396
+
397
+ # The path `__FILE__` must return for `subject`. The live method's
398
+ # `source_location` wins when it is the same file, because that string is
399
+ # the one the unmutated method returns (a symlink path stays a symlink
400
+ # path). Otherwise the expanded subject path.
401
+ #
402
+ # @api private
403
+ # @param subject [Mutineer::Subject] the method being redefined.
404
+ # @return [String] absolute path.
405
+ def self.anchor_file(subject)
406
+ defined_in = defined_path(subject)
407
+ return defined_in if defined_in && same_file?(defined_in, subject.file)
408
+
409
+ File.expand_path(subject.file)
410
+ end
411
+
412
+ # The directory `__dir__` and `require_relative` use for `file_path`:
413
+ # `File.dirname(File.realpath(file_path))`. A subject path that is not a
414
+ # file yet (a unit probe) uses the real directory that contains it.
415
+ #
416
+ # @api private
417
+ # @param file_path [String] the path {anchor_file} chose.
418
+ # @return [String] absolute real directory.
419
+ def self.anchor_directory(file_path)
420
+ File.dirname(File.realpath(file_path))
421
+ rescue SystemCallError
422
+ File.realpath(File.dirname(File.expand_path(file_path)))
423
+ end
424
+
425
+ # The file the live method was defined in, when that method is `subject`'s
426
+ # own. An inherited method, or a method that is not defined yet, returns nil
427
+ # so {anchor_file} uses the subject path.
428
+ #
429
+ # @api private
430
+ # @param subject [Mutineer::Subject] the method being redefined.
431
+ # @return [String, nil] `source_location` path, or nil.
432
+ def self.defined_path(subject)
433
+ target = subject.namespace.empty? ? Object : Object.const_get(subject.namespace.join("::"))
434
+ target = target.singleton_class if subject.singleton
435
+ method = target.instance_method(subject.name)
436
+ return unless method.owner == target
437
+
438
+ method.source_location&.first
439
+ rescue NameError
440
+ nil
441
+ end
442
+
443
+ # Whether `left` and `right` are the same file after resolving symlinks.
444
+ #
445
+ # @api private
446
+ # @param left [String] a path.
447
+ # @param right [String] a path.
448
+ # @return [Boolean]
449
+ def self.same_file?(left, right)
450
+ File.realpath(left) == File.realpath(right)
451
+ rescue SystemCallError
452
+ false
453
+ end
454
+
305
455
  # The enclosing def with the mutation applied, wrapped in `class << self`
306
456
  # for a singleton def with no receiver (#20). Pure text: it reads no live
307
457
  # module, so the tool process can call it too ({JobPlan.hook_mutant}).
@@ -310,14 +460,20 @@ module Mutineer
310
460
  # @param mutation [Mutineer::Mutation] mutation to apply.
311
461
  # @param subject [Mutineer::Subject] subject being mutated.
312
462
  # @param source [String] full source text.
463
+ # @param reach_path [String, nil] see {apply_surgical}.
464
+ # @param reach_key [String, nil] see {apply_surgical}.
313
465
  # @return [String] the mutated def.
314
- def self.mutated_def(mutation, subject, source)
466
+ def self.mutated_def(mutation, subject, source, reach_path: nil, reach_key: nil)
315
467
  loc = subject.def_node.location
316
468
  def_start = loc.start_offset
317
469
  snippet = source.byteslice(def_start...loc.end_offset)
318
470
  rel_s = mutation.start_offset - def_start
319
471
  rel_e = mutation.end_offset - def_start
320
472
  mutated = snippet.byteslice(0...rel_s) + mutation.replacement + snippet.byteslice(rel_e..)
473
+ if reach_path && rel_s >= 0 && rel_s + mutation.replacement.bytesize <= mutated.bytesize
474
+ probed = ReachProbe.wrap(mutated, rel_s, rel_s + mutation.replacement.bytesize, reach_path, reach_key)
475
+ mutated = probed if probed
476
+ end
321
477
  subject.singleton && subject.def_node.receiver.nil? ? "class << self\n#{mutated}\nend" : mutated
322
478
  end
323
479
 
@@ -365,14 +521,213 @@ module Mutineer
365
521
  #
366
522
  # @api private
367
523
  # @param status [Process::Status] child exit status.
524
+ # @param cause [String, nil] the {ChildCause} line the child sent, if any.
368
525
  # @return [Mutineer::Result] decoded result.
369
- def self.decode(status)
526
+ def self.decode(status, cause = nil)
370
527
  case status.exitstatus
371
528
  when 0 then Result.survived
372
529
  when 1 then Result.killed
373
- when 2 then Result.error("child exited with status 2")
530
+ when 2 then Result.error(cause || "child exited with status 2")
374
531
  else Result.error("unexpected exit status: #{status.exitstatus.inspect}")
375
532
  end
376
533
  end
534
+
535
+ # Rewrites path anchors in one snippet (#339). A `require_relative` argument
536
+ # is rewritten on its own first, so a nested `__dir__` or `__FILE__` is not
537
+ # left pointing at the file `load` runs.
538
+ #
539
+ # @api private
540
+ class PathAnchor < Prism::Visitor
541
+ # Argument nodes that are not a path expression. A keyword argument makes
542
+ # `require_relative` raise `ArgumentError` before it touches a file, so
543
+ # the call is left as written. A splat is a path and is kept.
544
+ SKIPPED_ARGUMENTS = [
545
+ Prism::KeywordHashNode, Prism::BlockArgumentNode, Prism::ForwardingArgumentsNode
546
+ ].freeze
547
+
548
+ # @param source [String] the snippet or argument to rewrite.
549
+ # @param file_literal [String] a dumped Ruby string of the original `__FILE__`.
550
+ # @param dir_literal [String] a dumped Ruby string of the original `__dir__`.
551
+ # @param bare_kernel [Boolean] rewrite a bare `Kernel` receiver. False when
552
+ # the method's lexical scope defines a different `Kernel`.
553
+ def initialize(source, file_literal, dir_literal, bare_kernel)
554
+ @source = source
555
+ @file_literal = file_literal
556
+ @dir_literal = dir_literal
557
+ @bare_kernel = bare_kernel
558
+ @edits = []
559
+ end
560
+
561
+ # Parses `source` and applies the edits. A parse that still builds a tree
562
+ # is rewritten too: Prism 2 reports `T += 1` inside a method while Ruby
563
+ # loads it (#392), and the anchors in that method must still move.
564
+ # With no tree, `source` comes back unchanged.
565
+ #
566
+ # @param source [String] snippet or argument source.
567
+ # @param file_literal [String] dumped original `__FILE__`.
568
+ # @param dir_literal [String] dumped original `__dir__`.
569
+ # @param bare_kernel [Boolean] see {#initialize}.
570
+ # @return [String]
571
+ def self.rewrite(source, file_literal, dir_literal, bare_kernel: true)
572
+ parsed = Prism.parse(source)
573
+ return source unless parsed.value
574
+
575
+ anchor = new(source, file_literal, dir_literal, bare_kernel)
576
+ anchor.visit(parsed.value)
577
+ anchor.apply
578
+ end
579
+
580
+ # Replaces a `__FILE__` keyword with the original path.
581
+ #
582
+ # @param node [Prism::SourceFileNode] the keyword.
583
+ # @return [void]
584
+ def visit_source_file_node(node)
585
+ replace(node, @file_literal)
586
+ end
587
+
588
+ # Replaces a path-anchor call, or walks into a call that is not one.
589
+ #
590
+ # @param node [Prism::CallNode] a call in the snippet.
591
+ # @return [void]
592
+ def visit_call_node(node)
593
+ return replace(node, @dir_literal) if dir_call?(node)
594
+
595
+ if (argument = relative_argument(node))
596
+ anchored = rewrite_slice(argument)
597
+ # `::Kernel.require` and `::File` do not follow a nested constant or an
598
+ # instance `require`. `absolute_path` leaves a leading `~` as a path
599
+ # segment; `expand_path` would treat it as a home directory, which
600
+ # `require_relative` does not. An ignored block is part of the call
601
+ # location and is dropped: `require_relative` does not yield it.
602
+ text = ["::Kernel.require(::File.absolute_path(", anchored, ", ", @dir_literal, "))"].join
603
+ return replace(node, text)
604
+ end
605
+
606
+ super
607
+ end
608
+
609
+ # Applies recorded edits from the end, so earlier byte offsets stay valid.
610
+ #
611
+ # @return [String] the rewritten source.
612
+ def apply
613
+ @edits.sort_by! { |start_off,| -start_off }
614
+ @edits.inject(@source) do |code, (start_off, end_off, text)|
615
+ code.byteslice(0, start_off) + text + code.byteslice(end_off..)
616
+ end
617
+ end
618
+
619
+ private
620
+
621
+ # True when `node` is the `__dir__` keyword, including `self.__dir__`,
622
+ # `Kernel.__dir__`, and `send` / `__send__` of the literal name.
623
+ #
624
+ # @param node [Prism::CallNode]
625
+ # @return [Boolean]
626
+ def dir_call?(node)
627
+ args = positional(node)
628
+ return false if args.nil?
629
+
630
+ if node.name == :__dir__
631
+ path_receiver?(node) && args.empty?
632
+ elsif send_call?(node)
633
+ args.size == 1 && literal_name(args.first) == "__dir__"
634
+ else
635
+ false
636
+ end
637
+ end
638
+
639
+ # The single path argument of a `require_relative` call, or nil when the
640
+ # call is not that anchor. `send(:require_relative, expr)` returns `expr`.
641
+ # A splat is included: `require_relative(*paths)` passes those paths on.
642
+ # A block does not matter: the method does not yield it.
643
+ #
644
+ # @param node [Prism::CallNode]
645
+ # @return [Prism::Node, nil]
646
+ def relative_argument(node)
647
+ args = positional(node)
648
+ return unless args
649
+
650
+ if node.name == :require_relative && path_receiver?(node) && args.size == 1
651
+ args.first
652
+ elsif send_call?(node) && args.size == 2 && literal_name(args.first) == "require_relative"
653
+ args.last
654
+ end
655
+ end
656
+
657
+ # True for an implicit receiver, literal `self`, or `Kernel` / `::Kernel`.
658
+ #
659
+ # @param node [Prism::CallNode]
660
+ # @return [Boolean]
661
+ def path_receiver?(node)
662
+ receiver = node.receiver
663
+ return true if receiver.nil? || receiver.is_a?(Prism::SelfNode)
664
+
665
+ kernel_constant?(receiver)
666
+ end
667
+
668
+ # True when `node` is `Kernel` or `::Kernel`.
669
+ #
670
+ # @param node [Prism::Node]
671
+ # @return [Boolean]
672
+ def kernel_constant?(node)
673
+ (node.is_a?(Prism::ConstantPathNode) && node.parent.nil? && node.name == :Kernel) ||
674
+ (@bare_kernel && node.is_a?(Prism::ConstantReadNode) && node.name == :Kernel)
675
+ end
676
+
677
+ # True for `send` or `__send__` on a receiver {path_receiver?} accepts.
678
+ #
679
+ # @param node [Prism::CallNode]
680
+ # @return [Boolean]
681
+ def send_call?(node)
682
+ (node.name == :send || node.name == :__send__) && path_receiver?(node)
683
+ end
684
+
685
+ # Positional arguments, or nil when one of them is a splat or keywords.
686
+ #
687
+ # @param node [Prism::CallNode]
688
+ # @return [Array<Prism::Node>, nil]
689
+ def positional(node)
690
+ args = node.arguments&.arguments || []
691
+ return if args.any? { |arg| SKIPPED_ARGUMENTS.any? { |kind| arg.is_a?(kind) } }
692
+
693
+ args
694
+ end
695
+
696
+ # The text of a symbol or string literal, without quotes.
697
+ #
698
+ # @param node [Prism::Node]
699
+ # @return [String, nil]
700
+ def literal_name(node)
701
+ node.unescaped if node.is_a?(Prism::SymbolNode) || node.is_a?(Prism::StringNode)
702
+ end
703
+
704
+ # The snippet bytes of `node`.
705
+ #
706
+ # @param node [Prism::Node]
707
+ # @return [String]
708
+ def slice(node)
709
+ location = node.location
710
+ @source.byteslice(location.start_offset, location.end_offset - location.start_offset)
711
+ end
712
+
713
+ # Rewrites anchors inside one argument, keeping the call's `bare_kernel` flag.
714
+ #
715
+ # @param node [Prism::Node]
716
+ # @return [String]
717
+ def rewrite_slice(node)
718
+ self.class.rewrite(slice(node), @file_literal, @dir_literal, bare_kernel: @bare_kernel)
719
+ end
720
+
721
+ # Records a replacement of `node`'s source range.
722
+ #
723
+ # @param node [Prism::Node]
724
+ # @param text [String] the Ruby source to write instead.
725
+ # @return [void]
726
+ def replace(node, text)
727
+ location = node.location
728
+ @edits << [location.start_offset, location.end_offset, text]
729
+ end
730
+ end
731
+ private_constant :PathAnchor
377
732
  end
378
733
  end