Skip to content

Align IronRuby with Ruby 4.0 behavior: core class fixes, CI prism pin, loader fix - #23

Merged
Largo merged 20 commits into
masterfrom
claude/ironruby-bugs-improvements-0lxw5o
Oct 26, 2026
Merged

Largo merged 20 commits into
masterfrom
claude/ironruby-bugs-improvements-0lxw5o

Conversation

@Largo

@Largo Largo commented Oct 26, 2026 •

Copy link
Copy Markdown
Owner

This PR brings IronRuby closer to Ruby 4.0, the project's compatibility target, through behavioral fixes across the core classes and runtime, found by running probe scripts on IronRuby and CRuby side by side and by ruby/spec. It also merges master (the speedup merge, PR #22) and repairs two things that merge left broken.

Compatibility target

The target is Ruby 4.0: where IronRuby and CRuby 4.0 differ, IronRuby is changed. The README now says so in the intro and in the Status section. Where ruby/spec and CRuby 4.0 disagreed with Ruby 3.x habits (beginless Range#max, (nil..nil).include?, Range#step without eager to_int, Float("1.")), the 4.0 answer won.

After the merge of master

  • CI: every build-and-test job, on master too, failed in the smoke test with Unknown prism node type: 228. ci.yml checked out ruby/prism's main, which has since moved to a post-order serialization with a checksum (ruby/prism ab92f0eb4, 01c1960e8) that the C# loader does not read. Both workflows now pin PRISM_REF to cd76b0d1, the revision Src/Prism/Generated was generated from and release.yml already pinned. Following prism's new format is a separate change.
  • Prism loader: the committed PrismLoader.Generated.cs skimmed a SymbolNode's content_loc as optional, one byte off from libprism; with lazy method bodies every required file whose method body has a symbol followed by more statements failed to load, which took the whole mspec harness down locally (CI regenerates the file and never saw it). Regenerated from prism cd76b0d1.
  • Thread#backtrace / #backtrace_locations / .each_caller_location: counted a Kernel#send frame that master's direct send(:literal) call no longer leaves; five spec/core/thread failures.
  • Struct#initialize: master's C# fast path now hands the slow path the positional values and the keywords apart, so a Hash passed as a member value is told from keywords; the frozen check comes first, as MRI's rb_struct_modify.

Key changes

Pattern matching & error handling

  • NoMatchingPatternError reasons and messages formatted as MRI formats them
  • NoMethodError#private_call?, method_missing told whether the call was private
  • Exception#to_s through to_str, full_message(highlight: nil), anonymous class names in comparison errors, Errno messages no longer doubled

Numeric

  • Float#round for large negative and large positive digit counts (exact rational rounding), Float#-@ keeps the sign of zero
  • Integer#** with huge exponents raises ArgumentError, Range#sum in closed form for Integer ranges
  • Math.cbrt, gamma, lgamma, erf, erfc from the C library, with MRI's glibc cbrt correction and factorial table

String formatting

  • sprintf: flags after width or precision rejected, numbered vs unnumbered argument mixing reported as MRI does, binary %c RangeError, ASCII-incompatible encodings, result encoding tracking, dtoa-style tie breaking

Array, Hash, Struct, Data

  • Array#fill as one dispatcher, #sample(nil), #zip with a shrinking receiver, #replace on a frozen array, #combination without a size, index overflow as IndexError / NoMemoryError, merge sort operand order
  • Hash#each/delete_if/replace iteration guards ("can't add a new key into hash during iteration"), identity hashes for fixnums and flonums, Hash#eql?, default_proc=
  • Struct keyword and positional forms, getter arity, frozen re-initialization, recursive inspect; Data copies and member checks; Marshal member validation

Range and Enumerator

  • Beginless/endless first, last, max, include?, reverse_each, step, inspect encoding, marshaling, initialize_copy, to_enum sizes, Enumerator#initialize_copy, lazy each_with_object

Time, IO, Proc, Kernel

  • Time from NaN/Infinity raises FloatDomainError, string components through Integer()
  • IO#set_encodings on a closed stream, Kernel#display(port), Proc.new argument checks

Tests

  • New harness cases: Float_Format1, Array_Struct_Misc1, Hash_Range_Misc1, Exception_Proc_Misc1. The C# suite passes with 0 failures; the ruby/spec suites for the touched classes pass, apart from the known fixnum_max helper errors.

https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3

claude added 15 commits October 25, 2026 22:02
…ivergences

Call sites: a site that forwards a block argument (x.count(&b)) was bound
once with b nil, which picks a library overload without a BlockParam, and the
rule carried no test for that. The same site then kept that overload when a
real block came through it, so `def c(x, &b) = x.count(&b)` counted every
element whatever the block said, `each(&b)` returned an Enumerator and
`inject(&b)` raised; Range#count, which reaches Enumerable#count through
super, ignored its block once any Range#count had run without one. The rule
now tests that the block is nil.

Hash: deleting a key from inside #each surfaced a KeyNotFoundException
(the key list was copied, the value looked up through the throwing indexer).
#each, #each_key, #each_value, #delete_if and #reject! now skip entries the
block deleted, and adding a key while a hash is being iterated raises MRI's
"can't add a new key into hash during iteration" (an iteration level on the
Hash, as RHASH_ITER_LEV).

sprintf: CRuby's dtoa treats a remainder it cannot tell from one half in
double arithmetic as a tie and settles it by the parity of the last digit,
so "%.2f" % 2.675 is 2.68 and "%.1f" % 99.45 is 99.4; the formatter now runs
the same fast-path steps and rounds the same way, and "%g" keeps the trailing
zero dtoa leaves on such a value. The decimal exponent is computed exactly
(Math.Log10 put 999.9999999999999 at 1.000000000000000e+03). "%f" of a
Rational is exact and rounds half up as sprintf.c does, and "%c" of a code
point no character has is an ArgumentError. 80,000 random renderings now
match CRuby byte for byte.

Float#-@ negates the sign bit: -(0.0) was 0.0 through Numeric#-@.

Math: gamma, lgamma, erf and erfc come from the C library (libm, libSystem,
ucrtbase) when it can be found, as MRI's do, with the DLR's series
approximations as the fallback; whole-number gamma uses MRI's factorial
table; cbrt is the C library's with the Newton step MRI applies on glibc.

Method listings: Module#instance_methods(false) listed a prepended module's
methods and, on a singleton class, the methods of the class behind it;
Kernel#public_methods(false) and friends keep MRI's walk through the
singleton class into the object's class. Method#inspect shows the parameter
list of library methods and attribute accessors, rule-generator methods
(Class#new, Kernel#send) have arity -1.

Also: Time#strftime accepts the %E and %O modifiers, prints %:::z with only
the fields that are not zero, drops seconds from %z, and raises on a lone
trailing %; Enumerator::Lazy#+ stays lazy; blockless #find_index, #find,
#take_while and #each_line enumerators report no size; Hash#default_proc=
raises MRI's message; Encoding marshals by name.

Regression tests for each in IronRuby.Tests; Method#inspect expectations
there updated for the parameter lists.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…le results, StringIO nil

Pattern matching: a failed `=>` or `case/in` said only what the subject was.
MRI's message says why: "[1, 2, 3]: [1, 2, 3] length mismatch (given 3,
expected 2)", "{a: 1}: String === 1 does not return true", "1: 1 does not
respond to #deconstruct", "rest of {b: 2} is not empty", "guard clause does
not return true", "[1, 2] does not match to find pattern". The prism bridge
now records the reason of the test that failed last, in a temp alongside the
missing-key one, and the error is built from it. minitest's own suite checks
these messages, and now passes.

Errno: a message built with the error's own text in it was prefixed with it
again, "No such file or directory - No such file or directory - path".

Thread::Mutex#sleep and ConditionVariable#wait answer the seconds slept, or
nil when the timeout ran out, as MRI's do, instead of 0 and the condition
variable; Mutex, Queue, SizedQueue and ConditionVariable inspect as Ruby
objects rather than by their CLR type name.

StringIO#write(nil) wrote "" in MRI and raised here; #truncate answers 0.
Fiber#backtrace and #backtrace_locations, GC.latest_gc_info added.

The doubled Errno text came from two places: RubyExceptions.MakeMessage
prefixing a message that already carried the error's text, and a C#-thrown
SystemCallError being re-initialized through the prelude's
SystemCallError#initialize with its composed message as the detail. Both are
fixed, and File.open names the path for a missing directory on the way to a
file (ENOENT) or a file standing where a directory should be (ENOTDIR),
rather than quoting the CLR's message.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…Error text, Float#eql?

- Bignum arithmetic with a Float ((10**400) * 1.0, + 1.0, / 10.0, fdiv, **)
  raised System::OverflowException because the operand was converted with
  BigInteger.ToFloat64, which throws past Double.MaxValue.  Every such site
  now uses Protocols.ToDouble, which answers a signed Infinity as MRI's
  big2dbl does; the "Integer out of Float range" warning is verbose-only,
  like rb_warning.
- Integer ** Bignum (2 ** (2**70)) failed with AmbiguousMatchException: the
  binder could not choose between the Bignum and the coercing overloads for
  a Fixnum receiver.  A Fixnum/Bignum overload delegates to the Bignum one,
  so 1, -1 and 0 have their answers and anything else is ArgumentError
  "exponent is too large" (MRI 3.4+).
- ZeroDivisionError raised by integer division carried the CLR's
  "Attempted to divide by zero."; it now reads "divided by 0".  The legacy
  Rational#/ said "division by zero" for the same case.
- Float#eql? went through Object#eql? and so Double.Equals, which considers
  NaN equal to itself; Float#eql? is now false for NaN and true only for a
  Float of the same value.
- "comparison of X with Y failed" printed an empty name for an anonymous
  class on either side; it now prints #<Class:0x...> as MRI does.
  Comparable#clamp(min, max) reports a failed min <=> max the same way.
- Complex#/ and #quo canonicalize an exact whole quotient to an Integer, so
  Complex(1, 2) / 2 is ((1/2)+1i) rather than ((1/2)+(1/1)*i).
- -1.times.size is 0, not -1.

Tests: Numeric_BignumFloatOverflow1, Numeric_BignumExponent1, Float_Eql1,
ComparisonError_AnonymousClass1.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…latten(nil)

String:
- "a\xFF".b.succ answered "b\x00": in a binary string the 0xFF byte read as
  the Latin-1 letter y-umlaut and was stepped with a carry.  Only ASCII
  letters and digits count in a binary string, so the answer is "b\xFF".
- #dump of a string in an ASCII-incompatible encoding writes
  ".dup.force_encoding(...)" as MRI does, and #undump accepts that form.
- #undump of "...".force_encoding("...") that contains a \u escape is a
  RuntimeError ("dumped string contained Unicode escape but used
  force_encoding"), as in MRI.
- #tr, #tr!, #tr_s and #tr_s! raise ArgumentError on a receiver with a broken
  encoding, before looking at the character sets.
- #count, #delete and #delete! without arguments report
  "wrong number of arguments (given 0, expected 1+)".

Enumerator:
- Enumerator.new without a block is "tried to create Proc object without a
  block"; more than one argument is an arity error; the size argument is
  converted with to_int (a String is a TypeError, 1.5 is 1) while nil, a
  callable and Float::INFINITY stand, as MRI's convert_to_feasible_size_value.
- #each with arguments on a generator-based enumerator passes them to the
  block after the yielder (and without a block answers a new enumerator)
  instead of failing with "undefined method `each' for nil".
- #inspect names the source and method for enumerators the prelude builds
  from a generator: with_index, with_object, each_with_index, cycle,
  permutation and combination, Enumerator.produce, every Enumerator::Lazy
  chain (#<Enumerator::Lazy: #<Enumerator::Lazy: 1..3>:map>) and
  Enumerator.new itself, where "#<Enumerator: generator>" and
  "#<Enumerator::Lazy: ...>" said nothing about the enumerator.
- Enumerator::Yielder.new without a block is a LocalJumpError and a yielder
  inspects without its instance variables.
- -1.times.size is 0.

Array#flatten(nil) and #flatten!(nil) flatten fully instead of raising
TypeError.  "unknown keyword: :foo" is singular for one unknown keyword.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…, Proc, Struct, Data, Time and error-message fixes

Backtraces (Build/dlr-patches/0004):
- An exception raised inside a rescue or ensure clause had a backtrace missing
  every frame from the rescuing frame outwards, and at the top level the
  backtrace was empty: the DLR interpreter runs a handler's instructions inside
  Interpreter.HandleException, which the stack-trace builder did not recognise
  as an interpreted frame.  The new DLR patch counts it as one.

Exception:
- #full_message prints a cause that has no backtrace at the same position as
  the exception, never prints a cause twice (a #cause override answering self
  overflowed the stack), uses the raise-recorded cause rather than a #cause
  override, and raises TypeError for a #backtrace that is not an Array of
  Strings instead of swallowing it.  #detailed_message is built from #message
  (so an overriding #message shows), drops a lone trailing newline, leaves
  empty lines unhighlighted and ignores a class's #name override.
- raise Klass, msg, 1 and #set_backtrace(1) are "backtrace must be Array of
  String".
- UncaughtThrowError.new(tag, value, message = nil) exists (the message is a
  format string for the tag, as in MRI); a C#-thrown exception whose class has a
  library constructor is no longer re-created through Ruby-level new, which
  would have lost its tag and value.

Hash:
- Hash#values_at answers the default for a missing key (Hash.new(5).values_at(:x)
  is [5]), as #[] does, instead of nil.
- #rehash during iteration is "rehash during iteration".
- Hash.new refuses a lambda default proc of the wrong arity ("default_proc takes
  two arguments (2 for 1)") and a non-Integer capacity:, like MRI.

Proc and Method:
- A lambda's arity error gives the positional bounds exactly ("expected 1..2"
  for |a, b = 1|, where the arity alone could only say "1+"), checks the upper
  bound, and names the required keywords as MRI does ("expected 1; required
  keyword: b").  A symbol proc keeps its own "no receiver given".
- UnboundMethod#bind names an anonymous class in its error.

Struct and Data:
- Struct#initialize tells keywords from a Hash argument: Struct.new(:a, :b).new({a: 1})
  is [{a: 1}, nil] and .new(1, b: 2) is [1, {b: 2}], while keyword_init: true
  still takes the keywords as one Hash.  "unknown keywords:" keeps MRI's wording;
  Struct.new(:a, foo: 1) is "unknown keyword: :foo"; a keyword_init: true class
  inspects as #<Class:0x...>(keyword_init: true).
- Struct#[] says "offset 1 too large for struct(size:1)" (it said too small, and
  spelt struct with a space).
- Data.define rejects a setter-like member ("invalid data member: x=") and reports
  fewer keywords than members as missing ones and otherwise unknown ones, in MRI's
  order; Data.new is undefined.

Time:
- Time.new(string) is parsed by hand the way MRI's time_init_parse does: "UTC"
  is a zone, and the messages name what is wrong ("missing sec part: 03:04",
  "missing min part: 03", "subsecond expected after dot: 03:04:05.", "year must
  be 4 or more digits: 24", "two digits mon is expected after '-': -1-2",
  "can't parse at: x", trailing whitespace is "can't parse").
- Broken-down components: hour 24 only with 00:00, month 0 and day 0 are
  "mon out of range" / "mday out of range", a String second is converted like
  Integer() ("1.5" is an error, not 1).
- Time#round/floor/ceil refuse a negative ndigits ("negative ndigits given")
  and a String; #round rounds a half up (Time.at(-1.5).round is -1).
- Time.now/at/new reject an unknown keyword (Time.new still takes precision:);
  a date without a time of day ("2020-12-25") is "no time information";
  "fraction min is not supported: 00:56."; an Infinity or NaN is a
  FloatDomainError; an instant outside the representable range is a RangeError
  ("time ... out of Time range") where it used to escape as a CLR
  OverflowException, and "time + x out of Time range" no longer prints as an
  ArgumentOutOfRangeException parameter name.

Errors:
- NoMethodError on an object with a singleton class is spelled by the default
  #to_s ("#<Object:0x...>") and never by the object's own #inspect; the
  top-level object is "main"; an anonymous class shows how it inspects.
- const_get("Foo::") is "wrong constant name Foo::", "Math::PI::X does not refer
  to class/module" names the whole path, remove_const(:foo) is "'foo' is not
  allowed as a constant variable name", and a constant missing from the
  singleton class of a plain object is "uninitialized constant Foo".
- ("a".."e").step(-1) is "step can't be negative"; 1.step(10, "a") inspects as
  #<Enumerator: 1:step(10, "a")>.

Odds and ends:
- Enumerator#dup and #clone of a method-based enumerator kept no target and
  failed with "undefined method `each' for nil".
- Float no longer includes the Ruby 1.8 Precision module (Float.ancestors is
  [Float, Numeric, Comparable, ...]).
- $-W answers the warning level (0, 1 or 2) and is read-only.

Tests: Hash_ValuesAtDefault1, Lambda_ArityMessages1, ErrorMessages_Receivers1,
Time_StringParsing1, Struct_IndexMessages1, Backtrace_RaiseInRescue1, Enumerator_Copy1.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…ultibyte text, nil limits, $~ from str[/re/]=, error messages

Found by running an IO/File/Dir and a StringIO/IO probe script on
CRuby 3.3 and IronRuby and comparing the outputs row by row.

Reading:
- IO#gets/readline/each_line/readlines with a nil separator and a byte
  limit split a multibyte character: gets(nil, 1) on "é" answered "\xC3".
  The limit is now relaxed while the last character is incomplete (by 16
  bytes at most, as in io.c); StringIO#gets(limit) does the same.
- A nil limit (gets(nil, nil), gets("", nil), readlines("", nil),
  each_line(nil, nil), readline(sep, nil)) raised a TypeError instead of
  meaning "no limit".
- StringIO#read with no length tagged the result BINARY; only a read of
  so many bytes does that, the rest of the string keeps its encoding.
- IO#codepoints (removed in Ruby 3.0) was still defined.
- IO#binmode? on a closed stream answered true once #binmode had been
  called on it; it raises IOError "closed stream".

Writing:
- IO#print wrote "nil" for a nil argument; it writes "" like to_s does.
- IO#putc with a String wrote its first byte, so putc("é") produced an
  invalid character; it writes the first character, and an empty string
  writes nothing instead of raising TypeError. putc(nil) says "no implicit
  conversion from nil to integer".
- "$, is set to non-nil value" (Array#join, IO#print) and "$; is set to
  non-nil value" are :deprecated-category warnings, hidden by default.
- "syswrite for buffered IO" and "sysseek for buffered IO" go through the
  runtime's warning sink, so they carry "file:line: warning: ".

Opening:
- A mode string and a textmode:/binmode: option that disagree raise
  "both textmode and binmode specified"; only repeating one is "specified
  twice".
- invalid:, undef: and newline: are validated when the stream opens
  ("unknown value for invalid character option", "unexpected value for
  newline option: bogus"), not on the first transcoding that needs them.
- IO#set_encoding with an unknown encoding name warns "Unsupported
  encoding X ignored" like a mode string does instead of raising, and
  raises IOError on a closed stream.
- File#inspect of a File made from a descriptor shows "#<File:fd 1>".

Errors name the path, as MRI's do:
- seek, pos=, sysseek, File#truncate, File.truncate and File.write with
  an offset: "Invalid argument - path"; a bad whence is Errno::EINVAL too.
  Errno::ESPIPE from a pipe no longer reads "Illegal seek - Illegal seek".
- File.rename, File.link, File.symlink: "No such file or directory -
  (old, new)"; an existing link target is named by its own path.
- Dir.new/Dir.entries/Dir.children on a file: Errno::ENOTDIR "Not a
  directory - path" instead of ENOENT. Dir.mkdir("a/b/c") with a missing
  parent names "a/b/c", not the parent.
- File#truncate checks writability first (IOError "not opened for
  writing"), IO#sysread(-1) says "negative string size (or size too
  big)", IO#pread with a negative offset names the file, and
  IO#advise's TypeError is "advice must be a Symbol".

Conversions:
- Array.new(nil) raised "no implicit conversion of nil into Object";
  Array#sample(nil) answered an element instead of raising TypeError;
  Integer#digits(nil) said "NilClass".

Regexp and MatchData (from a Regexp/MatchData/Symbol probe):
- str[/re/] = s and str[/re/, n] = s now set $~ like every other match,
  and take a capture name: str[/(?<n>b)/, "n"] = s, str[/(?<n>b)/, :n] = s.
- $+ answered the whole match for a pattern without groups; it is nil.
- "abc".sub(/b/) with neither a replacement nor a block raised "tried to
  create Proc object without a block" instead of the arity error.
- MatchData#match(n) answered nil for an index or a name the match does
  not have; it raises IndexError ("index 5 out of matches", "undefined
  group name reference: x"). Equal matches now hash alike.
- Regexp.new(nil) said "no implicit conversion of nil into Regexp";
  Regexp.new("\xC3") (invalid in its encoding) compiled instead of
  raising RegexpError "invalid multibyte character: /\xC3/";
  Regexp.escape left a vertical tab unescaped.
- Symbol#clone(freeze: false) answered the symbol; it raises
  ArgumentError "can't unfreeze Symbol".

Tests: Io_Messages1 in IronRuby.Tests covers the reading, option and
message changes that do not need the prelude.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…ative ordinals, scrub runs, self references and anonymous classes in Marshal

Encoding and strings
--------------------
Found by comparing an Encoding/String probe script between CRuby 3.3
and IronRuby, plus two ruby/spec Kernel#warn failures.

- A String whose undecodable bytes had been through a character
  operation (#reverse, #center, #succ, downcase(:ascii), ...) inspected
  them as "\u{dcff}", the escape surrogate they are held as; #inspect and
  #dump now show the byte itself ("\xFF").
- String#ord in an encoding that is not Unicode answered the Unicode code
  point ("\x81\x40" in Shift_JIS gave 12288); it answers the character's
  own code (0x8140), and 0x80 in Windows-1252 is 128, not 8364.
- String#casecmp and #casecmp? compared strings in incompatible
  encodings (UTF-8 against UTF-16LE) instead of answering nil; two empty
  strings in different encodings still compare.
- String#upcase/#downcase/#capitalize/#swapcase on a string with bytes
  that are not valid in its encoding mapped around them; MRI raises
  ArgumentError "input string invalid" (the :ascii mapping still works).
- String#scrub: a run of bytes was treated as one broken character
  whenever its first byte was 0xF0 or above, so "\xFF\xFE" became one
  replacement instead of two, and an encoded surrogate ("\xED\xA0\x80")
  one instead of three; the run now has to stay a valid prefix of a
  character. The default replacement for UTF-16 and UTF-32 strings is
  U+FFFD in that encoding rather than a UTF-8 "?" (which raised
  Encoding::CompatibilityError), a replacement in an incompatible
  encoding raises Encoding::CompatibilityError, and a block answering
  an invalid string raises ArgumentError like an invalid argument does.
- "".encode("UTF-16") produced a byte order mark for an empty string;
  str.encode(to, nil) raised instead of ignoring the nil source encoding.
- Encoding.find(nil) said "no implicit conversion of nil into Encoding"
  (now "into String"); Encoding objects answer frozen? with true;
  Encoding.new is undefined; Encoding::Converter#== compares the
  conversion path.
- Time#strftime with a format in a non-ASCII-compatible encoding raises
  ArgumentError "format should have ASCII compatible encoding".
- Kernel#warn bound to the Warning module (the escape hatch MRI uses so
  that a Warning#warn override calling super does not recurse) wrote
  through the built-in warn, which itself routes to Warning.warn, so the
  override was called anyway and `module Warning; def warn(*) super end`
  recursed. It now writes to $stderr directly.

Tests: Encoding_Misc1 in IronRuby.Tests.

Marshal, pack and format
------------------------
Found by comparing a format/pack/Marshal probe script between CRuby
and IronRuby.

Marshal.dump:
- A class object with instance variables (every Struct class, which
  keeps its keyword_init flag in one) was written with an 'I' wrapper and
  the variables; a 'c' or 'm' record never carries them.
- Dumping an instance of an anonymous class, or of an anonymous subclass
  of String/Array/Hash, failed with a CLR ArgumentNullException; it is
  TypeError "can't dump anonymous class #<Class:0x...>".
- marshal_dump and _dump are now found through respond_to? too, so an
  object that provides them through method_missing is dumped that way
  instead of being refused for its singleton methods.
- marshal_dump answering an instance of the object's own class (self,
  typically) wrote a self-reference that could never be loaded; it raises
  RuntimeError "X#marshal_dump returned same class instance".
- /a/n is written with MRI's ARG_ENCODING_NONE bit (0x20), and read back
  as /n.

Marshal.load:
- An 'o' record is entered in the link table before its instance
  variables are read, so an object that refers to itself (@A = self)
  loads with the reference pointing at itself rather than at a copy.
- A float record is read the way strtod reads it: the longest numeric
  prefix, and 0.0 when there is none ("1e" is 1.0, "a" is 0.0), instead of
  raising ArgumentError.
- A regexp record with unknown option bits raised NullReferenceException;
  the bits are masked off.
- A negative array length raises ArgumentError "negative array size (or
  size too big)" instead of answering [].
- The proc argument may be anything that answers #call, not only a Proc;
  the source may be anything with #to_str, and an object that is not a
  String has to answer both #getbyte and #read before it counts as an
  IO ("instance of IO needed").
- Messages: "class X needs to have method `_load'", "instance of X needs
  to have method `marshal_load'", "X does not refer to class/module",
  "struct X not compatible (:b for :a)" and "(struct size differs)".

Array#pack and format:
- [Float::NAN].pack("e") wrote the CLR's NaN, whose sign bit is set;
  MRI packs the positive quiet NaN (0x7FC00000 / 0x7FF8...).
- pack(fmt, buffer: nil) is no buffer; an unknown keyword raises
  ArgumentError "unknown keyword: :bogus"; a format string in a
  non-ASCII-compatible encoding raises "ASCII incompatible encoding: X",
  as it does for format/sprintf/String#%.

Tests: Marshal_Misc1 in IronRuby.Tests.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…on, Proc composition arity, Symbol#to_proc identity, Regexp.escape test

- Hash#each, #each_key and #each_value looked every snapshotted key up
  again to see deletions and replacements made by the block, so an entry
  whose key hash had drifted since it was stored - a Hash used as its own
  key - was skipped, and such a hash inspected as "{}". MRI walks the
  table and visits it. The lookup now falls back to the snapshot while
  nothing has been deleted (the block may not add entries, so the count
  can only have dropped by a deletion).
- Set#flatten on a Set that contains itself answered a copy instead of
  raising ArgumentError "tried to flatten recursive Set" - a consequence
  of the above, since Set iterates its Hash.
- Hash#index (removed in Ruby 1.9) was still defined.
- (lambda << f).call(x) handed the lambda f's result without an arity
  check, so a two-parameter lambda composed with a function answering an
  array took it as two arguments instead of raising ArgumentError.
- Symbol#to_proc answers the same Proc for the same Symbol, as MRI's does
  (and &:sym no longer allocates a Proc per call).
- RegexEscape1 expected "\v" to be left alone by Regexp.escape; it is
  escaped as "\\v" (fd83fef).

Tests: Hash_SelfKey1 in IronRuby.Tests.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…Kernel conversion checks; Queue, Mutex and ThreadGroup details

Found by comparing a Kernel-conversion/Thread probe script between
CRuby and IronRuby.

Threads:
- Thread#join and #value on the current thread waited for ever; they
  raise ThreadError "Target thread must not be current thread", and
  joining the main thread from another thread raises "Target thread must
  not be main thread".
- Queue.new(nil) is an empty queue instead of a TypeError; Queue#pop with
  two positional arguments is an arity error instead of "no implicit
  conversion of Integer into Hash".
- Mutex#sleep("x") named the CLR type ("can't convert MutableString into
  time interval"); it names the Ruby class.
- ThreadGroup#inspect and #to_s answered the CLR type name
  "IronRuby.Builtins.ThreadGroup"; they answer "#<ThreadGroup:0x...>".
- Thread.critical and Thread.critical= (gone since Ruby 1.9) were still
  defined.

Kernel conversions:
- Integer(nil, 8) raises "base specified for non string value" (the
  base is checked before the value, as in MRI) instead of a TypeError.
- Integer and Float of a String in a non-ASCII-compatible encoding raise
  ArgumentError "ASCII incompatible encoding: UTF-16LE"; Float of a
  String with a NUL byte says "string for Float contains null byte".
- Integer(obj, exception: false) answers nil when obj's own #to_i raises,
  as MRI's rb_protect around the call makes it do.
- The "invalid value for Integer()" message spells control characters
  the way #inspect does ("12\u0000") instead of embedding them raw.
- String(BasicObject.new) raised NoMethodError for is_a?; it raises
  TypeError "can't convert BasicObject into String".

Tests: Thread_JoinSelf1 in IronRuby.Tests.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…thods; public_instance_method, BasicObject#initialize, Kernel#clone details

Found by comparing a Module/Method reflection probe script between
CRuby and IronRuby.

- `self&.m` (and `self&.m = v`) raised NoMethodError for a private m:
  the Prism bridge read self into a temporary for the nil check, and a
  call through a temporary has no right to a private method. self is
  never nil, so the call is made on self directly, as `self.m` is.
- Method#inspect of a class method looked up on a subclass said
  "Base.cm"; MRI says "Sub(Base).cm".
- Module#public_instance_method of a private or protected method said
  "undefined method"; it says "method `m' for class `C' is private".
- BasicObject#initialize (and Object#initialize) answered self through
  bind_call; they answer nil.
- Method.new and UnboundMethod.new are undefined, as in MRI.
- Kernel#clone takes `freeze:` as a keyword parameter (its #parameters
  are [[:key, :freeze]]) instead of an optional Hash.

Tests: Reflection_Misc1 in IronRuby.Tests.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…mits, with_index values, Range#step, Enumerator::Generator

ArithmeticSequence#first with a negative count raises ArgumentError
("attempt to take negative size") and #last on an endless sequence raises
RangeError instead of looping forever. The integer fast path of stepping is
used only when the limit is nil or an Integer, so (1..3.5).step(1) yields
Floats like MRI.

Lazy#with_index with a block passes the values through unchanged, and
Lazy#each_with_object is eager (returns the memo; an enumerator without a
block). Enumerator#with_index/#with_object yield every value of a
multi-value step. Enumerator.produce rescues StopIteration raised while
computing the first value.

Range#step checks its arity, follows Ruby 3.4 for non-numeric steps (they
are added with #+, so #coerce works, and no block means an Enumerator is
built regardless) and gives the generic enumerator and Lazy#to_enum the
inspect string of the call that made them.

Enumerator::Generator is defined: an Enumerable wrapping the block of
Enumerator.new, as MRI has it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…floor/ceil underflow, sprintf encoding tracking and error messages

Float#round with a positive precision treated every value below 2**-53 as
rounding to zero, so 1e-20.round(25) was 0.0; the underflow test now uses
MRI's digit estimate, and more than 14 digits round the exact value of the
double (rb_flo_round_by_rational) instead of going through an inexact power
of ten. Float#floor/#ceil/#truncate return a positive 0.0 for a value that
rounds away entirely and use MRI's neighbour check, so 2.1.floor(1) and
friends land on the right side. Float::MAX_10_EXP and MIN_10_EXP are
Integers.

sprintf: the first non-ASCII argument now fixes the result encoding even
when it agreed with the format's, which stops "%s %s" % ["あ", "\xFF".b]
from producing a binary string holding U+3042 (an uncatchable encoder
exception on inspect). A flag after the width or precision is an error, a
"%d" of an ASCII-incompatible string raises Encoding::CompatibilityError,
"%c" past 0xFF in a binary format is "N out of char range", sprintf with no
arguments is "too few arguments", and the numbered/named/unnumbered mixing
errors carry MRI's wording ("value given twice - 1$", "named<a> after
numbered", "numbered(1) after named", "named{b} after <a>").

Kernel#Integer/#Float raise Encoding::CompatibilityError for an
ASCII-incompatible string, and Float()'s "invalid value" message spells a
non-ASCII string out in its bytes, as MRI does.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…erand order, fill dispatch, Data copies and member checks

Array: a[2**31 - 1] = x overflowed the append count and tripped an assertion
(IndexError "index 2147483647 too big" now, as MRI); an allocation the CLR
refuses raises NoMemoryError, which is now the Ruby class for
System.OutOfMemoryException, instead of a bare CLR exception. #sort compares
the earlier element against the later one, so [1, "a"].sort and
[1, nil].max fail with MRI's operand order and wording (the receiver is
always named by class, a Bignum too). #fill is one method dispatching by
hand: the Integer- and Object-typed overloads were ambiguous when a block
was given, fill() reported a missing block, and the arity errors could not
say 1..3 / 0..2. #combination requires its argument; #zip's block form reads
the receiver's length each step and no longer indexes past the end when the
block shrinks it; #replace checks frozen before the same-object shortcut;
endless ranges are reported as "-5.. out of range".

Struct: initialize_copy wants an instance of the same class
("initialize_copy should take same class object") and both it and
initialize refuse a frozen receiver; member readers report arity 0 and
writers 1; the recursion marker of an anonymous struct names the class.

Data: copies are frozen and carry the members (dup lost them and
clone(freeze: false) stayed thawed); #inspect, #to_h, #== and friends read
the stored members rather than the reader methods, so an overridden reader
cannot break them; initialize checks frozen before its arguments and takes
one positional Hash; Data.allocate and SubData.define are refused; Marshal
rejects a record whose members do not match the class.

Also:
Comparable#clamp accepts a range-like object and names nil properly,
Enumerable#min_by/#max_by keep the first of equal keys and raise for keys
that do not compare (a nil first key no longer returns the last element),
Array#zip packs multi-value yields of an Enumerator argument, and
Enumerable#inject without arguments or a block is an arity error.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…Range#max/include?/inspect, Range marshaling, enumerator copies

Hash: compare_by_identity treats every Integer that is a Fixnum in MRI and
every Float that is a flonum there as the same key again (h[1.5] and
h[2**40] used to be lost); #replace and #compare_by_identity during an
iteration raise MRI's RuntimeErrors; #eql? is false between an identity
hash and an ordinary one; default_proc= names the failed #to_proc
conversion.

Range: #max follows range_max - an exclusive end with a non-Integer begin
is a TypeError, a beginless range counts down from its end (Ruby 4.0) and
refuses a block; #first(n) on a beginless and #last(n) on an endless range
raise the RangeErrors; #include? decides by the endpoints only, so
(1..3).include?(1..2) is false and (nil..nil) takes numbers and times but
nothing else; #inspect carries the encoding of its endpoints instead of
BINARY; #initialize returns nil and #initialize_copy fills an allocated
range (a copy is not frozen); #sum of an Integer range is computed in closed
form, so (1..2**70).sum returns; the enumerator of reverse_each inspects as
MRI's.

Marshal: a loaded Range is frozen, a Range subclass loads (the subclass had
no deserializing constructor), a record missing begin, end or excl loads
with nil/false, and one whose ends do not compare is "bad value for range".

Enumerator: dup/clone of an enumerator whose external iteration is under
way raise TypeError ("can't copy execution context"); a fresh or finished
one copies as a fresh enumerator; to_enum's size block receives the
enumerator's arguments.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…roc.new argument checks, Kernel#display(port)

NoMethodError#private_call? is implemented: the call site records whether
the call that went missing had an implicit receiver (or `self.`), both for
the built-in failure and - as MRI's method_missing_reason does - for a
user-defined method_missing that calls super; NoMethodError.new takes the
fourth positional argument.

Exception#to_s applies String() to a non-String message, so an object with
#to_str reports it. Exception#full_message accepts highlight: nil.

Marshal.dump of a singleton class says "singleton class can't be dumped";
Marshal.load rejects an unknown keyword and, with freeze: true, no longer
turns an instance of a String subclass into a plain String through the
frozen-string table.

Proc.new with positional arguments is an ArgumentError (a Proc subclass
still passes them to its #initialize), and Kernel#display takes the port
to write to.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
@coderabbitai

coderabbitai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f3981f64-47a8-423b-b6cd-766a80420163
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Brings in the speedup merge (PR #22) and resolves the overlaps with this
branch:

- RubyMath: master's Float/Fixnum fast paths with the Ruby fallbacks stay;
  cbrt keeps the C library's answer with the Newton step MRI adds on glibc,
  and Math.__ir_cbrt__ (the fallback for Rational, Bignum and the rest) hands
  the Float back to it.
- Hash#each: master's single pass over the entries with the mutation stamp,
  inside this branch's iteration guard, so adding a key from the block is
  still the RuntimeError MRI raises; other IDictionaries keep the snapshot
  lookup.
- CheckLambdaArity: master's cached ChecksKeywords test, inside this branch's
  signature path (exact "1..2" bounds, required-keyword note, symbol procs
  left to their own receiver check).
- Struct#initialize: master moved the common call into C# and sends the rest
  to Struct#__struct_initialize_slow__; it now receives the positional values
  and the keywords apart, as this branch's `def initialize(*args, **kwargs)`
  did, so a Hash passed as a member value is told from keywords. The frozen
  check comes first, as MRI's rb_struct_modify does, and without the prelude
  the C# store takes the call, so the test harness still constructs structs.
- Enumerator::Lazy#each_with_object stays eager; IO#codepoints stays gone
  (removed in Ruby 3.0); the Math aliases use the alias keyword as master's
  prelude does.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…optional)

The committed PrismLoader.Generated.cs skimmed a SymbolNode's content_loc as an
optional location, one byte off from what libprism cd76b0d1 writes and from the
LoadNode half of the same file. With lazy method bodies on, every `require`d
file whose method body has a symbol followed by more statements failed to load
with "Unknown prism node type" - mspec's BaseFormatter#finish, for one, which
took the whole ruby/spec harness down locally. CI regenerates the file and never
saw it. `ruby Src/Prism/generate.rb` against prism cd76b0d1 now reproduces the
committed file byte for byte.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
ci.yml checked out ruby/prism's main branch, which has since moved to a
post-order serialization with a checksum (ruby/prism ab92f0eb4, 01c1960e8);
the C# loader reads the earlier layout, so every build-and-test job failed in
the smoke test with "Unknown prism node type: 228", on master as well as on
this branch. Both workflows now take PRISM_REF, the revision release.yml
already pinned and Src/Prism/README.md records (cd76b0d1); following prism's
new format is a change of its own.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
…frames without Kernel.send

The three skipped a fixed number of frames through `::Kernel.send(:caller, n)`,
one of them the frame of send itself. Since master binds a send of a literal
name as a direct call there is no such frame, so the current thread's backtrace
lost its innermost block frame, took the #backtrace_locations entry's line from
the frame above, and each_caller_location started one frame too high: five
specs in spec/core/thread. The methods now call caller and caller_locations
directly and put the native-style entry for themselves in front of the caller's
frames, where MRI has it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148CEo2oDuoL3mFTqDFTZU3
@Largo Largo changed the title Align IronRuby with MRI 3.4 behavior and fixes Align IronRuby with Ruby 4.0 behavior: core class fixes, CI prism pin, loader fix Oct 26, 2026
@Largo
Largo merged commit 7692b6f into master Oct 26, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants