Module: Mutineer::ReloadGuards::RepeatedCallbacks

Defined in:
lib/mutineer/reload_guards.rb

Overview

Puts back one copy of each callback and validator that a second run of a class body added again (#390).

Each class body the load runs again appends its block callbacks, lambda callbacks and validators a second time. Rails drops the old copy only of a callback that names a method, and appends the new one at the end. For each class whose chains the load changed, RepeatedCallbacks.replacements pairs each entry the load added to the class's own chain with the class's own entry from before the load that it repeats. RepeatedCallbacks.restore then puts each new entry where its old entry was and drops the old one, in every changed chain and in _validators. So each macro runs once, in its original order.

An included concern adds its entries to the class, and the reload does not run its block again, so it adds no new copy of them. Its entries can look like the class body's own, so entries pair first with old entries that are the same (RepeatedCallbacks.same?): a validator with equivalent options, a lambda that captured equivalent values, a block from the same place in the code. They pair only when there are as many old ones as new ones (RepeatedCallbacks.exact_pairs). An entry left over pairs by RepeatedCallbacks.key. The key is the callback kind, the filter, and its if: / unless: conditions. A &:name proc's filter is that symbol. A block's filter is its place and its code, not a value it captured. A validator's filter is its class, its attributes and its option names, not values a method the mutant changed can return. A concern entry that differs on any of those is not a candidate, so the class body's repeat can pair. One that is the same on all of them still shares the key, and the pair is kept only when the counts match, so a guess cannot drop the concern's entry. Otherwise both copies stay (#413). Full reload (#389) builds the class once, which is what can separate those identical entries. Redefine does not run the class body again, so it never adds the copy.

ActiveSupport gives a class a new chain object each time a callback is added or skipped, so a class whose chain objects all stay the same was not changed by the load and is skipped.

Defined Under Namespace

Classes: ChainView

Constant Summary collapse

EQUIVALENT_DEPTH =

How deep equivalent? looks into objects before it gives up.

6
SAME_OBJECT =

BasicObject#equal?, unbound, so a proxy cannot answer for its target.

::BasicObject.instance_method(:equal?)
INSTANCE_OF =

Kernel#instance_of?, unbound, for the same reason.

::Kernel.instance_method(:instance_of?)
KERNEL_CLASS =

Kernel#class, unbound, for the same reason.

::Kernel.instance_method(:class)
SYMBOL_PROC =

CRuby prints Symbol#to_proc as #<Proc:0xaddr(&:name) (lambda)>. The text after & is the symbol's own inspect. The cache holds 67 of these procs, so a later &:other can make the next &:name a new object; the text still matches (#413).

/\A#<Proc:0x[0-9a-fA-F]+\(&(.+)\) \(lambda\)>\z/
ISEQ_FORMAT =

Magic InstructionSequence#to_a starts with. A different format has no code identity, so the block matches by file and label only.

"YARVInstructionSequence/SimpleDataFormat"
ISEQ_MISC_KEYS =

Fields of an instruction sequence that stay the same when the same block is compiled again. Node ids and code locations change on every load, so they are left out.

%i[arg_size local_size stack_max parser].freeze

Class Method Summary collapse

Class Method Details

.block_code(block, reloaded) ⇒ Array?

The block's code, with locations removed, or nil when Ruby cannot show it. A value the block captured is not part of the code, so a new object, a time or a random value still pairs (#413). __FILE__ is the source path in one load and the mutant path in the other; both become the same placeholder. A rescue or ensure keeps a nested sequence in the catch table; that sequence is normalized too, or the two copies would not pair.

Parameters:

  • block (Proc)
  • reloaded (Array<String>) —

    real paths of the source and mutant files.

Returns:

  • (Array, nil)


735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
# File 'lib/mutineer/reload_guards.rb', line 735

def self.block_code(block, reloaded)
  return unless defined?(::RubyVM::InstructionSequence)

  iseq = ::RubyVM::InstructionSequence.of(block)
  return unless iseq

  data = iseq.to_a
  return unless data.is_a?(Array) && data[0] == ISEQ_FORMAT && data[4].is_a?(Hash)

  file, = block.source_location
  paths = [file, *reloaded].compact.flat_map { |path| [path, real_path(path)] }.uniq
  code_identity(data, paths)
rescue StandardError
  nil
end

.block_key(block, reloaded, code: true) ⇒ Array

Where a block sits in the code: the file and Ruby's label for it, such as "block in class:Parcel", plus the line for a file the load did not run, plus the block's code (block_code). The source file and the mutant file count as one file, and their lines are left out, because a mutant can move lines. Two blocks that share a label and differ in code are different callbacks (#413). A &:name proc is the symbol Ruby prints for it, so :normalize does not share a key with :touch.

Parameters:

  • block (Proc)
  • reloaded (Array<String>) —

    real paths of the source and mutant files.

  • code (Boolean) (defaults to: true) —

    when false, the compiled body is left out. A mutant of that body then shares the key of the block it replaced.

Returns:

  • (Array)


691
692
693
694
695
696
697
698
699
700
# File 'lib/mutineer/reload_guards.rb', line 691

def self.block_key(block, reloaded, code: true)
  symbol = symbol_proc_text(block)
  return [:symbol, symbol] if symbol

  file, line = block.source_location
  # CRuby only; elsewhere blocks match by file and line alone.
  label = RubyVM::InstructionSequence.of(block)&.label if defined?(::RubyVM::InstructionSequence)
  compiled = block_code(block, reloaded) if code
  reloaded.include?(file && real_path(file)) ? [:reloaded, label, compiled] : [file, line, label, compiled]
end

.by_key(added, pool, reloaded, code: true) ⇒ Array<Array(Object, Object)>

Pairs the entries no exact match took, by key, but only for a key with as many old entries left as new ones. More old entries means an included concern added some of them, and a guess could drop the concern's entry. Those keep both copies, as before #390.

Parameters:

  • added (Array) —

    new entries with no exact match.

  • pool (Array) —

    old entries no exact match took.

  • reloaded (Array<String>) —

    real paths of the source and mutant files.

  • code (Boolean) (defaults to: true) —

    when false, a block's compiled body is left out of the key, so a mutant of that body still pairs.

Returns:

  • (Array<Array(Object, Object)>) —

    each old entry and the new entry that replaces it.



271
272
273
274
275
276
277
# File 'lib/mutineer/reload_guards.rb', line 271

def self.by_key(added, pool, reloaded, code: true)
  old_by_key = pool.group_by { |entry| key(entry, reloaded, code: code) }
  added.group_by { |entry| key(entry, reloaded, code: code) }.flat_map do |k, new_entries|
    old_entries = old_by_key.fetch(k, [])
    old_entries.size == new_entries.size ? old_entries.zip(new_entries) : []
  end
end

.captured(block) ⇒ Array?

The block's receiver and the values it captured, or nil when Ruby cannot show them. The receiver tells apart method(:x).to_proc of two objects; a class body's blocks share the class as receiver.

Parameters:

  • block (Proc)

Returns:

  • (Array, nil)


670
671
672
673
674
675
# File 'lib/mutineer/reload_guards.rb', line 670

def self.captured(block)
  scope = block.binding
  [scope.receiver] + scope.local_variables.map { |name| scope.local_variable_get(name) }
rescue ArgumentError
  nil
end

.chain_view(callback) ⇒ ChainView

Returns that callback's chain name and config.

Parameters:

  • callback (Object) —

    an ActiveSupport callback.

Returns:

  • (ChainView) —

    that callback's chain name and config.



471
472
473
# File 'lib/mutineer/reload_guards.rb', line 471

def self.chain_view(callback)
  ChainView.new(callback.name, callback.chain_config)
end

.code_identity(data, paths) ⇒ Array

Parameters:

  • data (Array) —

    one InstructionSequence#to_a array.

  • paths (Array<String>) —

    paths to treat as the reloaded file.

Returns:

  • (Array)


754
755
756
757
# File 'lib/mutineer/reload_guards.rb', line 754

def self.code_identity(data, paths)
  misc = ISEQ_MISC_KEYS.to_h { |key| [key, data[4][key]] }
  [data[5], misc, data[9], data[10], data[11], strip_code(data[12], paths), strip_code(data[13], paths)]
end

.condition_item_key(item, reloaded, code: true) ⇒ Object

Parameters:

  • item (Object) —

    one if: or unless: condition.

  • reloaded (Array<String>) —

    real paths of the source and mutant files.

  • code (Boolean) (defaults to: true) —

Returns:

  • (Object)


858
859
860
861
862
863
864
# File 'lib/mutineer/reload_guards.rb', line 858

def self.condition_item_key(item, reloaded, code: true)
  case item
  when Proc then block_key(item, reloaded, code: code)
  when Symbol, Module, Numeric, String, TrueClass, FalseClass, NilClass then item
  else item.class
  end
end

.condition_key(callback, reloaded, code: true) ⇒ Array

Returns its if: and unless: conditions, as keys. A proc condition uses block_key, so a captured value that changes on each load does not hide the repeat.

Parameters:

  • callback (Object) —

    an ActiveSupport callback.

  • reloaded (Array<String>) —

    real paths of the source and mutant files.

  • code (Boolean) (defaults to: true) —

Returns:

  • (Array) —

    its if: and unless: conditions, as keys. A proc condition uses block_key, so a captured value that changes on each load does not hide the repeat.



848
849
850
851
852
# File 'lib/mutineer/reload_guards.rb', line 848

def self.condition_key(callback, reloaded, code: true)
  conditions(callback).map do |list|
    Array(list).map { |item| condition_item_key(item, reloaded, code: code) }
  end
end

.conditions(callback) ⇒ Array

Returns its if: and unless: conditions, as ActiveSupport keeps them (empty lists when it keeps none).

Parameters:

  • callback (Object) —

    an ActiveSupport callback.

Returns:

  • (Array) —

    its if: and unless: conditions, as ActiveSupport keeps them (empty lists when it keeps none).



558
559
560
# File 'lib/mutineer/reload_guards.rb', line 558

def self.conditions(callback)
  %i[@if @unless].map { |name| callback.instance_variable_get(name) || [] }
end

.displaced?(entry, other) ⇒ Boolean

Returns true when Rails drops entry on appending other: both name the same method, with the same kind.

Parameters:

  • entry (Object) —

    an old ActiveSupport callback.

  • other (Object) —

    a new one.

Returns:

  • (Boolean) —

    true when Rails drops entry on appending other: both name the same method, with the same kind.



536
537
538
# File 'lib/mutineer/reload_guards.rb', line 536

def self.displaced?(entry, other)
  entry.filter.is_a?(Symbol) && entry.kind == other.kind && entry.filter == other.filter
end

.displaced_pairs(added, pool, now) ⇒ Array<Array(Object, Object)>

Pairs a new callback that names a method with the old one it displaced. Rails keeps one callback per method name and kind in a chain, whatever its if: and unless:, so the old one is gone from the chain. A reload that changes a condition makes the key differ (#413), but the pair is still certain. restored needs it to rebuild a subclass skip from the reloaded callback (#440).

Parameters:

  • added (Array) —

    new entries nothing else paired.

  • pool (Array) —

    old entries nothing else paired.

  • now (Array) —

    the chain's entries after the load.

Returns:

  • (Array<Array(Object, Object)>) —

    each old entry and the new entry that replaces it.



225
226
227
228
229
230
231
232
# File 'lib/mutineer/reload_guards.rb', line 225

def self.displaced_pairs(added, pool, now)
  present = identity_set(now)
  gone = pool.reject { |entry| present.include?(entry) }
  added.filter_map do |new_entry|
    olds = gone.select { |entry| displaced?(entry, new_entry) }
    [olds.first, new_entry] if olds.size == 1
  end
end

.equivalent?(left, right, reloaded, depth = 0, seen = {}) ⇒ Boolean

True when two values would make the same callback or validator. Each run of a class body builds new blocks, so a block matches another from the same place in the code (block_key) that captured equivalent values. Hashes and arrays match element by element. A class or module matches only itself. Other objects, such as a validator or a callback object, match when they are equal, or of one class with equivalent instance variables. Past EQUIVALENT_DEPTH levels nothing matches, so a deep object pairs only by key (by_key).

A pair already being compared, such as a lambda that captures itself (Rails's belongs_to touch: lambda does), counts as a match: nothing else in it differs. Each answer is kept in seen, so a value many blocks capture is compared once. A value that cannot be compared, such as the proxy with_options yields, matches nothing, so both copies stay.

Parameters:

  • left (Object)
  • right (Object)
  • reloaded (Array<String>) —

    real paths of the source and mutant files.

  • depth (Integer) (defaults to: 0) —

    levels already compared.

  • seen (Hash{Array => Boolean, Symbol}) (defaults to: {}) —

    each pair's answer, or :open while it is being compared, by object id.

Returns:

  • (Boolean)


587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/mutineer/reload_guards.rb', line 587

def self.equivalent?(left, right, reloaded, depth = 0, seen = {})
  return true if SAME_OBJECT.bind_call(left, right)

  pair = [left.__id__, right.__id__]
  return seen[pair] != false if seen.key?(pair)
  return false if depth > EQUIVALENT_DEPTH || !INSTANCE_OF.bind_call(left, KERNEL_CLASS.bind_call(right))

  seen[pair] = :open
  same = ->(a, b) { equivalent?(a, b, reloaded, depth + 1, seen) }
  seen[pair] = case left
               when Module then false
               when Proc then same_block?(left, right, reloaded, same)
               when Hash then left.keys == right.keys && left.all? { |k, v| same.(v, right[k]) }
               when Array then left.size == right.size && left.zip(right).all? { |a, b| same.(a, b) }
               else left == right || same_state?(left, right, same)
               end
rescue StandardError
  seen[pair] = false if pair
  false
end

.exact_pairs(added, pool, reloaded) ⇒ Array<Array(Object, Object)>

Pairs new entries with the old entries that are the same (same?), in order, but only when there are as many old ones as new ones. The class body can add a callback once only (@done ||= ...), or a concern can hold a look-alike, so a different count keeps both copies, as before #390. Removes the paired old entries from pool.

Parameters:

  • added (Array) —

    the entries the load added.

  • pool (Array) —

    the old entries that could be repeated.

  • reloaded (Array<String>) —

    real paths of the source and mutant files.

Returns:

  • (Array<Array(Object, Object)>) —

    each old entry and the new entry that replaces it.



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/mutineer/reload_guards.rb', line 244

def self.exact_pairs(added, pool, reloaded)
  seen = {}
  rest = added
  pairs = []
  until rest.empty?
    first = rest.first
    group, rest = rest.partition { |entry| same?(entry, first, reloaded, seen) }
    olds = pool.select { |entry| same?(entry, first, reloaded, seen) }
    next unless olds.size == group.size

    pool.replace(without(pool, olds))
    pairs.concat(olds.zip(group))
  end
  pairs
end

.extra_conditions(entry, parent) ⇒ Array(Array, Array)

The conditions skip_callback appended after parent's. merged_from? has already required parent's conditions to be a prefix.

Parameters:

  • entry (Object) —

    the merged subclass callback.

  • parent (Object) —

    the ancestor callback it was merged from.

Returns:

  • (Array(Array, Array)) —

    the extra if conditions and the extra unless conditions.



459
460
461
462
463
# File 'lib/mutineer/reload_guards.rb', line 459

def self.extra_conditions(entry, parent)
  entry_if, entry_unless = conditions(entry)
  parent_if, parent_unless = conditions(parent)
  [entry_if.drop(parent_if.size), entry_unless.drop(parent_unless.size)]
end

.identity_set(list) ⇒ Set

A set that compares by identity. Building it first keeps entries that are equal by value but not the same object.

Parameters:

  • list (Array)

Returns:

  • (Set)


879
880
881
# File 'lib/mutineer/reload_guards.rb', line 879

def self.identity_set(list)
  Set.new.compare_by_identity.merge(list)
end

.instruction_body?(node) ⇒ Boolean

Returns true when node is a list of instructions rather than one instruction's operands.

Parameters:

  • node (Array) —

    one array from an instruction sequence.

Returns:

  • (Boolean) —

    true when node is a list of instructions rather than one instruction's operands.



798
799
800
# File 'lib/mutineer/reload_guards.rb', line 798

def self.instruction_body?(node)
  node.any? { |child| child.is_a?(Symbol) && child.to_s.start_with?("RUBY_EVENT_") }
end

.interned_condition?(object) ⇒ Boolean

Returns true for nil, true, false, a Symbol, or an Integer. Those are the same object wherever they are written. A Proc is not.

Parameters:

  • object (Object) —

    one if: or unless: condition.

Returns:

  • (Boolean) —

    true for nil, true, false, a Symbol, or an Integer. Those are the same object wherever they are written. A Proc is not.



435
436
437
438
439
440
# File 'lib/mutineer/reload_guards.rb', line 435

def self.interned_condition?(object)
  object.nil? || same_object?(object, true) || same_object?(object, false) ||
    object.is_a?(Symbol) || object.is_a?(Integer)
rescue StandardError
  false
end

.iseq_node?(node) ⇒ Boolean

A real instruction sequence, not an array a callback happened to build. The magic string alone is not enough: the node also has the misc hash, a label, and a bytecode array. Anything else stays an array, so it cannot blank the block's code identity.

Parameters:

  • node (Array)

Returns:

  • (Boolean)


791
792
793
# File 'lib/mutineer/reload_guards.rb', line 791

def self.iseq_node?(node)
  node[0] == ISEQ_FORMAT && node[4].is_a?(Hash) && node[5].is_a?(String) && node[13].is_a?(Array)
end

.key(callback, reloaded, code: true) ⇒ Array

What two entries share when they are copies of one macro call, apart from values a mutant can change. A callback that names a method matches the same name. A block or lambda matches by block_key. A validator matches by class, attributes and option names, not option values. if: and unless: are part of the key, so the same filter under a different condition is a different callback (#413).

Parameters:

  • callback (Object) —

    an ActiveSupport callback.

  • reloaded (Array<String>) —

    real paths of the source and mutant files.

  • code (Boolean) (defaults to: true) —

Returns:

  • (Array)


813
814
815
816
817
818
819
820
821
# File 'lib/mutineer/reload_guards.rb', line 813

def self.key(callback, reloaded, code: true)
  filter = callback.filter
  filter_key = case filter
               when Symbol, Module then filter
               when Proc then block_key(filter, reloaded, code: code)
               else object_key(filter)
               end
  [callback.kind, filter_key, condition_key(callback, reloaded, code: code)]
end

.merge_source(entry, stray, swap) ⇒ Object?

The nearest old callback that swap maps to stray and that restored can show entry was merged from. Ancestors are inserted furthest first, so the last match is the nearest class that reloaded stray.

Parameters:

  • entry (Object) —

    the subclass callback Rails dropped.

  • stray (Object) —

    the ancestor callback appended in its place.

  • swap (Hash{Object => Object}) —

    each old entry to its new entry.

Returns:

  • (Object, nil) —

    that old callback, or nil when entry is not its merge.



394
395
396
397
398
399
400
# File 'lib/mutineer/reload_guards.rb', line 394

def self.merge_source(entry, stray, swap)
  found = nil
  swap.each do |old_entry, new_entry|
    found = old_entry if new_entry.equal?(stray) && merged_from?(entry, old_entry)
  end
  found
end

.merge_stray(entry, stray, swap) ⇒ Object?

The reloaded callback entry was merged from, when several ancestors appended a callback of the same name. The first of those is not always the one. displaced? only compares the method name and the kind.

Parameters:

  • entry (Object) —

    the subclass callback Rails dropped.

  • stray (Array) —

    new callbacks this chain did not have.

  • swap (Hash{Object => Object}) —

    each old entry to its new entry.

Returns:

  • (Object, nil) —

    the stray to rebuild from, or nil.



410
411
412
# File 'lib/mutineer/reload_guards.rb', line 410

def self.merge_stray(entry, stray, swap)
  stray.find { |candidate| displaced?(entry, candidate) && merge_source(entry, candidate, swap) }
end

.merged_from?(entry, parent) ⇒ Boolean

Returns true when entry's conditions still start with parent's condition objects, and one of those objects is not interned. skip_callback copies those objects. A parent with no conditions matches every copy, so that is not evidence. A symbol is the same object wherever it is written, so it is not evidence either. A symbol-only parent condition stays on the old copy. No issue tracks that limit yet.

Parameters:

  • entry (Object) —

    a callback left by skip_callback.

  • parent (Object) —

    the ancestor callback it was merged from.

Returns:

  • (Boolean) —

    true when entry's conditions still start with parent's condition objects, and one of those objects is not interned. skip_callback copies those objects. A parent with no conditions matches every copy, so that is not evidence. A symbol is the same object wherever it is written, so it is not evidence either. A symbol-only parent condition stays on the old copy. No issue tracks that limit yet.



423
424
425
426
427
428
429
430
# File 'lib/mutineer/reload_guards.rb', line 423

def self.merged_from?(entry, parent)
  entry_if, entry_unless = conditions(entry)
  parent_if, parent_unless = conditions(parent)
  return false if parent_if.empty? && parent_unless.empty?
  return false unless prefix?(entry_if, parent_if) && prefix?(entry_unless, parent_unless)

  (parent_if + parent_unless).any? { |item| !interned_condition?(item) }
end

.object_key(filter) ⇒ Array

Returns its class, attributes and option names.

Parameters:

  • filter (Object) —

    a callback filter that is not a symbol, module or proc.

Returns:

  • (Array) —

    its class, attributes and option names.



825
826
827
828
829
# File 'lib/mutineer/reload_guards.rb', line 825

def self.object_key(filter)
  attributes = filter.attributes if filter.respond_to?(:attributes)
  shape = option_shape(filter.options) if filter.respond_to?(:options)
  [filter.class, attributes, shape]
end

.option_shape(value) ⇒ Array?

Option names, nested, without the values. A method the mutant changed can return a different value; the names in the class body stay.

Parameters:

  • value (Object) —

    a validator's options, or a nested value.

Returns:

  • (Array, nil) —

    nil when value is not a Hash.



836
837
838
839
840
# File 'lib/mutineer/reload_guards.rb', line 836

def self.option_shape(value)
  return unless value.is_a?(Hash)

  value.keys.sort_by(&:to_s).map { |key| [key, option_shape(value[key])] }
end

.owners(klass) ⇒ Array<Class>

Returns klass and its ancestors, furthest first.

Parameters:

  • klass (Class)

Returns:

  • (Array<Class>) —

    klass and its ancestors, furthest first.



522
523
524
525
526
527
528
529
530
# File 'lib/mutineer/reload_guards.rb', line 522

def self.owners(klass)
  owners = []
  current = klass
  while current.is_a?(Class)
    owners << current
    current = current.superclass
  end
  owners.reverse
end

.prefix?(list, parent) ⇒ Boolean

Returns true when each of parent is that object of list. A shorter list does not start with parent.

Parameters:

  • list (Array)
  • parent (Array) —

    the objects list must start with.

Returns:

  • (Boolean) —

    true when each of parent is that object of list. A shorter list does not start with parent.



486
487
488
# File 'lib/mutineer/reload_guards.rb', line 486

def self.prefix?(list, parent)
  parent.each_with_index.all? { |item, index| same_object?(list[index], item) }
end

.real_path(file) ⇒ String

Returns the real path, so a symlinked path still matches.

Parameters:

  • file (String)

Returns:

  • (String) —

    the real path, so a symlinked path still matches.



885
886
887
888
889
890
891
# File 'lib/mutineer/reload_guards.rb', line 885

def self.real_path(file)
  (@real_paths ||= {})[file] ||= begin
    File.realpath(file)
  rescue SystemCallError
    File.expand_path(file)
  end
end

.remove(before, files) ⇒ void

This method returns an undefined value.

Keeps one copy of each entry the load added again.

Parameters:

  • before (Hash) —

    the snapshot from before the load.

  • files (Array<String>) —

    the source file and the mutant file. A block from either one counts as a block from the same file.



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/mutineer/reload_guards.rb', line 155

def self.remove(before, files)
  changed = before.keys.reject { |klass| same_chains?(klass.__callbacks, before[klass]) }
  return if changed.empty?

  reloaded = files.map { |file| real_path(file) }
  # Each class's entries before the load, copied only for the classes asked.
  old = Hash.new { |copies, klass| copies[klass] = before.fetch(klass, {}).transform_values(&:to_a) }
  by_chain = {}
  changed.each do |klass|
    replacements(klass, old, reloaded).each do |name, pairs|
      by_chain[[klass, name]] = pairs
    end
  end
  restore(changed, old, by_chain) unless by_chain.empty?
end

.reorder(old, now, swap) ⇒ Array

A paired new entry whose old entry this chain did not have came from an ancestor's class body, for this same chain name. Rails appends a parent's callback to every loaded subclass, so it also reached a subclass that skipped it (#414). Such an entry is dropped. A replacement on another chain name, or on a class that is not an ancestor, is not such an entry: that chain keeps it. When Rails dropped the subclass's own copy as a duplicate, such as the conditional copy that a skip_callback ... if: leaves, that copy comes back. A copy that still holds its ancestor's conditions from before this load is rebuilt from the reloaded callback, so a mutant of those conditions reaches the subclass (#440). Reload and the daemon run this path. Redefine does not re-run the class body.

Parameters:

  • old (Array) —

    the chain's entries before the load.

  • now (Array) —

    its entries after the load.

  • swap (Hash{Object => Object}) —

    each old entry to its new entry.

Returns:

  • (Array) —

    old with each new entry swapped in, then the other new entries.



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/mutineer/reload_guards.rb', line 333

def self.reorder(old, now, swap)
  present = identity_set(now)
  paired = identity_set(swap.values)
  kept = identity_set(old.filter_map { |entry| swap[entry] })
  stray = now.select { |entry| paired.include?(entry) && !kept.include?(entry) }
  order = old.filter_map do |entry|
    new_entry = swap[entry]
    next new_entry if new_entry && present.include?(new_entry)
    next entry if present.include?(entry)

    other = merge_stray(entry, stray, swap)
    if other
      restored(entry, other, swap)
    elsif stray.any? { |candidate| displaced?(entry, candidate) }
      entry
    end
  end
  order + without(now, order).reject { |entry| swap.key?(entry) || paired.include?(entry) }
end

.replacements(klass, old, reloaded) ⇒ Hash{Symbol => Array<Array(Object, Object)>}

Pairs each entry the load added to klass's own chains with the old entry it repeats: first with old entries that are the same (exact_pairs), then by key. A mutant can change a block's body, so the code no longer matches. Leftovers that share a place and have equal counts pair without the code (by_key with code: false). A concern that shares only that place still makes the counts differ. Last, a callback that names a method pairs with the one it displaced (displaced_pairs), even when its conditions changed.

Parameters:

  • klass (Class) —

    a class whose chains the load changed.

  • old (Hash{Class => Hash{Symbol => Array}}) —

    each class's entries before the load.

  • reloaded (Array<String>) —

    real paths of the source and mutant files.

Returns:

  • (Hash{Symbol => Array<Array(Object, Object)>}) —

    for each chain name, each old entry and the new entry that replaces it.



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/mutineer/reload_guards.rb', line 192

def self.replacements(klass, old, reloaded)
  parent = klass.superclass
  parent_now = parent.respond_to?(:__callbacks) ? parent.__callbacks : {}
  parent_old = old[parent]
  pairs = {}
  klass.__callbacks.each do |name, chain|
    before = old[klass].fetch(name, [])
    added = without(without(chain.to_a, before), parent_now[name].to_a)
    next if added.empty?

    pool = without(before, parent_old.fetch(name, []))
    exact = exact_pairs(added, pool, reloaded)
    rest = without(added, exact.map(&:last))
    keyed = by_key(rest, pool, reloaded)
    loose = by_key(without(rest, keyed.map(&:last)), without(pool, keyed.map(&:first)), reloaded, code: false)
    matched = exact + keyed + loose
    matched += displaced_pairs(without(added, matched.map(&:last)), without(pool, matched.map(&:first)), chain.to_a)
    pairs[name] = matched unless matched.empty?
  end
  pairs
end

.restore(changed, old, by_chain) ⇒ void

This method returns an undefined value.

Rebuilds each changed chain in its order from before the load, with each old entry swapped for its new entry, and entries the load added unpaired at the end. Swaps each validator in _validators the same way.

Parameters:

  • changed (Array<Class>) —

    the classes whose chains the load changed.

  • old (Hash{Class => Hash{Symbol => Array}}) —

    each class's entries before the load.

  • by_chain (Hash{Array(Class, Symbol) => Array<Array(Object, Object)>}) —

    each class and chain name, with the old and new entries paired there.



288
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
# File 'lib/mutineer/reload_guards.rb', line 288

def self.restore(changed, old, by_chain)
  seen = {}.compare_by_identity
  changed.each do |klass|
    klass.__callbacks.each do |name, chain|
      next if seen[chain]

      seen[chain] = true
      now = chain.to_a
      order = reorder(old[klass].fetch(name, []), now, swap_for(klass, name, by_chain))
      next if order.size == now.size && order.zip(now).all? { |a, b| a.equal?(b) }

      chain.clear
      chain.append(*order)
    end
  end
  # A validator is the filter of its `validate` callback. The same
  # validator object can sit on a subclass, so every pair counts here.
  validators = {}.compare_by_identity
  by_chain.each_value do |pairs|
    pairs.each { |old_entry, new_entry| validators[old_entry.filter] = new_entry.filter }
  end
  lists = changed.select { |klass| klass.respond_to?(:_validators) }.flat_map { |klass| klass._validators.values }
  lists.uniq(&:object_id).each do |list|
    list.map! { |validator| validators.fetch(validator, validator) }
    list.uniq!(&:object_id)
  end
end

.restored(entry, stray, swap) ⇒ Object

The callback to put back when Rails dropped entry as a duplicate of stray. skip_callback with if: or unless: builds entry by copying the parent's condition objects and appending the subclass's own. Putting that object back would keep the parent's conditions from before the reload (#440). When those objects are still the parent's previous ones, this rebuilds entry from stray through merge_conditional_options, the same merge skip_callback uses: a subclass if: is stored on unless, and a subclass unless: on if. A copy that does not hold those objects is the subclass's own callback and stays. A parent that had no conditions has no objects to match, so its copy stays too (#414): a subclass callback of the same name is not rewritten. A list of only symbols, or other interned objects, is not evidence either. An independent callback can name the same symbol. A copied Proc is evidence, and that Proc is carried. The old copy also stays when stray still has those same condition objects.

Parameters:

  • entry (Object) —

    the subclass callback Rails dropped.

  • stray (Object) —

    the ancestor callback appended in its place.

  • swap (Hash{Object => Object}) —

    each old entry to its new entry.

Returns:

  • (Object) —

    entry, or the rebuilt callback.



374
375
376
377
378
379
380
381
382
383
384
# File 'lib/mutineer/reload_guards.rb', line 374

def self.restored(entry, stray, swap)
  parent = merge_source(entry, stray, swap)
  return entry unless parent
  return entry if same_conditions?(stray, parent)
  return entry unless stray.respond_to?(:merge_conditional_options)

  extra_if, extra_unless = extra_conditions(entry, parent)
  stray.merge_conditional_options(
    chain_view(stray), if_option: extra_unless, unless_option: extra_if
  )
end

.same?(old_entry, new_entry, reloaded, seen = {}) ⇒ Boolean

True when two entries come from the same macro call with the same arguments: the same kind, and filters and if:/unless: conditions that are equivalent?. A concern and the class body can add one callback class under different conditions; those are different entries.

Parameters:

  • old_entry (Object) —

    an ActiveSupport callback from before the load.

  • new_entry (Object) —

    one the load added.

  • reloaded (Array<String>) —

    real paths of the source and mutant files.

  • seen (Hash) (defaults to: {}) —

    answers already found (equivalent?).

Returns:

  • (Boolean)


550
551
552
553
# File 'lib/mutineer/reload_guards.rb', line 550

def self.same?(old_entry, new_entry, reloaded, seen = {})
  old_entry.kind == new_entry.kind && equivalent?(old_entry.filter, new_entry.filter, reloaded, 0, seen) &&
    equivalent?(conditions(old_entry), conditions(new_entry), reloaded, 0, seen)
end

.same_block?(left, right, reloaded, same) ⇒ Boolean

Returns true for blocks from the same place in the code that captured equivalent values. A &:name proc has no source and captures nothing; it matches another for the same symbol (#413). method(:x).to_proc still matches only through its source and the receiver it captured.

Parameters:

  • left (Proc)
  • right (Proc)
  • reloaded (Array<String>) —

    real paths of the source and mutant files.

  • same (Proc) —

    compares two values one level deeper.

Returns:

  • (Boolean) —

    true for blocks from the same place in the code that captured equivalent values. A &:name proc has no source and captures nothing; it matches another for the same symbol (#413). method(:x).to_proc still matches only through its source and the receiver it captured.



641
642
643
644
645
646
647
648
# File 'lib/mutineer/reload_guards.rb', line 641

def self.same_block?(left, right, reloaded, same)
  left_symbol = symbol_proc_text(left)
  right_symbol = symbol_proc_text(right)
  return left_symbol == right_symbol if left_symbol || right_symbol
  return false unless left.source_location && right.source_location

  block_key(left, reloaded) == block_key(right, reloaded) && same_captures?(left, right, same)
end

.same_captures?(left, right, same) ⇒ Boolean

Returns true when both captured equivalent values. The list itself is not a level, so blocks that capture each other in a loop reach the pair already being compared before the depth limit.

Parameters:

  • left (Proc)
  • right (Proc) —

    a block from the same place in the code.

  • same (Proc) —

    compares two values one level deeper.

Returns:

  • (Boolean) —

    true when both captured equivalent values. The list itself is not a level, so blocks that capture each other in a loop reach the pair already being compared before the depth limit.



656
657
658
659
660
661
662
# File 'lib/mutineer/reload_guards.rb', line 656

def self.same_captures?(left, right, same)
  mine = captured(left)
  theirs = captured(right)
  return false unless mine && theirs && mine.size == theirs.size

  mine.zip(theirs).all? { |a, b| same.(a, b) }
end

.same_chains?(now, before) ⇒ Boolean

Returns true when every chain is the same object as before.

Parameters:

  • now (Hash{Symbol => Object}) —

    a class's chains after the load.

  • before (Hash{Symbol => Object}) —

    its chains before the load.

Returns:

  • (Boolean) —

    true when every chain is the same object as before.



174
175
176
# File 'lib/mutineer/reload_guards.rb', line 174

def self.same_chains?(now, before)
  now.size == before.size && now.all? { |name, chain| before[name].equal?(chain) }
end

.same_conditions?(left, right) ⇒ Boolean

Returns true when both condition lists hold the same objects, in order.

Parameters:

  • left (Object) —

    a callback.

  • right (Object) —

    another callback.

Returns:

  • (Boolean) —

    true when both condition lists hold the same objects, in order.



446
447
448
449
450
# File 'lib/mutineer/reload_guards.rb', line 446

def self.same_conditions?(left, right)
  left_if, left_unless = conditions(left)
  right_if, right_unless = conditions(right)
  same_list?(left_if, right_if) && same_list?(left_unless, right_unless)
end

.same_list?(list, parent) ⇒ Boolean

Returns true when list and parent are the same objects, in order.

Parameters:

  • list (Array)
  • parent (Array)

Returns:

  • (Boolean) —

    true when list and parent are the same objects, in order.



478
479
480
# File 'lib/mutineer/reload_guards.rb', line 478

def self.same_list?(list, parent)
  list.size == parent.size && prefix?(list, parent)
end

.same_object?(left, right) ⇒ Boolean

BasicObject#equal?, so a proxy condition cannot answer for its target. A condition that cannot be compared does not count as the parent's.

Parameters:

  • left (Object)
  • right (Object)

Returns:

  • (Boolean)


496
497
498
499
500
# File 'lib/mutineer/reload_guards.rb', line 496

def self.same_object?(left, right)
  SAME_OBJECT.bind_call(left, right)
rescue StandardError
  false
end

.same_state?(left, right, same) ⇒ Boolean

Returns true when the instance variables both have are equivalent. One of them can hold a value the other has not cached yet, such as a Rails reflection's memoized lookups, so the others are skipped. No shared variables is not a match: a symbol or a number has none, and those compare by value.

Parameters:

  • left (Object)
  • right (Object) —

    an object of the same class.

  • same (Proc) —

    compares two values one level deeper.

Returns:

  • (Boolean) —

    true when the instance variables both have are equivalent. One of them can hold a value the other has not cached yet, such as a Rails reflection's memoized lookups, so the others are skipped. No shared variables is not a match: a symbol or a number has none, and those compare by value.



625
626
627
628
629
630
# File 'lib/mutineer/reload_guards.rb', line 625

def self.same_state?(left, right, same)
  names = left.instance_variables & right.instance_variables
  return false if names.empty?

  names.all? { |name| same.(left.instance_variable_get(name), right.instance_variable_get(name)) }
end

.snapshot ⇒ Hash{Class => Hash{Symbol => Object}}

Every loaded class with ActiveSupport callbacks, with its chain objects.

Returns:

  • (Hash{Class => Hash{Symbol => Object}}) —

    empty without ActiveSupport.



141
142
143
144
145
146
147
# File 'lib/mutineer/reload_guards.rb', line 141

def self.snapshot
  return {} unless ReloadGuards.callbacks_loaded?

  # Asks the module: a class can define its own `<` (`extend Comparable`).
  classes = ObjectSpace.each_object(Class).select { |klass| ::ActiveSupport::Callbacks > klass }
  classes.to_h { |klass| [klass, klass.__callbacks.dup] }
end

.strip_code(node, paths) ⇒ Object

Returns node with line numbers and those paths removed. A bare integer in an instruction list is a line number, including one in the middle of a rescue or ensure body. An integer that is an operand, such as [:getlocal_WC_0, 3], stays.

Parameters:

  • node (Object) —

    one node of an instruction sequence.

  • paths (Array<String>) —

    paths to treat as the reloaded file.

Returns:

  • (Object) —

    node with line numbers and those paths removed. A bare integer in an instruction list is a line number, including one in the middle of a rescue or ensure body. An integer that is an operand, such as [:getlocal_WC_0, 3], stays.



765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
# File 'lib/mutineer/reload_guards.rb', line 765

def self.strip_code(node, paths)
  case node
  when Array
    if iseq_node?(node)
      code_identity(node, paths)
    elsif instruction_body?(node)
      node.filter_map { |child| strip_code(child, paths) unless child.is_a?(Integer) }
    else
      node.map { |child| strip_code(child, paths) }
    end
  when String
    paths.include?(node) ? :reloaded_path : node
  when Hash
    node.to_h { |key, value| [strip_code(key, paths), strip_code(value, paths)] }
  else
    node
  end
end

.swap_for(klass, name, by_chain) ⇒ Hash{Object => Object}

Pairs for name on klass and on each of its ancestors. Rails appends one reloaded callback onto descendants of that class, and only onto this chain name. A pair from any other chain must not drop an entry here.

Parameters:

  • klass (Class) —

    the class whose chain is being rebuilt.

  • name (Symbol) —

    the chain name, such as :save.

  • by_chain (Hash{Array(Class, Symbol) => Array<Array(Object, Object)>}) —

    see restore.

Returns:

  • (Hash{Object => Object}) —

    each old entry to its new entry.



512
513
514
515
516
517
518
# File 'lib/mutineer/reload_guards.rb', line 512

def self.swap_for(klass, name, by_chain)
  swap = {}.compare_by_identity
  owners(klass).each do |owner|
    by_chain[[owner, name]]&.each { |old_entry, new_entry| swap[old_entry] = new_entry }
  end
  swap
end

.symbol_proc_text(block) ⇒ String?

Returns the symbol text, such as ":normalize", or nil when block is not a Symbol#to_proc.

Parameters:

  • block (Proc)

Returns:

  • (String, nil) —

    the symbol text, such as ":normalize", or nil when block is not a Symbol#to_proc.



711
712
713
# File 'lib/mutineer/reload_guards.rb', line 711

def self.symbol_proc_text(block)
  SYMBOL_PROC.match(block.to_s)&.[](1) if block.is_a?(::Proc)
end

.without(list, others) ⇒ Array

Returns the entries of list that are not in others, by identity.

Parameters:

  • list (Array)
  • others (Array)

Returns:

  • (Array) —

    the entries of list that are not in others, by identity.



869
870
871
872
# File 'lib/mutineer/reload_guards.rb', line 869

def self.without(list, others)
  others = identity_set(others)
  list.reject { |entry| others.include?(entry) }
end