def &(enum)
n = __new_like__
- if enum.is_a?(Set)
+ if ::Set === enum && __core_set__?
+ # set_i_intersection: the smaller table walked, the larger one looked up
+ h = n.__send__(:__ir_hidden_ivar__, :@__hash__)
+ mine = @__hash__
+ other = enum.__send__(:__ir_hidden_ivar__, :@__hash__)
+ if other.size > mine.size
+ mine.each_key { |o| h[o] = true if other.key?(o) }
+ else
+ other.each_key { |o| h[o] = true if mine.key?(o) }
+ end
+ elsif enum.is_a?(Set)
if enum.size > size
each { |o| n.add(o) if enum.include?(o) }
else
@@ -716,9 +869,11 @@ def &(enum)
# enumerable's #each may look at what its block answers. Kept and called after
# #& has returned, it still adds to the result but answers nil, as MRI's does
# (test_set.rb's test_and).
+ h = n.__send__(:__ir_hidden_ivar__, :@__hash__)
+ mine = @__hash__
done = false
begin
- __do_with_enum__(enum) { |o| n.add(o) if include?(o); done ? nil : o }
+ __do_with_enum__(enum) { |o| h[o] = true if mine.key?(o); done ? nil : o }
ensure
done = true
end
@@ -749,8 +904,15 @@ def ^(enum)
return n
end
n = dup
- enum = __alloc_like__.merge(enum) unless enum.is_a?(Set)
- enum.each { |o| n.add(o) unless n.delete?(o) }
+ h = n.__send__(:__ir_hidden_ivar__, :@__hash__)
+ enum = __alloc_like__.merge(enum) unless ::Set === enum
+ enum.__send__(:__ir_hidden_ivar__, :@__hash__).each_key do |o|
+ if h.key?(o)
+ h.delete(o)
+ else
+ h[o] = true
+ end
+ end
n
end
diff --git a/Util/bench/erb-shapes.rb b/Util/bench/erb-shapes.rb
new file mode 100644
index 000000000..5db38793a
--- /dev/null
+++ b/Util/bench/erb-shapes.rb
@@ -0,0 +1,46 @@
+# Where ERB#result's time goes (perf/erb2): the parts of app-shapes.rb's erb_result, one template
+# render per unit. erb_full is result_with_hash; erb_eval evals the template's src in a fresh
+# binding (parse, bridge, transform, compile and run); erb_def runs the same src as a method
+# defined once (the body alone); erb_toplevel is new_toplevel + local_variable_set (the binding);
+# erb_new is ERB.new(t).src (the template compiler); eval_small is eval('1 + 1', fresh binding).
+#
+# IR_CONFIG=Release ./ir.sh Util/bench/erb-shapes.rb [shape ...]
+# ruby Util/bench/erb-shapes.rb
+$stdout.sync = true
+require 'erb'
+require 'zlib'
+def crc(s) = Zlib.crc32(s)
+
+PAGE = <<~'EOS'
+ <%= title %>
+
+ <% items.each do |item| -%>
+ - <%= ERB::Util.html_escape(item[:text]) %> (<%= item[:n] %>)
+ <% end -%>
+
+ Total: <%= items.sum { |i| i[:n] } %>
+EOS
+ITEMS = (1..40).map { |i| { text: "Task <#{i}> & more", n: i * 3, done: i.even? } }.freeze
+ERBT = ERB.new(PAGE, trim_mode: '-')
+SRC = ERBT.src
+class Body; end
+Body.class_eval("def self.run(title, items)\n#{SRC}\nend")
+def fresh(title) = (b = binding; b.local_variable_set(:title, title); b.local_variable_set(:items, ITEMS); b)
+
+def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end
+def t(name, n)
+ return puts(name) if ARGV == ['--list']
+ return unless ARGV.empty? || ARGV.include?(name)
+ best = 1e9; sum = nil
+ 7.times { t0 = cpu; sum = yield n; d = cpu - t0; best = d if d < best }
+ printf "%-16s %9.1f ns %d\n", name, best * 1e9 / n, sum
+end
+N = (ENV["N"] || 1000).to_i
+def n(count) = [count * N / 1000, 1].max
+
+t("erb_full", n(300)) { |n| s = 0; n.times { |i| s += crc(ERBT.result_with_hash(title: "T#{i & 3}", items: ITEMS)) }; s }
+t("erb_eval", n(300)) { |n| s = 0; n.times { |i| s += crc(eval(SRC, fresh("T#{i & 3}"), '(erb)', 0)) }; s }
+t("erb_def", n(3000)) { |n| s = 0; n.times { |i| s += crc(Body.run("T#{i & 3}", ITEMS)) }; s }
+t("erb_toplevel", n(3000)) { |n| s = 0; n.times { |i| b = ERBT.send(:new_toplevel, [:title, :items]); b.local_variable_set(:title, i); s += b.local_variable_get(:title) }; s }
+t("erb_new", n(1000)) { |n| s = 0; n.times { s += crc(ERB.new(PAGE, trim_mode: '-').src) }; s }
+t("eval_small", n(10000)) { |n| s = 0; n.times { s += eval('1 + 1', binding) }; s }
diff --git a/Util/bench/invoice-parts.rb b/Util/bench/invoice-parts.rb
new file mode 100644
index 000000000..b5ad9fc29
--- /dev/null
+++ b/Util/bench/invoice-parts.rb
@@ -0,0 +1,64 @@
+# The parts of app-shapes.rb's invoice_build and invoice_render (module Shop), one operation per
+# shape, to see which of them carry the gap to CRuby:
+# ruby Util/bench/invoice-parts.rb [shape...]
+# ruby Util/perf/ab.rb Util/bench/invoice-parts.rb "base=..." "new=..." -- money_new money_with
+$stdout.sync = true
+def cpu = Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID)
+def t(name, n)
+ return puts(name) if ARGV == ['--list']
+ return unless ARGV.empty? || ARGV.include?(name)
+ best = 1e9; sum = nil
+ 7.times { t0 = cpu; sum = yield n; d = cpu - t0; best = d if d < best }
+ printf "%-16s %9.1f ns %d\n", name, best * 1e9 / n, sum
+end
+N = (ENV["N"] || 1000).to_i
+def n(c) = [c * N / 1000, 1].max
+
+module P
+ Address = Struct.new(:street, :city, :country, keyword_init: true)
+ Money = Data.define(:cents) do
+ include Comparable
+ def +(other) = with(cents: cents + other.cents)
+ def *(n) = with(cents: (cents * n).round)
+ def <=>(other) = cents <=> other.cents
+ def to_s = format("%d.%02d", cents / 100, cents % 100)
+ end
+ class Product
+ attr_reader :sku, :price
+ def initialize(sku:, name:, price:, tax: :standard)
+ @sku, @name, @price, @tax = sku, name, Money.new(price), tax
+ end
+ end
+ class Line
+ attr_reader :qty
+ def initialize(product, qty: 1, discount: 0)
+ @product, @qty, @discount = product, qty, discount
+ end
+ end
+ class Doc
+ def audit_log = (@audit_log ||= [])
+ def record(event, **details) = audit_log << { event: event, at: audit_log.size, **details }
+ end
+ module Deep; class Order; end; end
+ M = Money.new(5)
+ PR = Product.new(sku: "A", name: "B", price: 1)
+ LINES = Array.new(6) { |i| Money.new(i) }
+end
+
+t("money_new", n(100000)) { |n| s = 0; n.times { |i| s += P::Money.new(i).cents }; s }
+t("money_new_kw", n(100000)) { |n| s = 0; n.times { |i| s += P::Money.new(cents: i).cents }; s }
+t("money_plus", n(100000)) { |n| m = P::M; s = 0; n.times { s += (m + m).cents }; s }
+t("money_mul", n(100000)) { |n| m = P::M; s = 0; n.times { s += (m * 2).cents }; s }
+t("money_with", n(100000)) { |n| m = P::M; s = 0; n.times { |i| s += m.with(cents: i).cents }; s }
+t("address_new", n(100000)) { |n| s = 0; n.times { s += P::Address.new(street: "a", city: "b", country: "c").country.size }; s }
+t("product_new", n(100000)) { |n| s = 0; n.times { s += P::Product.new(sku: "A", name: "B", price: 3).price.cents }; s }
+t("product_new_opt", n(100000)) { |n| s = 0; n.times { s += P::Product.new(sku: "A", name: "B", price: 3, tax: :zero).price.cents }; s }
+t("line_new", n(100000)) { |n| s = 0; pr = P::PR; n.times { s += P::Line.new(pr, qty: 2).qty }; s }
+t("line_new2", n(100000)) { |n| s = 0; pr = P::PR; n.times { s += P::Line.new(pr, qty: 2, discount: 1).qty }; s }
+t("record", n(100000)) { |n| s = 0; d = P::Doc.new; n.times { |i| d.instance_variable_set(:@audit_log, nil) if i % 8 == 0; s += d.record(:x, a: 1).size }; s }
+t("sum_init", n(30000)) { |n| s = 0; l = P::LINES; n.times { s += l.sum(P::Money.new(0)) { |x| x }.cents }; s }
+t("format", n(100000)) { |n| s = 0; n.times { |i| s += format("%d.%02d", i / 100, i % 100).size }; s }
+t("class_last", n(100000)) { |n| s = 0; o = P::Deep::Order.new; n.times { s += o.class.name.split('::').last.size }; s }
+t("cmp", n(100000)) { |n| s = 0; a = P::M; b = P::Money.new(7); n.times { s += (a <=> b) }; s }
+t("sort", n(30000)) { |n| s = 0; l = P::LINES; n.times { s += l.sort.first.cents }; s }
+t("sort_by_arr", n(30000)) { |n| s = 0; l = P::LINES; n.times { s += l.sort_by { |x| [-x.cents, "a"] }.first.cents }; s }
diff --git a/Util/bench/set-shapes.rb b/Util/bench/set-shapes.rb
new file mode 100644
index 000000000..8be5d4850
--- /dev/null
+++ b/Util/bench/set-shapes.rb
@@ -0,0 +1,52 @@
+# Times each operation of app-shapes.rb's `set` alone (Set is core in CRuby 4.0, set.c, and
+# Ruby in IronRuby, Src/StdLib/ironruby/set.rb). Prints ` ns `; the
+# checksums must equal CRuby's.
+#
+# ruby Util/bench/set-shapes.rb [shape...]
+# ruby Util/perf/ab.rb Util/bench/set-shapes.rb cruby=ruby "new=env IR_CONFIG=Release ./ir.sh"
+$stdout.sync = true
+def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end
+# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the
+# seven sections as the time is. See Util/perf/instructions.rb.
+INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)"))
+def t(name, n)
+ return puts(name) if ARGV == ['--list']
+ return unless ARGV.empty? || ARGV.include?(name)
+ best = 1e9; fewest = nil; counted = !!INSTR; sum = nil
+ 7.times do
+ c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read
+ best = d if d < best
+ # a read is nil once the counter is lost: then there is no count, rather than one of the sections that had it
+ if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end
+ end
+ printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : ""
+end
+N = (ENV["N"] || 1000).to_i
+def n(c) = [c * N / 1000, 1].max
+A = Set.new(1..200)
+B = Set.new((100..300).step(2))
+D = A & B
+R = (1..200)
+AR = R.to_a
+EN = (100..300).step(2)
+S3 = Set[1, 2, 3]
+W = %w[apple pear apple plum fig pear kiwi fig]
+T = Set[1000]
+t("new_range", n(300)) { |n| s = 0; n.times { s += Set.new(R).size }; s }
+t("new_step", n(300)) { |n| s = 0; n.times { s += Set.new(EN).size }; s }
+t("new_array", n(300)) { |n| s = 0; n.times { s += Set.new(AR).size }; s }
+t("new_empty", n(30000)) { |n| s = 0; n.times { s += Set.new.size }; s }
+t("brackets", n(30000)) { |n| s = 0; n.times { s += Set[1, 2, 3].size }; s }
+t("union", n(300)) { |n| s = 0; n.times { s += (A | B).size }; s }
+t("minus", n(300)) { |n| s = 0; n.times { s += (A - S3).size }; s }
+t("and", n(300)) { |n| s = 0; n.times { s += (A & B).size }; s }
+t("xor", n(300)) { |n| s = 0; n.times { s += (A ^ B).size }; s }
+t("subset", n(3000)) { |n| s = 0; n.times { s += 1 if D.subset?(A) }; s }
+t("superset", n(3000)) { |n| s = 0; n.times { s += 1 if A.superset?(D) }; s }
+t("disjoint", n(30000)) { |n| s = 0; n.times { s += 1 if A.disjoint?(T) }; s }
+t("add_words", n(10000)) { |n| s = 0; n.times { w = Set.new; W.each { |x| w << x }; s += w.size }; s }
+t("include", n(100000)) { |n| s = 0; n.times { s += 1 if A.include?(150) }; s }
+t("each", n(1000)) { |n| s = 0; n.times { A.each { |x| s += x } }; s }
+t("select_sum", n(1000)) { |n| s = 0; n.times { s += A.select(&:even?).sum }; s }
+t("map_sum", n(1000)) { |n| s = 0; n.times { s += D.map { |x| x * 2 }.sum }; s }
+t("size", n(100000)) { |n| s = 0; n.times { s += A.size }; s }
diff --git a/Util/bench/time-shapes.rb b/Util/bench/time-shapes.rb
new file mode 100644
index 000000000..19ebff99c
--- /dev/null
+++ b/Util/bench/time-shapes.rb
@@ -0,0 +1,32 @@
+# The parts of app-shapes.rb's `time` shape, one shape each.
+$stdout.sync = true
+require 'time'
+require 'zlib'
+def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end
+INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)"))
+def t(name, n)
+ return puts(name) if ARGV == ['--list']
+ return unless ARGV.empty? || ARGV.include?(name)
+ best = 1e9; fewest = nil; counted = !!INSTR; sum = nil
+ 7.times do
+ c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read
+ best = d if d < best
+ if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end
+ end
+ printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : ""
+end
+N = (ENV["N"] || 1000).to_i
+def n(c) = [c * N / 1000, 1].max
+ST = ["2026-03-14 15:09:26", "2025-12-31 23:59:59", "2024-02-29 00:00:01", "2001-09-09 01:46:40"].freeze
+TS = ST.map { |s| Time.utc(*s.scan(/\d+/).map(&:to_i)) }.freeze
+ISO = TS.map(&:iso8601).freeze
+def crc(s) = Zlib.crc32(s)
+t("strptime", n(2000)) { |n| s = 0; n.times { |i| s += Time.strptime(ST[i & 3] + " UTC", "%Y-%m-%d %H:%M:%S %Z").utc.to_i % 1000 }; s }
+t("d_strptime", n(4000)) { |n| s = 0; n.times { |i| s += Date._strptime(ST[i & 3] + " UTC", "%Y-%m-%d %H:%M:%S %Z").size }; s }
+t("iso_out", n(20000)) { |n| s = 0; n.times { |i| s += TS[i & 3].iso8601.size }; s }
+t("iso_in", n(4000)) { |n| s = 0; n.times { |i| s += Time.iso8601(ISO[i & 3]).to_i % 1000 }; s }
+t("strftime", n(20000)) { |n| s = 0; n.times { |i| s += TS[i & 3].strftime("%a %d %b %Y %H:%M").size }; s }
+t("parse", n(2000)) { |n| s = 0; n.times { |i| s += Time.parse(ST[i & 3] + " +0000").utc.to_i % 1000 }; s }
+t("d_parse", n(2000)) { |n| s = 0; n.times { |i| s += Date._parse(ST[i & 3] + " +0000").size }; s }
+t("httpdate", n(20000)) { |n| s = 0; n.times { |i| s += TS[i & 3].httpdate.size }; s }
+t("crc", n(20000)) { |n| s = 0; n.times { |i| s += crc(ISO[i & 3]) % 1000 }; s }
diff --git a/Util/erb-escape-matrix.rb b/Util/erb-escape-matrix.rb
new file mode 100644
index 000000000..d57923fca
--- /dev/null
+++ b/Util/erb-escape-matrix.rb
@@ -0,0 +1,107 @@
+# Differential matrix for ERB::Escape.html_escape (Src/Libraries/Erb/ErbEscape.cs, escape.c's erb_escape_html):
+# what it escapes and hands back, and how it converts a non-String with #to_s - rb_convert_type, whose
+# rb_check_funcall asks a respond_to? of the object's own, then any #to_s, then respond_to_missing? and a
+# method_missing of the object's own, and turns a NoMethodError out of method_missing into the TypeError
+# unless respond_to? or respond_to_missing? said yes.
+#
+# ruby Util/erb-escape-matrix.rb > cruby.txt
+# IR_CONFIG=Release ./ir.sh Util/erb-escape-matrix.rb > ir.txt
+# IR_CONFIG=Release ./ir.sh -X:NoJIT -X:NoOSR Util/erb-escape-matrix.rb > ir-nojit.txt
+#
+# All three outputs must be identical.
+require 'erb/escape'
+def t(label)
+ r = yield
+ puts "#{label}: #{r.inspect}"
+rescue Exception => e
+ puts "#{label}: #{e.class}: #{e.message}"
+end
+class P1 < BasicObject # no respond_to?, no respond_to_missing?
+ def method_missing(m, *a) = m == :to_s ? "" : super
+end
+class P2 < BasicObject # respond_to_missing? only, BasicObject has no respond_to?
+ def respond_to_missing?(m, priv) = m == :to_s
+ def method_missing(m, *a) = m == :to_s ? "" : super
+end
+class P3 # to_s advertised only for private lookup
+ undef_method :to_s
+ def respond_to_missing?(m, priv) = m == :to_s && priv
+ def method_missing(m, *a) = m == :to_s ? "" : super
+end
+class P4 # advertised publicly
+ undef_method :to_s
+ def respond_to_missing?(m, priv) = m == :to_s
+ def method_missing(m, *a) = m == :to_s ? "" : super
+end
+class P5 # method_missing without respond_to_missing?
+ undef_method :to_s
+ def method_missing(m, *a) = m == :to_s ? "" : super
+end
+class P6 < BasicObject # nothing at all
+end
+class P7 # respond_to? redefined to say yes
+ undef_method :to_s
+ def respond_to?(m, priv = false) = m == :to_s || super
+ def method_missing(m, *a) = m == :to_s ? "" : super
+end
+class P8 # private to_s
+ private def to_s = ""
+end
+class P9 # to_s returns non-String
+ def to_s = 42
+end
+[P1, P2, P3, P4, P5, P6, P7, P8, P9].each { |c| t(c.name) { ERB::Escape.html_escape(c.new) } }
+class Q1 # method_missing that gives up (super)
+ undef_method :to_s
+ def method_missing(m, *a) = super
+end
+class Q2 # gives up although respond_to_missing? said yes
+ undef_method :to_s
+ def respond_to_missing?(m, priv) = m == :to_s
+ def method_missing(m, *a) = super
+end
+class Q3 # raises a NoMethodError about something else
+ undef_method :to_s
+ def method_missing(m, *a) = m == :to_s ? nil.zork : super
+end
+class Q4 # respond_to? says no although to_s exists
+ def respond_to?(m, priv = false) = m == :to_s ? false : super
+end
+class Q5 # respond_to? of one parameter
+ undef_method :to_s
+ def respond_to?(m) = m == :to_s
+ def method_missing(m, *a) = m == :to_s ? "" : super
+end
+class Q6 < BasicObject # respond_to_missing? says yes only privately, method_missing gives up
+ def respond_to_missing?(m, priv) = m == :to_s && priv
+ def method_missing(m, *a) = ::Kernel.raise(::NoMethodError.new("nope", m, receiver: self))
+end
+$log = []
+class Q7 # what respond_to_missing? is asked
+ undef_method :to_s
+ def respond_to_missing?(m, priv) = ($log << [m, priv]; true)
+ def method_missing(m, *a) = m == :to_s ? "" : super
+end
+[Q1, Q2, Q3, Q4, Q5, Q6, Q7].each { |c| t(c.name) { ERB::Escape.html_escape(c.new) } }
+class Q8 < BasicObject # respond_to? defines the to_s it says yes to: found on the first call
+ def respond_to?(m, priv = false)
+ return false unless m == :to_s
+ (class << self; self; end).send(:define_method, :to_s) { "" }
+ true
+ end
+end
+t("Q8") { ERB::Escape.html_escape(Q8.new) }
+p $log
+class SubS < String; end
+plain = "no entities"
+sub = SubS.new("plain sub")
+[["plain", "a&\"c'd"], ["empty", ""], ["utf8", "é<ü>"], ["binary", "".b], ["sjis", "".encode("Shift_JIS")]].each do |label, s|
+ t(label) { r = ERB::Escape.html_escape(s); [r, r.encoding.name] }
+end
+t("same object") { [ERB::Escape.html_escape(plain).equal?(plain), ERB::Escape.html_escape(sub).equal?(sub), ERB::Escape.html_escape(sub).class] }
+t("utf16") { require "cgi/escape"; ERB::Escape.html_escape("".encode("UTF-16LE")).encode("UTF-8") }
+t("symbol") { ERB::Escape.html_escape(:"") }
+t("integer") { ERB::Escape.html_escape(42) }
+t("nil") { ERB::Escape.html_escape(nil) }
+t("hot") { r = nil; 5000.times { |i| r = ERB::Escape.html_escape(i.even? ? "<#{i}>" : P4.new) }; r }
+t("util") { require "erb"; [ERB::Util.html_escape("<&>"), ERB::Util.h(P5.new)] }
diff --git a/Util/eval-matrix.rb b/Util/eval-matrix.rb
index 7905e4c3a..1bced1185 100644
--- a/Util/eval-matrix.rb
+++ b/Util/eval-matrix.rb
@@ -224,4 +224,71 @@ def t23; m23; rescue => e; e.backtrace.first(3).map { |l| l[/:\d+:in '[^']*'/] }
2.times { eval("define_method(:evb24) { /blk/ }"); c << evb24 }
puts "24. literals in defs: #{r.inspect} #{[a[0].equal?(a[1]), a[0].equal?(a[2]), b[0].equal?(b[1]), c[0].equal?(c[1])].inspect}"
+# 25. blocks and loops of eval'd text that run past the interpreter's compilation threshold (an
+# eval's is higher than other code's): a method redefined, a closure local, a /o regexp, break and
+# next while they run; a while loop whose locals the binding keeps; a define_method block called on
+def f25(i) = i
+src25 = "acc = []; o = nil\n1500.times { |i| (def f25(i) = -i) if i == 700; (def f25(i) = i * 2) if i == 1200\n" \
+ "o = /o\#{i}/o; next if i.odd?; break if i == 1400; acc << f25(i) }\n" \
+ "j = 0; s = 0; while j < 3000; s += j; j += 1; end\n" \
+ "define_method(:g25) { |x| x + j }\n[acc.size, acc.sum, acc[349..352], o, s]"
+r = 3.times.map { eval(src25) }
+g = (1..2500).sum { |x| g25(x) }
+b25 = binding; eval("k25 = 0; 2000.times { k25 += 1 }", b25)
+puts "25. hot blocks in eval: #{r.uniq.inspect} #{r.size} #{g} #{b25.local_variable_get(:k25)}"
+
+# 26-31: the trees of evaluated strings are kept (EvalAstCache, keyed by the text, file, line,
+# outer locals and encoding) and transformed and compiled afresh at each eval.
+# 26. the same text where a name is a method, a parameter, or a local an earlier eval of the
+# binding defined
+def x26 = :meth
+def a26 = eval("x26")
+def b26(x26) = eval("x26")
+def c26
+ b = binding
+ r = [eval("defined?(z26) ? z26 : :none", b)]
+ eval("z26 = 7", b)
+ r << eval("defined?(z26) ? z26 : :none", b) << eval("x26", b)
+end
+r = 600.times.map { |i| i.even? ? a26 : b26(i % 3) }
+puts "26. names: #{r.tally.sort_by(&:to_s).inspect} #{300.times.map { c26 }.uniq.inspect}"
+
+# 27. the same text with a different file and line, hot (a line of 0 is left out: its backtrace
+# line differs on the baseline too)
+r = 600.times.map { |i| eval("[__FILE__, __LINE__, __method__.inspect, caller(0)[0].split('/').last]", nil, "f#{i % 2}.rb", [-1, 1, 7][i % 3]) }
+puts "27. file and line: #{r.uniq.sort.inspect}"
+
+# 28. the same characters in strings of other encodings, and with a magic comment
+u = "['é'.encoding.to_s, 'é'.bytesize, __ENCODING__.to_s]"
+r = 300.times.map { |i| eval(i % 3 == 0 ? u : i % 3 == 1 ? u.encode("ISO-8859-1") : u.b) }
+m = 200.times.map { |i| eval(i.even? ? "# encoding: us-ascii\n__ENCODING__.to_s" : "__ENCODING__.to_s") }
+puts "28. encodings: #{r.uniq.inspect} #{m.uniq.inspect}"
+
+# 29. a syntax error and an error found while compiling, the same each time after the text was
+# evaluated without one in another place
+e = 3.times.map { begin; eval("1 +"); rescue SyntaxError => x; x.message.lines.first.chomp; end }
+f = 3.times.map { |i| begin; eval("break", nil, "b29.rb", 5); rescue SyntaxError => x; x.message[/\A[^\n]*/]; end }
+g = [1, 2].map { |v| eval("[v * 2].each { |w| break w + 1 }") }
+puts "29. errors: #{e.uniq.inspect} #{f.uniq.inspect} #{g.inspect}"
+
+# 30. an ERB template rendered hot, with other values each time, and one that defines a method
+# with a /o regexp and a literal each time it is rendered
+require 'erb'
+t30 = ERB.new("<% items.each do |it| -%><%= title %>:<%= it * k %>,<% end -%>|<%= defined?(extra) ? extra : '-' %>", trim_mode: '-')
+r = 400.times.map { |i| t30.result_with_hash(title: "t#{i % 4}", items: [1, 2, i % 5], k: i % 7) }
+x = 3.times.map { t30.result_with_hash(title: "x", items: [], k: 1, extra: "E") }
+d30 = ERB.new("<% def d30(v) = [/a\#{v}/o, /lit/] %><%= d30(n).first.source %>")
+o = 3.times.map { |n| d30.result_with_hash(n: n) + d30(9).first.source + d30(9)[1].equal?(d30(8)[1]).to_s }
+puts "30. erb: #{r.sum(&:size)} #{r.uniq.size} #{r[0..1].inspect} #{x.uniq.inspect} #{o.inspect}"
+
+# 31. threads rendering the same template and evaluating the same text with other locals at once
+r = 6.times.map do |n|
+ Thread.new do
+ s31 = 0
+ 300.times { |i| s31 += t30.result_with_hash(title: "t", items: [n, i % 3], k: n).size + eval("n * i + 1") }
+ s31
+ end
+end.map(&:value)
+puts "31. threads: #{r.inspect}"
+
puts 'end'
diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md
index 9373dee5f..e2ba3ba8c 100644
--- a/Util/perf/LEDGER.md
+++ b/Util/perf/LEDGER.md
@@ -858,6 +858,14 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has
do not do it. Unexplained, and outside AWFY, but a factor of 2.6 on a polymorphic
site is worth an afternoon. Bounce may be the same thing: one tree's steady state
was 64 ms in one run and 81-83 ms in three others of the same session.
+ Round thirty-three (see Landed, perf/pwalk): a site in a method without a scope
+ (`node.accept(self)` in a visitor) built and compiled a rule per receiver class, and past
+ the DLR's rule caches kept building them again: 52 us a call over 60 classes. Such sites
+ now take a precompiled dispatcher per class (127 ns). Left: `prism_walk` spends about 12%
+ in the dispatcher chain and its cache lookup; a table from class to dispatcher per site is
+ the next idea. A light caller's call of a JIT-typed method with a Float argument (`selfcall`
+ of micro-table) is 3% slower by median through the dispatcher than through the rule, with
+ the same bytes.
13. **Calling an iterator at all costs twice what it does in CRuby**: `a.each { |x| s +=
x }` over one element from a method is 166 ns against 79, `n.times` 182 against 88,
`a.map` 194 against 101, and `a.any? { |x| x > 1000 }` 414 against 67, 438 against
@@ -940,6 +948,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has
`super`, `{}`, a `while` with `break`, a block passed on - which is /perf-frame's. `uniq` is not this skill's:
its C# method alone costs what the call does (500 ns against CRuby's 230). One method per run of
`/perf-core`. `tap` and `then` are already minimal Ruby: what they pay is gap 13.
+ Round thirty-four (see Landed, perf/time2): ASCII `Date._strptime` is C#, `strptime` 0.2-0.3
+ of its time. Left: `Date._parse` and `Time.parse` about 3x CRuby (Ruby regexps and Hash
+ building in `format.rb`), a "UT-3" style offset, UTF-16 subjects' errors, and a subclass of
+ String taking the Ruby path.
16. **A light frame whose usual callee wants the caller's scope costs more than a frame
with a scope**, and **the splat itself is what a forwarding wrapper still pays**. Both
are what is left of "wrappers that splat stay out of light frames", which is done (see
@@ -1059,6 +1071,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has
against 369 ns; positional creation is level at 142 against 131). And
`h.each_pair { |k, v| }` / `each_with_index` are 1.6 to 1.9 times CRuby (gap 13 with
two parameters).
+ Round thirty-four (see Landed, perf/inv2): `Data.new`, `#with` and Data readers are direct;
+ the invoice shapes are at CRuby's time. Left: initializers taking keywords (`Product.new(sku:
+ ...)`) at about 2x CRuby, `Hash#dup`, and Struct `keyword_init` as above. And
+ `Data.singleton_methods` lists `:allocate`, which CRuby's does not (as on the baseline).
25. **Havlak: 1.4 times CRuby, 25 times TruffleRuby, and no single place** (round
sixteen's breakdown; its author's numbers, taken beside two other experiments at load
2-14, so ratios). CRuby runs a copy with som.rb's `Set` renamed to `SomSet`: 2.85-3.3
@@ -1190,6 +1206,13 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has
0.46 of its time, `instance_eval` and `binding.eval` about half. Left: the parse, bridge,
transformation and compilation of every text (about 15 us at the least, CRuby's 2), and
`caller(0)`/`caller_locations` paying the whole CLR walk.
+ Round thirty-three (see Landed, perf/erbr): the blocks of eval'd text are compiled after
+ 1000 runs instead of 32, and `ERB::Escape.html_escape` is C#: `erb_result` 0.68-0.81 of its
+ time. Left: an eval's own cost is about 1 ms on a template (light compile, transformation,
+ bridge), and the template's body run as a method is about 8 times CRuby's.
+ Round thirty-four (see Landed, perf/erb2): the parsed tree of an evaluated text is kept, so a
+ template's parse and bridge cost 5 us instead of 72; `erb_eval` 0.77 of its time. Left: the
+ transformation (~50 us) and light compile (~80 us) of every eval.
32. **A singleton class, and a method defined at run time, cost 25 to 60 times CRuby's**
(`Object.new.singleton_class` 17 us, `def o.x` 18, `define_singleton_method` 46,
`Class.new` 12, with a `def` 37), and `OpenStruct.new(h)` of three keys, which
@@ -1208,6 +1231,15 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has
Left: `singleton_class` (1.4 us here, mostly the class itself), `define_singleton_method`
(4-9 us, which the factory does not cover: its body is a block), `extend` (gap 19), and
the scope per call of a factory-made body.
+ Round thirty-three (see Landed, perf/ostr): readers at light sites, `respond_to?(:x)` and
+ the first setter through `method_missing` no longer build a rule per object's singleton
+ class: `ostruct` of `app-shapes.rb` 0.56 of its time, `ostruct3` of `sdef-shapes.rb` 0.14-0.16.
+ Left: `OpenStruct.new` is about 120 us against CRuby's 10, some fifteen binds per object.
+ Round thirty-four (see Landed, perf/ostr2): a shared rule's test takes in a re-versioned
+ singleton class that resolves the same: binds per OpenStruct 17 -> 4, `ostruct` 0.30-0.33 of
+ its time. Left: the four binds of per-object readers (a different method on each object);
+ the resolution in a polymorphic rule's test, which remembers one rejected version only; and
+ the lock that resolution takes inside a rule test.
33. **Three differences from CRuby in interpolation**, found by the probes of
`Util/interpolation-matrix.rb` on the build before perf/interp and left as they were
@@ -1227,6 +1259,141 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has
## Landed
+- **Gate of 2026-11-24 for round thirty-four** (perf/time2, perf/inv2, perf/erb2, perf/ostr2):
+ the branch at 77f841b9 against 592c75ab, Release net10.0: **PASS** with 7289271b (below).
+ IronRuby.Tests PASSED on both trees, no failure name on either. 37 matrices in seven modes:
+ CRuby's output but for the differences the baseline has too; `strptime-matrix` differs from
+ CRuby in 20 lines against the baseline's 32 and `value-object-matrix` in 2 against 12.
+ `caller-matrix` and `block-loop-matrix` differed on the ReadyToRun host only (the known
+ `Kernel#eval` and nested `Range#each` frames). Recursion a million deep: SystemStackError in
+ both modes. ruby/spec, all five suites (32,285 examples): no failure the known list does not
+ name. The fourteen benchmarks verify; `app-shapes.rb` prints CRuby's checksums, JIT on and off.
+ Timing: AWFY, 12 iterations, both orders: geomean 0.967 and 1.015 (new/base), no benchmark
+ more than 5% slower in both. micro-table: `ivar_rw`, `abs`, `arr`, `yield`, `each4`, `poly2`,
+ `blockeach` and `selfcall` were slower in both orders; in six alternating rounds of their own
+ they are 0.96-1.08, all overlapping, and `poly2` (the shape perf/ostr2's rule test could
+ touch) 1.01 in twelve. Of the shape files, `iso_in`, `parse`, `format` and `eval_distinct`
+ looked slower in one order or both; in alternating rounds of their own, at a steady-state N,
+ they are 0.83-1.03, overlapping. `app-shapes.rb` four rounds each order: `ostruct` 0.30-0.33
+ of its time, `invoice_build` 0.41-0.46, `invoice_render` 0.40-0.43, the rest overlapping.
+ Bytes per iteration: geomean 1.007, none more than 1% but Towers (149 -> 163 KB). Start-up on
+ the ReadyToRun host, twelve alternating runs, best ms (base -> new): `-e 1` 425 -> 449 (medians
+ 521 and 528), `gem --version` 585 -> 600 (medians 685 and 660), and of the gate's own runs
+ `gem list` 1436 -> 1430, `require "irb"` 1292 -> 1286, `irb` 1866 -> 1840.
+
+- **7289271b (round thirty-four, after the merge) - an attribute reader may read a hidden
+ variable.** `RubyAttributeReaderInfo` asserted a name starting with `@`; perf/inv2's Data
+ readers read the hidden `name`, so every Debug build (CI's) failed the assertion in
+ `Prelude_DataStructErrors1`. The assertion takes the hidden prefix too.
+
+- **perf/time2 (round thirty-four, 2026-11-23, ec0f1c98, merged in 1587bcd3) - ASCII-only
+ `Date._strptime` in C#** (`Src/Libraries/Date/DateStrptime.cs`). The Ruby port of 1.9's
+ `_strptime_i` cost about 18 us a call against CRuby's 1.1: a String per format token, a case
+ over sixty literals, a `sub!` with a MatchData per field. The C# walk takes a subject and a
+ format that are both ASCII-only plain Strings and answers false for anything else, which
+ `format.rb` then parses as before. Fixed on both paths: `%L`/`%N` with a sign, `%p` before a
+ letter, an unknown zone's `offset: nil` (in `Date._parse` too). `d_strptime` 0.09-0.31 of its
+ time, `strptime` 0.20-0.30, `time` of `app-shapes.rb` 0.52. `Util/strptime-matrix.rb` gains
+ 69 rows; `Util/bench/time-shapes.rb` splits `time` into its parts.
+
+- **perf/inv2 (round thirty-four, 2026-11-23, 7a2d25f4, merged in ef88aec2) - `Data.new`,
+ `Data#with`, Data readers and `Array#sum`'s plain fold.** `Data.new` built a keyword Hash out
+ of positional values and splatted it into `initialize` through three `__send__`s; when the
+ class's `initialize` is Data's own and the arguments name every member, `KernelOps.DataNew`
+ makes the frozen instance directly (as MRI, calling neither `allocate` nor `freeze`), and
+ `DataWith` likewise. Readers are attribute readers of hidden variables, not `define_method`
+ blocks. `Array#sum` past a non-number is a plain `+` loop, as rb_ary_sum. `Money.new` 1083 ->
+ 307 ns, `with` 1168 -> 478, `<=>` 143 -> 55; `invoice_build` 0.41-0.46 of its time,
+ `invoice_render` 0.40-0.43, near CRuby's at steady state (149 and 128 us against 128 and 126). `Util/bench/invoice-parts.rb`.
+
+- **perf/erb2 (round thirty-four, 2026-11-23, 66e5dec6, merged in acc9f9fc) - the prism trees
+ of evaluated strings are kept** (`EvalAstCache`, gap 31). Per runtime, the last 64 texts up
+ to 64 KB, keyed by text, file, line, outer locals, encoding and whether the eval is outside a
+ method; only the AST, so every eval still transforms and compiles afresh (literal identity,
+ `/o`, `END {}` and call sites stay per eval, which is what sank the compiled-code cache of
+ perf/evalc). A parse that reported anything is not kept. Parse and bridge of a template 72 ->
+ 5 us; `erb_eval` 0.77-0.78 of its time, `erb_full` 0.71-0.73, `erb_result` 0.68.
+ `Util/eval-matrix.rb` rows 26-31, `Util/bench/erb-shapes.rb`.
+
+- **perf/ostr2 (round thirty-four, 2026-11-23, 39fd30bf, merged in 77f841b9) - a shared rule's
+ test takes in a new class version that resolves to its method** (gap 32). Every
+ `define_singleton_method` re-versions the object's singleton class, so each self call inside
+ `ostruct.rb` bound again (about 22 binds per `OpenStruct.new`). `RuleVersionSet.IsValidFor`
+ now resolves the call for a version it does not hold (`RubyCallAction.TryShareVersion`, as
+ `BindShared` would) and adds it when it lands on the rule's method; a call whose visibility
+ comes from the caller's scope only for a public method; one rejected version is remembered.
+ `BindShared` no longer hands out the interpreted rule after the compiled one exists, and a
+ receiver with a singleton class of its own tries the shared rule before a dispatcher at any
+ site. Binds per OpenStruct 17 -> 4; `ostruct` of `app-shapes.rb` 0.30-0.33 of its time,
+ `ostruct3_new` and `ostruct_app` 0.21-0.32. `Util/sdef-matrix.rb` section 11.
+
+- **Gate of 2026-11-23 for round thirty-three** (perf/setx, perf/erbr, perf/ostr, perf/pwalk):
+ the branch at 4e349c7f against 02aa8db1, Release net10.0: **PASS** with 5f9f11ef (below).
+ IronRuby.Tests PASSED on both trees, no failure name on either. 36 matrices in seven modes
+ (JIT on, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls`, `IR_LIGHT_FRAMES=0`, `IR_PARKED_SCOPES=0`,
+ ReadyToRun, and the baseline): CRuby's output but for the differences the baseline has too,
+ and the new `set-matrix` matches CRuby where the baseline differs in 360 lines.
+ `block-loop-matrix` differed on the baseline and the ReadyToRun host only (the known nested
+ `Range#each` frame). Recursion a million deep: SystemStackError in both modes. ruby/spec, all
+ five suites (32,285 examples): no failure the known list does not name. The fourteen
+ benchmarks verify; `app-shapes.rb` prints CRuby's checksum for all 26 shapes, JIT on and off.
+ Timing: AWFY, 12 iterations, both orders: geomean 0.964 and 0.984 (new/base), Richards 0.86-0.89,
+ no benchmark more than 5% slower in both. micro-table: `symcase`, `selfcall` and `str==` were
+ slower in both orders; in eight alternating rounds of their own they overlap (`selfcall` again
+ in ten processes per tree: median 28.9 against 28.1 ns, minimum 27.7 against 26.2).
+ `app-shapes.rb` five rounds each order: `set` 0.48-0.50 of its time, `ostruct` 0.56, `prism_walk`
+ 0.87-0.90, `erb_result` 0.78-0.81 (overlapping), the rest overlapping. `set-shapes.rb` and
+ `eval_1p1`, slower in one order, overlap in eight alternating rounds of their own.
+ **Bytes per iteration: Richards 14.0 -> 30.3 MB**, the one finding: perf/pwalk gave light sites
+ the attribute writer's dispatcher, which boxed a typed Boolean per store. Fixed in 5f9f11ef
+ (geomean of bytes 0.993, Richards 12.8 MB; Richards, DeltaBlue, Towers and Havlak timed again
+ in both orders: 0.963 and 0.937). Start-up on the ReadyToRun host, ten alternating runs, best
+ ms (base -> new): `-e 1` 372 -> 380, `gem --version` 485 -> 491, `gem list` 1094 -> 1061,
+ `require "irb"` 926 -> 929, `irb` 1259 -> 1270.
+
+- **5f9f11ef (round thirty-three, after the gate) - an attribute writer's dispatcher boxes with
+ the shared boxes.** `RubyObjectAttributeWriterDispatcherWithScope` stored `(object)arg0`, a new
+ box per call when the method JIT had typed the site's argument as a Boolean or Integer; it now
+ converts with `MethodDispatcher.Box` (true and false the shared objects, small Integers from the
+ cache), as the method dispatchers do. A case of hot writers from light methods in
+ `Util/perf/hot-shapes-matrix.rb`.
+
+- **perf/setx (round thirty-three, 2026-11-23, a8c5b84c and e8de5370, merged in 8903a912) -
+ a core Set's table filled directly** (`Src/StdLib/ironruby/set.rb`). `Set.new`, `merge`, `&`,
+ `^`, `-`, `subset?` and their kin went through `add` and `include?` per element, which a
+ subclass may redefine and CRuby's set.c does not call; they now fill and read the Hash.
+ New `Util/set-matrix.rb` (408 lines; the baseline differs from CRuby in 360) and
+ `Util/bench/set-shapes.rb`. `set` of `app-shapes.rb` 0.48-0.50 of its time; `Set.new` of a
+ Range or Array 0.15-0.27, `subset?` 0.14-0.54, `&` 0.39, `[]` 0.42. Left: `^` and `|` cost dup
+ and Hash inserts; the method JIT refuses the `i.succ` and `frozen?` loops. Differences from
+ CRuby left as they were: a Set frozen or iterated during a merge, CRuby's interning of String
+ keys, one more `hash`/`eql?` call in `Hash#delete`, redefined Hash methods being seen.
+
+- **perf/erbr (round thirty-three, 2026-11-23, aaa9f836 and c9c171d0, merged in e08dc551) -
+ eval'd blocks compiled later, and `ERB::Escape.html_escape` in C#** (gap 31). The blocks of
+ an eval'd text were compiled after 32 runs, so a template evaluated per request compiled its
+ blocks on the background JIT again and again; `RubyContext.EvalCompilationThreshold` (1000)
+ is the threshold for eval'd code, and `Util/eval-matrix.rb` row 25 runs one past it. And
+ `erb/escape` was a `gsub` in Ruby; `Src/Libraries/Erb/ErbEscape.cs` ports escape.c.
+ `erb_result` 0.68-0.81 of its time; process CPU per call 9-11 -> 2.7-3.5 ms.
+
+- **perf/ostr (round thirty-three, 2026-11-23, 22468d63, merged in ce1ac3ab) - calls on
+ per-object singleton classes without a rule each** (gap 32). `BindShared` shares the rule of
+ a call that lands in a Ruby `method_missing` (`IsMissing`, `ResolveMethodMissingForSite`);
+ `DispatchIntrinsics.MaySpecialize` no longer folds `respond_to?` on a singleton class of a
+ plain object; a light site's first calls of a `define_method` block method go through a
+ LibraryDispatcher. `ostruct` of `app-shapes.rb` 0.56 of its time, `ostruct3` of
+ `sdef-shapes.rb` 0.14-0.16, `extend` 0.36-0.58.
+
+- **perf/pwalk (round thirty-three, 2026-11-23, 9e29c85b, merged in 4e349c7f) - precompiled
+ dispatchers at light sites** (gap 12). `BindPrecompiled` refused sites in methods without a
+ scope, so each receiver class got a rule; it now gives them the dispatchers of Ruby methods
+ and attribute accessors, resolving an explicit receiver's public method only, never for a
+ splat, a refined name or a singleton class (except a `define_method` block method), and
+ `RubyMetaBinder` tries the shared rule first. A site over 60 classes: 52 us -> 127 ns a call;
+ `prism_walk` 0.87-0.90 of its time, Richards 0.83-0.89. The writer's boxing it exposed is
+ fixed in 5f9f11ef.
+
- **Gate of 2026-11-23 for round thirty-two** (perf/caller, perf/stdre, perf/invoice,
perf/sclass): the branch at dbe0a3b3 against b7b71c89, Release net10.0: **PASS**.
IronRuby.Tests PASSED on both trees, no failure name on either. 35 matrices in seven modes
diff --git a/Util/perf/hot-shapes-matrix.rb b/Util/perf/hot-shapes-matrix.rb
index 1d1bd7897..9de7b8009 100644
--- a/Util/perf/hot-shapes-matrix.rb
+++ b/Util/perf/hot-shapes-matrix.rb
@@ -856,3 +856,37 @@ def one_char_slice_threads
p [errs.size, dups, Array.new(128) { |i| (0..127).map(&:chr).join[i].ord } == Array.new(128) { |i| i }]
end
one_char_slice_threads
+
+# ---- attribute writers called hot from methods without a scope (their sites have a precompiled dispatcher), with a
+# literal, a passed and a computed Boolean or Integer: the method JIT types those sites, and the dispatcher boxes the value
+# as the runtime does (true and false are the shared objects). Then a subclass's own writer, a writer redefined, the
+# receiver frozen and a singleton writer, each after the sites are hot.
+class HSWriter
+ attr_accessor :b, :i, :f, :o
+ def set_lit; self.b = false; self.i = 7; self.f = 1.5; self.o = nil; self; end
+ def set_var(x, y); self.b = x; self.i = y; self; end
+ def set_cmp(y); self.b = y > 3; self.i = y * 2; self; end
+end
+class HSWriter2 < HSWriter
+ def b=(v); @b = [:w2, v]; end
+end
+def hs_writers
+ r = []
+ w = HSWriter.new
+ 5000.times { |k| w.set_lit; w.set_var(k.odd?, k); w.set_cmp(k) }
+ r << [w.b, w.i, w.f, w.o, w.b.equal?(true), w.i.equal?(9998)]
+ w.set_lit
+ r << [w.b, w.b.equal?(false), w.i, w.f]
+ v = HSWriter2.new
+ 3000.times { |k| v.set_lit; v.set_cmp(k) }
+ r << [v.b, v.i]
+ HSWriter.class_eval { def i=(v); @i = -v; end }
+ w.set_lit; w.set_var(true, 100); r << [w.b, w.i]
+ w.freeze
+ begin; w.set_lit; rescue => e; r << e.class; end
+ o = HSWriter.new; def o.b=(v); @b = :single; end
+ 2000.times { o.set_lit }
+ r << o.b
+ p r
+end
+hs_writers
diff --git a/Util/sdef-matrix.rb b/Util/sdef-matrix.rb
index 34cae10a8..6aebf7402 100644
--- a/Util/sdef-matrix.rb
+++ b/Util/sdef-matrix.rb
@@ -206,5 +206,69 @@ class B10; def m(*) = :base; end
row "hot #{key}", r
end
+# ---------------------------------------------------------------- 11. shared rules that take in a new singleton class in their test
+# A shared rule's version test resolves the call again for a class version it does not hold (RuleVersionSet.IsValidFor): each
+# object below has a singleton class of its own, and some resolve the call to another method, a private one, a protected one,
+# method_missing, or nothing.
+
+class C11
+ def m = :c11
+ def go = m
+ def go_explicit(o) = o.m
+ def go_missing = zz
+ def method_missing(n, *a) = n == :zz ? :c11_missing : super
+ def respond_to_missing?(n, p = false) = n == :zz || super
+ protected def pm = :c11_pm
+ def call_pm(o) = o.pm
+end
+module M11; def m = :m11; end
+def c11_object(i)
+ o = C11.new
+ o.singleton_class
+ case i % 7
+ when 1 then def o.m = :single
+ when 2 then o.singleton_class.send(:private, :m)
+ when 3 then o.extend(M11)
+ when 4 then o.define_singleton_method(:m) { :dsm }
+ when 5 then def o.method_missing(n, *a) = n == :zz ? :own_missing : super
+ when 6 then o.singleton_class.send(:undef_method, :m)
+ end
+ o
+end
+row "implicit self over singletons", runs(700) { |i| (c11_object(i).go rescue $!.class) }
+row "explicit receiver over singletons", runs(700) { |i| (C11.new.go_explicit(c11_object(i)) rescue $!.class) }
+row "explicit top-level over singletons", runs(700) { |i| o = c11_object(i); (o.m rescue $!.class) }
+row "method_missing over singletons", runs(700) { |i| (c11_object(i).go_missing rescue $!.class) }
+row "protected over singletons", runs(700) { |i| o = c11_object(i); (o.call_pm(c11_object(i + 1)) rescue $!.class) }
+row "public_send over singletons", runs(700) { |i| (c11_object(i).public_send(:m) rescue $!.class) }
+row "respond_to? over singletons", runs(700) { |i| c11_object(i).respond_to?(:m) }
+row "alternating owners", runs(700) { |i| o = C11.new; (i.even? ? (def o.m = :even) : o.singleton_class); o.go }
+class C11b; def m = :b; def go = m; end
+row "method removed mid-loop", runs(600) { |i|
+ C11b.send(:remove_method, :m) if i == 300
+ C11b.send(:define_method, :m) { :back } if i == 450
+ o = C11b.new; o.singleton_class; (o.go rescue $!.class)
+}
+row "method redefined mid-loop", runs(600) { |i|
+ C11b.send(:define_method, :m) { :redefined } if i == 200
+ o = C11b.new; def o.x = 1; o.go
+}
+module R11; refine(C11b) { def m = :refined }; end
+# the refinement is active only where `using R11` is (Use11); C11b#go, defined outside it, is the unrefined control
+module Use11
+ using R11
+ def self.go(o) = o.m
+end
+row "refined class over singletons", runs(300) { |i| o = C11b.new; o.singleton_class; [Use11.go(o), o.go] }
+# each worker counts its calls that did not give what one thread alone gives for the same kind of object
+c11_expected = 7.times.map { |k| (c11_object(k).go rescue $!.class) }
+threads = 4.times.map { |t| Thread.new { c11_wrong = 0; 2000.times { |c11_i| c11_v = (c11_object(c11_i + t).go rescue $!.class); c11_wrong += 1 unless c11_v.equal?(c11_expected[(c11_i + t) % 7]) }; c11_wrong } }
+row "threads over singletons", [c11_expected, threads.map(&:value)]
+os = 300.times.map { |i| OpenStruct.new(a: i, b: i * 2) }
+row "ostruct readers", os.sum { |o| o.a + o.b + o[:a] + (o.respond_to?(:b) ? 1 : 0) }
+os.each_with_index { |o, i| o.c = i; def o.a = -1 if i % 5 == 0 }
+row "ostruct after writers", os.sum { |o| o.a + o.c + o.to_h.size }
+row "ostruct dig/==", [os[3].dig(:a), os[3] == os[3].dup, os[5].delete_field(:a), (os[5].a rescue $!.class), os[1].frozen?, os[1].freeze.frozen?, (begin; os[1].a = 2; rescue => e; e.class; end)]
+
$stderr.puts "jit=#{defined?(IronRuby) ? 'ironruby' : 'cruby'}"
puts "end"
diff --git a/Util/set-matrix.rb b/Util/set-matrix.rb
new file mode 100644
index 000000000..5b5507f1d
--- /dev/null
+++ b/Util/set-matrix.rb
@@ -0,0 +1,202 @@
+# Differential matrix for Set's constructors and operators (Src/StdLib/ironruby/set.rb):
+# Set.new and merge from a Set, an Array, a Range, an arithmetic sequence and other
+# enumerables, |, -, &, ^, subset?, superset?, proper_subset?, proper_superset?, intersect?
+# and disjoint?, for Set, a subclass (Set::SubclassCompatible) and a Set::CoreSet subclass.
+# ruby Util/set-matrix.rb # CRuby reference
+# ./ir.sh Util/set-matrix.rb # IronRuby; the same with -X:NoJIT -X:NoOSR
+# # and with IR_LIGHT_FRAMES=0
+# Each row is evaluated once cold and again after thousands of runs, some with a method
+# of Set or Range redefined or a singleton method added half way.
+
+$log = []
+class Sub < Set
+ def add(o) = ($log << [:sub_add, o]; super)
+ def each(&b) = ($log << :sub_each; super)
+ def include?(o) = ($log << [:sub_inc, o]; super)
+end
+class Core < Set::CoreSet
+ def add(o) = ($log << [:core_add, o]; super)
+ def each(&b) = ($log << :core_each; super)
+ def include?(o) = ($log << [:core_inc, o]; super)
+ def delete?(o) = ($log << [:core_del, o]; super)
+ def size = ($log << :core_size; super)
+end
+class Arr < Array
+ def each = ($log << :arr_each; super)
+ def size = ($log << :arr_size; super)
+ def [](i) = ($log << :arr_at; super)
+end
+class Rng < Range
+ def each = ($log << :rng_each; super)
+end
+class Key
+ attr_reader :k
+ def initialize(k) = @k = k
+ def hash = ($log << [:hash, @k]; @k.hash)
+ def eql?(o) = ($log << [:eql, @k]; o.is_a?(Key) && o.k == @k)
+ def inspect = "K#{@k}"
+end
+class Each2
+ include Enumerable
+ def each = (yield 1; yield 2, 3; yield; yield [4, 5]; self)
+end
+class OwnEntry
+ include Enumerable
+ def each = (yield 9)
+ def each_entry = (yield 1; yield 2)
+end
+class OnlyEach
+ def each = (yield :x; yield :y)
+end
+class OnlyEntry
+ def each_entry = (yield :e)
+end
+
+def row(name)
+ $log = []
+ v = begin
+ r = yield
+ "#{r.class} #{r.inspect}#{r.frozen? ? ' frozen' : ''}"
+ rescue Exception => e
+ "!#{e.class}: #{e.message}"
+ end
+ puts "#{name.ljust(44)} #{v}#{$log.empty? ? '' : " #{$log.inspect}"}"
+end
+
+ROWS = {
+ "new range" => -> { Set.new(1..6) },
+ "new endless step" => -> { Set.new((1..12).step(5)) },
+ "new int step" => -> { Set.new(1.step(10, 4)) },
+ "new float step" => -> { Set.new(1.step(2, 0.5)) },
+ "new string range" => -> { Set.new("a".."d") },
+ "new beginless range" => -> { Set.new(..3) },
+ "new Rng" => -> { Set.new(Rng.new(1, 3)) },
+ "new array" => -> { Set.new([3, 1, 3, "s", nil]) },
+ "new Arr" => -> { Set.new(Arr[1, 2, 2]) },
+ "new hash" => -> { Set.new({a: 1, b: 2}) },
+ "new struct" => -> { Set.new(Struct.new(:a, :b).new(1, 2)) },
+ "new Each2" => -> { Set.new(Each2.new) },
+ "new OwnEntry" => -> { Set.new(OwnEntry.new) },
+ "new OnlyEach" => -> { Set.new(OnlyEach.new) },
+ "new OnlyEntry" => -> { Set.new(OnlyEntry.new) },
+ "new enumerator" => -> { Set.new([1, 2].each_slice(1)) },
+ "new 5" => -> { Set.new(5) },
+ "new keys" => -> { Set.new([Key.new(1), Key.new(1), Key.new(2)]) },
+ "new block" => -> { Set.new(1..3) { |x| x * 10 } },
+ "new Arr block" => -> { Set.new(Arr[1, 2]) { |x| x * 10 } },
+ "Sub.new block" => -> { Sub.new([1, 2]) { |x| -x } },
+ "Core.new block" => -> { Core.new(Each2.new) { |x| [x] } },
+ "new string key" => -> { s = +"str"; r = Set.new([s]); [r.first.frozen?, r.first.equal?(s)] },
+ "new Set" => -> { Set.new(Set[1, 2]) },
+ "new Sub" => -> { Set.new(Sub[1, 2]) },
+ "new Core" => -> { Set.new(Core[1, 2]) },
+ "Sub.new array" => -> { Sub.new([1, 2]) },
+ "Sub.new range" => -> { Sub.new(1..2) },
+ "Core.new array" => -> { Core.new([1, 2]) },
+ "Core.new range" => -> { Core.new(1..2) },
+ "Core.new Each2" => -> { Core.new(Each2.new) },
+ "Core.new Set" => -> { Core.new(Set[7]) },
+ "brackets" => -> { Set[1, 2, 1] },
+ "Core brackets" => -> { Core[1, 2, 1] },
+ "identity new" => -> { a = "x"; s = Set.new.compare_by_identity; s.merge([a, a, "x".dup]); [s.size, s.compare_by_identity?] },
+ "merge many" => -> { Set[1].merge([2], 3..4, Set[5]) },
+ "merge frozen" => -> { Set[1].freeze.merge([2]) },
+ "merge in each" => -> { s = Set[1]; s.each { s.merge([2]) } },
+ "merge self in each" => -> { s = Set[1]; s.each { s.merge(s) } },
+ "merge non-enum" => -> { Set[1].merge(Object.new) },
+ "union" => -> { Set[1, 2] | Set[2, 3] },
+ "union array" => -> { Set[1, 2] | [3, 1] },
+ "union range" => -> { Set[1, 2] | (2..4) },
+ "union non-enum" => -> { Set[1] | 3 },
+ "union Sub" => -> { Set[1] | Sub[5] },
+ "union Core" => -> { Set[1] | Core[5] },
+ "Sub union" => -> { Sub[1] | [2] },
+ "Core union" => -> { Core[1] | [2] },
+ "Core union Core" => -> { Core[1] | Core[2] },
+ "union frozen" => -> { Set[1].freeze | [2] },
+ "union identity" => -> { s = Set["a"].compare_by_identity | ["a"]; [s.size, s.compare_by_identity?] },
+ "minus" => -> { Set[1, 2, 3] - Set[2] },
+ "minus array" => -> { Set[1, 2, 3] - [3, 4] },
+ "minus range" => -> { Set[1, 2, 3] - (2..9) },
+ "minus Sub" => -> { Set[1, 2] - Sub[1] },
+ "minus Core" => -> { Set[1, 2] - Core[1] },
+ "Sub minus" => -> { Sub[1, 2] - [1] },
+ "Core minus" => -> { Core[1, 2] - [1] },
+ "Core minus Core" => -> { Core[1, 2] - Core[2] },
+ "minus non-enum" => -> { Set[1] - 3 },
+ "minus frozen" => -> { Set[1, 2].freeze - [1] },
+ "and" => -> { Set[1, 2, 3] & Set[3, 2, 9] },
+ "and larger" => -> { Set[1, 2] & Set[3, 2, 9, 1] },
+ "and array" => -> { Set[1, 2, 3] & [3, 1, 7] },
+ "and Sub" => -> { Set[1, 2] & Sub[1, 2, 3] },
+ "and Core" => -> { Set[1, 2, 3, 4] & Core[1] },
+ "Sub and" => -> { Sub[1, 2] & [1] },
+ "Sub and Set" => -> { Sub[1, 2] & Set[1] },
+ "Core and" => -> { Core[1, 2] & [1] },
+ "Core and Core" => -> { Core[1, 2] & Core[2, 3] },
+ "and non-enum" => -> { Set[1] & 3 },
+ "and identity" => -> { s = Set["a"].compare_by_identity & ["a"]; [s.size, s.compare_by_identity?] },
+ "and keys" => -> { Set[Key.new(1), Key.new(2)] & Set[Key.new(2)] },
+ "and frozen" => -> { Set[1, 2].freeze & Set[2] },
+ "xor" => -> { Set[1, 2] ^ Set[2, 3] },
+ "xor array" => -> { Set[1, 2] ^ [2, 3, 3] },
+ "xor Sub" => -> { Set[1, 2] ^ Sub[2, 3] },
+ "Sub xor" => -> { Sub[1, 2] ^ [3] },
+ "Core xor" => -> { Core[1, 2] ^ [2, 3] },
+ "Core xor Core" => -> { Core[1, 2] ^ Core[2, 3] },
+ "xor non-enum" => -> { Set[1] ^ 3 },
+ "xor identity" => -> { s = Set["a"].compare_by_identity ^ ["a"]; [s.size, s.compare_by_identity?] },
+ "xor frozen" => -> { Set[1, 2].freeze ^ [2] },
+ "subset" => -> { [Set[1].subset?(Set[1, 2]), Set[1, 3].subset?(Set[1, 2]), Set[1, 2] <= Set[1, 2], Set[1, 2] < Set[1, 2], Set[1] < Set[1, 2]] },
+ "superset" => -> { [Set[1, 2].superset?(Set[1]), Set[1].superset?(Set[1, 2]), Set[1, 2] >= Set[1, 2], Set[1, 2] > Set[1, 2], Set[1, 2] > Set[1]] },
+ "subset Sub" => -> { [Set[1].subset?(Sub[1, 2]), Set[1] < Sub[1, 2], Set[1, 2].superset?(Sub[1]), Set[1, 2] > Sub[1]] },
+ "subset Core" => -> { [Set[1].subset?(Core[1, 2]), Set[1] < Core[1, 2], Set[1, 2].superset?(Core[1]), Set[1, 2] > Core[1]] },
+ "Sub subset" => -> { [Sub[1].subset?(Set[1, 2]), Sub[1] < Sub[1, 2], Sub[1, 2].superset?(Core[1]), Sub[1, 2] > Set[1]] },
+ "Core subset" => -> { [Core[1].subset?(Set[1, 2]), Core[1] < Core[1, 2], Core[1, 2].superset?(Sub[1]), Core[1, 2] > Set[1]] },
+ "subset array" => -> { Set[1].subset?([1]) },
+ "superset array" => -> { Set[1] >= [1] },
+ "subset identity" => -> { a = "a".freeze; b = "a".dup.freeze; [Set[a].compare_by_identity <= Set[b], Set[b] <= Set[a].compare_by_identity, Set[a] <= Set[a].compare_by_identity, Set[a] <= Set[b].compare_by_identity] },
+ "subset keys" => -> { Set[Key.new(1)] <= Set[Key.new(1), Key.new(2)] },
+ "intersect" => -> { [Set[1].intersect?(Set[1, 2]), Set[1, 2, 3].intersect?(Set[4]), Set[1].intersect?([1]), Set[1].intersect?(2..3)] },
+ "disjoint" => -> { [Set[1].disjoint?(Set[1, 2]), Set[1, 2, 3].disjoint?(Set[4]), Set[1].disjoint?([1]), Set[1].disjoint?(2..3)] },
+ "intersect Sub Core" => -> { [Set[1].intersect?(Sub[1]), Set[1].disjoint?(Core[1]), Sub[1].intersect?(Core[1]), Core[1].disjoint?(Sub[1])] },
+ "intersect non-enum" => -> { Set[1].intersect?(3) },
+ "intersect keys" => -> { Set[Key.new(1), Key.new(2)].intersect?(Set[Key.new(2)]) },
+}
+
+ROWS.each { |name, f| row(name, &f) }
+2000.times { ROWS.each_value { |f| $log = []; f.call rescue nil } }
+puts "-- hot"
+ROWS.each { |name, f| row(name, &f) }
+
+# something changes in the middle of hot loops
+class Set
+ alias __m_keep_add add
+ def add(o) = ($log << [:set_add, o]; __m_keep_add(o))
+end
+puts "-- Set#add redefined"
+ROWS.each { |name, f| row(name, &f) }
+class Set
+ alias add __m_keep_add
+end
+class Range
+ alias __m_keep_each each
+ def each(&b) = ($log << :range_each; __m_keep_each(&b))
+end
+puts "-- Range#each redefined"
+2.times { ["new range", "union range", "new beginless range"].each { |n| row(n, &ROWS[n]) } }
+class Range
+ alias each __m_keep_each
+end
+s = Set[1, 2]
+def s.each(&b) = ($log << :singleton_each; super)
+def s.add(o) = ($log << :singleton_add; super)
+puts "-- singleton methods"
+row("single union") { s | [3] }
+row("single and") { s & Set[2] }
+row("single subset") { s <= Set[1, 2, 3] }
+row("new from single") { Set.new(s) }
+row("merge single") { Set[9].merge(s) }
+puts "-- hot again"
+2000.times { ROWS.each_value { |f| $log = []; f.call rescue nil } }
+ROWS.each { |name, f| row(name, &f) }
diff --git a/Util/strptime-matrix.rb b/Util/strptime-matrix.rb
index 3ec99a0d6..373a1f7d7 100644
--- a/Util/strptime-matrix.rb
+++ b/Util/strptime-matrix.rb
@@ -25,7 +25,7 @@ def row(label)
first = v if i == 0
last = v
end
- puts "#{label}: #{first.inspect}#{first == last ? '' : " HOT #{last.inspect}"}"
+ puts "#{label}: #{first.inspect}#{first.inspect == last.inspect ? '' : " HOT #{last.inspect}"}"
end
def sp(str, fmt) = row("_strptime #{str.inspect} #{fmt.inspect}") { Date._strptime(str, fmt) }
@@ -47,6 +47,36 @@ def sp(str, fmt) = row("_strptime #{str.inspect} #{fmt.inspect}") { Date._strpti
["a.b*c", "a.b*c"], ["2026", "%EY"], ["04", "%Od"], ["5", "%Q"], ["2026 ", "%Y"], ["", "%Y"], ["", ""],
["abc", ""], ["2026", "%"], ["2026", "%Y%"], ["2026", "%q"], ["%q", "%q"]].each { |s, f| sp(s, f) }
+# odd rows for the C# walk over ASCII-only strings (Src/Libraries/Date/DateStrptime.cs) and the
+# cases it leaves to format.rb (another encoding, a number past a long)
+[["EST5", "%Z"], ["EST DST", "%Z"], ["est dst5", "%Z"], ["est dstx", "%Z"], ["Central Daylight Time", "%Z"],
+ ["a.b standard time!", "%Z"], ["x standard timex", "%Z"], ["utc+09:30:15", "%Z"], ["UT-3", "%Z"], ["gmt", "%Z"],
+ ["gmtx", "%Z"], ["Z", "%z"], ["xyz", "%Z"], ["+5.5", "%z"], ["+09,30", "%z"], ["+", "%z"], ["UTC_", "%Z"],
+ ["9", "%Ez"], ["x", "%E"], ["x", "%O"], [":", "%:"], ["+09:00:00", "%:::z"], ["+0900", "%::::z"],
+ ["20260304", "%Y%m%d"], ["2026030405", "%Y%m%d%H"], ["1" * 30, "%Y"], ["-" + "9" * 20, "%s"], ["9" * 25, "%Q"],
+ ["12345678901234567", "%Y"], ["-5", "%L"], ["+5", "%N"], ["123456789012", "%N"], ["123456789012", "%N "],
+ ["-", "%s"], ["+", "%Y"], ["5 pmx", "%I %p"], ["5 p.m", "%I %p"], ["5 PM", "%H %p"], ["12 am", "%I %p"],
+ ["12 pm 3 am", "%I %p %I %p"], ["1926", "%C%y"], ["2619", "%y%C"], ["99 5", "%g %y"], ["a\vb", "a b"],
+ ["a \t\n b", "a b"], ["2026-03", "%Y-%m-%d"], ["Wednesday", "%a"], ["wedn", "%A"], ["Septem", "%B"],
+ ["2026 xx", "%Y"], ["2026", "%Y %"], ["2026 %", "%Y %%"], ["10 5", "%U %W"], ["2026", "%EC%Ey"],
+ ["3 7", "%Ou %OV"], ["2026é", "%Y"], ["é2026", "é%Y"], ["2026", "%Y é"]].each { |s, f| sp(s, f) }
+row("_strptime binary leftover") { h = Date._strptime("2026 xx".b, "%Y"); [h, h[:leftover].encoding] }
+row("_strptime binary zone") { h = Date._strptime("UTC".b, "%Z"); [h, h[:zone].encoding] }
+row("_strptime us-ascii zone") { h = Date._strptime("UTC".encode("US-ASCII"), "%Z"); [h, h[:zone].encoding] }
+row("_strptime utf-16") { Date._strptime("2026".encode("UTF-16LE"), "%Y") }
+StrptimeSub = Class.new(String) # one class for all the runs: the row compares their inspect
+row("_strptime subclass") { h = Date._strptime(StrptimeSub.new("2026 x"), "%Y"); [h, h[:leftover].class] }
+row("_strptime frozen") { Date._strptime("2026".freeze, "%Y".freeze) }
+row("_strptime int") { Date._strptime(2026, "%Y") }
+row("_strptime nil fmt") { Date._strptime("2026", nil) }
+row("_strptime fraction") { Date._strptime("1.5", "%s.%N")[:sec_fraction].class }
+row("Time.strptime L") { Time.strptime("2026-03-04 05:06:07.5 +0900", "%Y-%m-%d %H:%M:%S.%L %z").inspect }
+row("Time.strptime Q") { Time.strptime("1700000000123", "%Q").utc.inspect }
+row("Time.strptime zone name") { Time.strptime("2026-03-04 05:06:07 PST", "%Y-%m-%d %H:%M:%S %Z").utc.inspect }
+row("Time.strptime bad zone") { Time.strptime("2026-03-04 05:06:07 xyz", "%Y-%m-%d %H:%M:%S %Z").utc.inspect }
+row("Time.strptime bad mday") { Time.strptime("2026-02-31", "%Y-%m-%d").inspect }
+row("Time.strptime huge year") { Time.strptime("123456789012345678901234", "%Y").year }
+
row("_strptime default") { Date._strptime("2026-03-04") }
row("DateTime._strptime default") { DateTime._strptime("2026-03-04T05:06:07+09:00") }
row("Date.strptime") { Date.strptime("2026-03-04", "%Y-%m-%d").to_s }
diff --git a/Util/value-object-matrix.rb b/Util/value-object-matrix.rb
index dcdaa6925..9bb232b37 100644
--- a/Util/value-object-matrix.rb
+++ b/Util/value-object-matrix.rb
@@ -359,6 +359,77 @@ def initialize(w:, h:); super(w: w, h: h, area: w * h); end
(ObjectSpace.undefine_finalizer(Object.new).class rescue "#{$!.class}")
(ObjectSpace.each_object(Class).class rescue "#{$!.class}")
(ObjectSpace.garbage_collect.class rescue "#{$!.class}")
+ # --- Data.new / #with made directly (KernelOps.DataNew, DataWith) and when they are not
+ M.new(1, "kg")
+ M.new(amount: 1, unit: "kg").frozen?
+ M.new("amount" => 1, "unit" => "kg")
+ (M.new(1) rescue "#{$!.class}: #{$!.message}")
+ (M.new(amount: 1) rescue "#{$!.class}: #{$!.message}")
+ (M.new(amount: 1, unit: 2, x: 3) rescue "#{$!.class}: #{$!.message}")
+ (M.new(1, 2, 3) rescue "#{$!.class}: #{$!.message}")
+ (M.new(1, unit: 2) rescue "#{$!.class}: #{$!.message}")
+ M.new(*[1, 2], **{})
+ E0.new.frozen?
+ E0.new.instance_variables
+ M.new(1, 2).instance_variables
+ SUB.new(1, 2)
+ ($trace = nil; OVER.new(1, 2); $trace)
+ ($trace = nil; OVER.new(1, 2).with(unit: 3); $trace)
+ AREA.new(w: 2, h: 3)
+ AREA.new(w: 2, h: 3).with(w: 4)
+ (AREA.new(w: 2, h: 3).with(area: 1) rescue "#{$!.class}: #{$!.message}")
+ M.new(1, 2).with(unit: 3)
+ M.new(1, 2).with
+ M.new(1, 2).with("unit" => 4)
+ (M.new(1, 2).with(foo: 4) rescue "#{$!.class}: #{$!.message}")
+ (M.new(1, 2).with(1) rescue "#{$!.class}: #{$!.message}")
+ (M.new(1, 2).with({unit: 4}) rescue "#{$!.class}: #{$!.message}")
+ (m = M.new(1, 2); m.with(unit: 3).equal?(m))
+ (m = M.new(1, 2); m.with(amount: 1, unit: 2).equal?(m))
+ Class.new(M).new(1, 2).class.superclass
+ (c = Class.new(M); c.new(1, 2).with(unit: 5).class == c)
+ (m = M.new(1, 2); m.singleton_class; m.with(unit: 3).singleton_methods)
+ (o = Data.define(:a) { def self.allocate = raise("no") }; o.new(1).a)
+ (o = Data.define(:a) { def freeze = raise("no") }; o.new(1).frozen?)
+ (o = Data.define(:a); o.new(1).method(:a).arity)
+ (o = Data.define(:a); o.instance_method(:a).parameters)
+ (o = Data.define(:a); [o.public_method_defined?(:a), o.instance_method(:a).owner == o])
+ (o = Data.define(:a) { def a = super * 2 }; o.new(4).a rescue $!.class)
+ (o = Data.define(:a); m = o.new(5); m.instance_variable_get(:@a))
+ # hot loops with the class changed half way: initialize, the reader, a prepended initialize
+ (o = Data.define(:a); (1..300).map { |i| o.class_eval { def initialize(a:) = super(a: a * 10) } if i == 150; o.new(i).a }.sum)
+ (o = Data.define(:a); (1..300).map { |i| o.class_eval { def initialize(**kw) = super(a: 0) } if i == 150; o.new(a: i).with(a: 1).a }.sum)
+ (o = Data.define(:a); (1..300).map { |i| o.class_eval { def a = 7 } if i == 150; o.new(i).a }.sum)
+ (o = Data.define(:a); (1..300).map { |i| o.prepend(Module.new { def initialize(a:) = super(a: -a) }) if i == 150; o.new(i).a }.sum)
+ (o = Data.define(:a); (1..300).map { |i| o.class_eval { remove_method :a } if i == 150; (o.new(i).a rescue 1) }.sum)
+ # --- Array#sum folding something that is not a number (Array#__sum_tail__)
+ [M.new(1, 2), M.new(3, 4)].sum([])
+ %w[a b c].sum("")
+ [[1], [2]].sum([0])
+ [1, 2].sum(Rational(1, 2)) { |x| x * 0.5 }
+ ([1, "a"].sum(0) rescue "#{$!.class}: #{$!.message}")
+ ([0.1] * 10).sum
+ ([0.1] * 10).sum(0) { |x| x }
+ (t = Struct.new(:v) { def +(o) = v + (o.respond_to?(:v) ? o.v : o) }; [t.new(1), 1e100, 1.0, -1e100].sum(0) rescue $!.class)
+ (t = Struct.new(:v) { def +(o) = v + (o.respond_to?(:v) ? o.v : o) }; [t.new(1), 1e100, 1.0, -1e100].sum(0) { |x| x } rescue $!.class)
+ (t = Struct.new(:v) { def +(o) = v + (o.respond_to?(:v) ? o.v : o) }; [3, t.new(1), 0.1, t.new(2), 0.2, 0.3].sum(0) rescue $!.class)
+ (t = Struct.new(:v) { def +(o) = self.class.new(v + (o.respond_to?(:v) ? o.v : o)) }; [1, 2, 0.5].sum(t.new(0)).v)
+ (t = Struct.new(:v) { def +(o) = self.class.new(v + (o.respond_to?(:v) ? o.v : o)) }; (1..300).map { |i| t.class_eval { def +(o) = 1 } if i == 150; [1, 2].sum(t.new(0)) { |x| x }.then { |r| r.is_a?(t) ? r.v : r } }.sum)
+ (["a", 1.5].sum(0.0) rescue "#{$!.class}: #{$!.message}")
+ ([1, 1.5, "a"].sum(M.new(0, 0)) { |x| x } rescue "#{$!.class}: #{$!.message}")
+ (t = Struct.new(:v) { def +(o) = v + o }; [2, 0.1, 0.2, 0.3].sum(t.new(1)) { |x| x })
+ (t = Struct.new(:v) { def +(o) = v + o }; [2, 1e100, 1.0, -1e100].sum(t.new(1)))
+ (t = Struct.new(:v) { def +(o) = v + o }; [1e100, 1.0, -1e100, 3].sum(t.new(1.5)) { |x| x })
+ (t = Struct.new(:v) { def +(o) = v + o }; [1r / 3, 0.1, 2].sum(t.new(1)))
+ # a Rational before the first Float is added exactly, and the Floats after it are compensated
+ [Rational(1, 1), 1e100, 1.0, -1e100].sum(0) { |x| x }
+ [Rational(1, 1), 1e100, 1.0, -1e100].sum
+ [1, Rational(1, 3), 1e100, 1.0, -1e100].sum
+ [Rational(1, 3), Rational(2, 3), 1].sum
+ (1..300).map { |i| [Rational(i, 7), 1e100, 1.0, -1e100].sum }.uniq.size
+ # --- a Data#initialize redefined on Data itself: Data.new and #with call it (last: it stays redefined)
+ (class Data; alias_method :__vom_init, :initialize; def initialize(**kw) = __vom_init(**kw.transform_values { _1 * 10 }); end; o = Data.define(:a); [o.new(a: 2).a, o.new(3).a, o.new(a: 1).with(a: 4).a])
+ (o = Data.define(:a, :b); (1..300).map { |i| o.new(i, 1).with(b: 2).b }.sum)
RUBY
eval(PRELUDE, TOPLEVEL_BINDING)