Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,6 @@ jobs:
- '3.3'
- '3.4'
- '4.0'
- mingw
- mswin
- ucrt

Expand Down
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@
`diff` and `sdiff` build their default results without traversal events.
[#230][pull-230]

- Clément Joubert ([@czj][gh-user-czj]) made `Diff::LCS::Change` and
`Diff::LCS::ContextChange` plain frozen classes with the API they had as
`Data` classes, so building one allocates a single object: on line diffs
with YJIT, `sdiff` runs more than twice as fast and `traverse_balanced`
1.7 times as fast. They are no longer `Data` instances, `to_s`, `pp` and
`ContextChange#inspect` drop the `data` prefix, keyword names must be
Symbols, a subclass overriding `initialize` with keyword parameters can no
longer be built positionally, and a `Marshal` or YAML dump made with 2.0.x
no longer loads. [#235][pull-235]

## 2.0.0 / 2026-02-01

This release has significant **breaking changes**.
Expand Down Expand Up @@ -591,6 +601,7 @@ This release has significant **breaking changes**.
[pull-230]: https://github.com/halostatue/diff-lcs/pull/230
[pull-231]: https://github.com/halostatue/diff-lcs/pull/231
[pull-234]: https://github.com/halostatue/diff-lcs/pull/234
[pull-235]: https://github.com/halostatue/diff-lcs/pull/235
[rspec-expectations#200]: https://github.com/rspec/rspec-expectations/pull/200
[rspec-expectations#219]: https://github.com/rspec/rspec-expectations/issues/219
[rspec-expectations#238]: https://github.com/rspec/rspec-expectations/issues/238
Expand Down
2 changes: 2 additions & 0 deletions Manifest.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ lib/diff/lcs/array.rb
lib/diff/lcs/block.rb
lib/diff/lcs/callbacks.rb
lib/diff/lcs/change.rb
lib/diff/lcs/frozen_value.rb
lib/diff/lcs/hunk.rb
lib/diff/lcs/internals.rb
lib/diff/lcs/ldiff.rb
Expand Down Expand Up @@ -113,6 +114,7 @@ test/fixtures/old-chef2
test/test_block.rb
test/test_change.rb
test/test_diff.rb
test/test_frozen_value.rb
test/test_helper.rb
test/test_hunk.rb
test/test_issues.rb
Expand Down
106 changes: 74 additions & 32 deletions lib/diff/lcs/change.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
# frozen_string_literal: true

Diff::LCS::Change = Data.define(:action, :position, :element) # :nodoc:
Diff::LCS::ContextChange = Data.define(:action, :old_position, :old_element, :new_position, :new_element) # :nodoc:
require "diff/lcs/frozen_value"

# Represents a simplistic (non-contextual) change. Represents the removal or addition of
# an element from either the old or the new sequenced enumerable.
class Diff::LCS::Change
include Diff::LCS::FrozenValue

# The only actions valid for changes are '+' (add), '-' (delete), '=' (no change), '!'
# (changed), '<' (tail changes from first sequence), or '>' (tail changes from second
# sequence). The last two ('<>') are only found with Diff::LCS::diff and
Expand All @@ -14,23 +15,37 @@ class Diff::LCS::Change

def self.valid_action?(action) = VALID_ACTIONS.include?(action)

##
MEMBERS = %i[action position element].freeze
private_constant :MEMBERS

# Returns the member names of a Change, in the order of its positional arguments.
def self.members = MEMBERS.dup

# Returns the action this Change represents.
# :attr_reader: action
attr_reader :action

##
# Returns the position of the Change.
# :attr_reader: position
attr_reader :position

##
# Returns the sequence element of the Change.
# :attr_reader: element
attr_reader :element

# :call-seq:
# new(action, position, element) -> change
# new(action:, position:, element:) -> change
#
# Returns a new frozen Change. `action` must be one of VALID_ACTIONS and `position`
# must be an Integer.
def initialize(action = NO_ARGUMENT, position = NO_ARGUMENT, element = NO_ARGUMENT)
action, position, element = arguments_to_values(action, position, element) if NO_ARGUMENT.equal?(element)

def initialize(action:, position:, element:)
fail "Invalid Change Action '#{action}'" unless Diff::LCS::Change.valid_action?(action)
fail "Invalid Position Type" unless position.is_a?(Integer)

super
@action = action
@position = position
@element = element
freeze
end

def inspect(*_args) = "#<#{self.class}: #{to_a.inspect}>"
Expand All @@ -41,6 +56,12 @@ def to_a = [action, position, element]

def deconstruct_keys(_) = {action:, position:, element:}

protected def values # :nodoc:
[@action, @position, @element]
end

private def member_names = MEMBERS

def self.from_a(arr)
case arr
in [action, [old_position, old_element], [new_position, new_element]]
Expand Down Expand Up @@ -84,32 +105,51 @@ def finished_b? = action == "<"
# Represents a contextual change. Contains the position and values of the elements in the
# old and the new sequenced enumerable values as well as the action taken.
class Diff::LCS::ContextChange
##
include Diff::LCS::FrozenValue

MEMBERS = %i[action old_position old_element new_position new_element].freeze
private_constant :MEMBERS

# Returns the member names of a ContextChange, in the order of its positional arguments.
def self.members = MEMBERS.dup

# Returns the action this Change represents.
# :attr_reader: action
attr_reader :action

##
# Returns the old position being changed.
# :attr_reader: old_position

##
# Returns the new position being changed.
# :attr_reader: new_position
attr_reader :old_position

##
# Returns the old element being changed.
# :attr_reader: old_element
attr_reader :old_element

# Returns the new position being changed.
attr_reader :new_position

##
# Returns the new element being changed.
# :attr_reader: new_element
attr_reader :new_element

# :call-seq:
# new(action, old_position, old_element, new_position, new_element) -> context_change
# new(action:, old_position:, old_element:, new_position:, new_element:) -> context_change
#
# Returns a new frozen ContextChange. `action` must be one of Change::VALID_ACTIONS,
# and each position must be an Integer or `nil`.
def initialize(action = NO_ARGUMENT, old_position = NO_ARGUMENT, old_element = NO_ARGUMENT, new_position = NO_ARGUMENT, new_element = NO_ARGUMENT)
if NO_ARGUMENT.equal?(new_element)
action, old_position, old_element, new_position, new_element =
arguments_to_values(action, old_position, old_element, new_position, new_element)
end

def initialize(action:, old_position:, old_element:, new_position:, new_element:)
fail "Invalid Change Action '#{action}'" unless Diff::LCS::Change.valid_action?(action)
fail "Invalid (Old) Position Type" unless old_position.nil? || old_position.is_a?(Integer)
fail "Invalid (New) Position Type" unless new_position.nil? || new_position.is_a?(Integer)

super
@action = action
@old_position = old_position
@old_element = old_element
@new_position = new_position
@new_element = new_element
freeze
end

def to_a = [action, [old_position, old_element], [new_position, new_element]]
Expand All @@ -118,20 +158,22 @@ def to_a = [action, [old_position, old_element], [new_position, new_element]]

def deconstruct_keys(_) = {action:, old_position:, old_element:, new_position:, new_element:}

protected def values # :nodoc:
[@action, @old_position, @old_element, @new_position, @new_element]
end

private def member_names = MEMBERS

def self.from_a(arr) = Diff::LCS::Change.from_a(arr)

# Simplifies a context change for use in some diff callbacks. '<' actions are converted
# to '-' and '>' actions are converted to '+'.
def self.simplify(event)
case event.action
when "-"
event.with(new_element: nil)
when "<"
event.with(action: "-", new_element: nil)
when "+"
event.with(old_element: nil)
when ">"
event.with(action: "+", old_element: nil)
when "-", "<"
event.class.new("-", event.old_position, event.old_element, event.new_position, nil)
when "+", ">"
event.class.new("+", event.old_position, nil, event.new_position, event.new_element)
else
event
end
Expand Down
74 changes: 74 additions & 0 deletions lib/diff/lcs/frozen_value.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# frozen_string_literal: true

module Diff; end unless defined? Diff
module Diff::LCS; end unless defined? Diff::LCS

# The Data API (keyword or positional construction, `members`, `to_h`, `with`, `eql?`,
# `hash`, frozen instances) for Diff::LCS::Change and Diff::LCS::ContextChange. They are
# built for each element of a traversal, and a Data subclass validating in `initialize`
# allocates three more objects per instance than a plain class (ruby-core#22437).
#
# An including class defines a class-level `members` returning a new Array, like Data, a
# private `member_names` returning the same names without a copy, `values`,
# `deconstruct_keys`, readers, and an `initialize` taking one positional argument per
# member, each defaulting to NO_ARGUMENT, which calls `arguments_to_values` when its last
# argument is NO_ARGUMENT, then freezes.
module Diff::LCS::FrozenValue # :nodoc:
NO_ARGUMENT = Object.new.freeze
private_constant :NO_ARGUMENT

def self.included(base)
base.singleton_class.alias_method :[], :new
end

def members = self.class.members

def to_h(&) = deconstruct_keys(nil).to_h(&)

def with(**updates)
return self if updates.empty?

self.class.new(**to_h.merge!(updates))
end

def eql?(other) = self.class == other.class && values.eql?(other.values)

def hash = [self.class, values].hash

def inspect = "#<#{self.class} #{to_h.map { |member, value| "#{member}=#{value.inspect}" }.join(", ")}>"

alias_method :to_s, :inspect

# Psych only calls `encode_with` and `init_with` when they are public.
def encode_with(coder) = to_h.each { |member, value| coder[member.to_s] = value }

# Like `marshal_load`, goes through `initialize`, so loaded values are validated and
# frozen.
def init_with(coder) = initialize(**coder.map.transform_keys { _1.is_a?(String) ? _1.to_sym : _1 })

private

# `allocate` must stay defined: Psych calls it before `init_with`, and TruffleRuby's
# Marshal before `marshal_load`.
def marshal_load(values) = initialize(*values)

def marshal_dump = values

def initialize_copy(*) = super.freeze

def arguments_to_values(*arguments)
arguments.pop while NO_ARGUMENT.equal?(arguments.last)
keywords = arguments.first if arguments.size == 1 && arguments.first.is_a?(Hash)

# Fewer positional arguments than members: the ones left out are always missing.
missing = keywords ? member_names.reject { keywords.key?(_1) } : member_names.drop(arguments.size)
raise_keywords_error("missing", missing) if missing.any?
raise_keywords_error("unknown", keywords.keys - member_names) if keywords.size > member_names.size

keywords.values_at(*member_names)
end

def raise_keywords_error(kind, keywords)
raise ArgumentError, "#{kind} keyword#{"s" if keywords.size > 1}: #{keywords.map(&:inspect).join(", ")}"
end
end
28 changes: 16 additions & 12 deletions test/test_change.rb
Original file line number Diff line number Diff line change
Expand Up @@ -215,20 +215,24 @@ def test_spaceship_element_precedence
end

def test_simplify
simplify("-", 5, "old", 10, "new") => {action:, new_element:}
assert_equal action, "-"
assert_nil new_element
assert_equal change("-", 5, "old", 10, nil), simplify("-", 5, "old", 10, "new")
assert_equal change("-", 5, "old", 10, nil), simplify("<", 5, "old", 10, "new")
assert_equal change("+", 5, nil, 10, "new"), simplify("+", 5, "old", 10, "new")
assert_equal change("+", 5, nil, 10, "new"), simplify(">", 5, "old", 10, "new")
end

def test_simplify_returns_unchanged_and_changed_events_as_they_are
%w[= !].each do |action|
event = change(action, 5, "old", 10, "new")

simplify("<", 5, "old", 10, "new") => {action:, new_element:}
assert_equal action, "-"
assert_nil new_element
assert_same event, Diff::LCS::ContextChange.simplify(event)
end
end

simplify("+", 5, "old", 10, "new") => {action:, old_element:}
assert_equal action, "+"
assert_nil old_element
def test_simplify_keeps_the_class_of_the_event
subclass = Class.new(Diff::LCS::ContextChange)

simplify(">", 5, "old", 10, "new") => {action:, old_element:}
assert_equal action, "+"
assert_nil old_element
assert_instance_of subclass, Diff::LCS::ContextChange.simplify(subclass.new("<", 5, "old", 10, "new"))
assert_instance_of subclass, Diff::LCS::ContextChange.simplify(subclass.new(">", 5, "old", 10, "new"))
end
end
Loading
Loading