Skip to content

#89: $~.string after sub, huge shift widths, faster Enumerable#zip and String#count/delete/squeeze - #171

Merged
Largo merged 6 commits into
masterfrom
claude/issue-89-gaps
Nov 9, 2026
Merged

Largo merged 6 commits into
masterfrom
claude/issue-89-gaps

Conversation

@Largo

@Largo Largo commented Nov 9, 2026 •

Copy link
Copy Markdown
Owner

Part of #89. Four of its unticked items, one commit each; the expected outputs of the new tests are CRuby 4.0.9's.

#89 items this addresses

  • $~.string.class for a String subclass is String; a frozen source is copied (Strings and regexps)
  • Integer << 2**31 raises RangeError (Numerics)
  • Enumerable#zip with an Enumerable argument goes through Enumerator#next (Collections and iteration)
  • String#count, #delete and #squeeze are 30–145× slower than CRuby (Strings and regexps). ljust/center, which the same item mentions, are untouched.

1. $~.string (b0e45a9)

Master already matched CRuby for every match except one: after String#sub, $~.string was the receiver's class and, for a frozen receiver, the receiver itself. MRI's rb_str_sub runs sub! on str_duplicate(rb_cString, str), so there it is a String copy. MatchData.DetachString makes that copy lazily, on the first #string, from the frozen subject the match already holds. Test: Regex_MatchStringClassAndIdentity1.

2. Huge shift widths (b61f3a7, 57f99a3)

On net8.0, 1 << 2**31 now builds the 231+1-bit Integer, as MRI does. Right shifts by widths past Int32 keep the real bits ((1 << 2**31) >> 2**31 was 0, now 1), and Integer#[] reaches bits past index 231 (it answered from the sign alone).

net10.0 differs. .NET 9 and later cap a BigInteger at about 2**31 bits, so there 1 << 2**31 is NoMemoryError, the error MRI raises when an allocation fails. Before this PR, master already raised a raw System::OverflowException on net10.0 for 1 << (2**31 - 33); that is now NoMemoryError too.

From a left-shift width of 232** on, IronRuby still raises "shift width too big". In MRI the RangeError starts at about 266 (big_shift3), and in between it is NoMemoryError on most machines (1 << 2**40 here). ruby/spec's left_shift_spec/right_shift_spec let a non-MRI engine use 232 as the limit. A .NET 8 BigInteger cannot hold much past 2**36 bits anyway.

Test: Integer_HugeShifts1, with expected output that depends on the .NET version. NumericOps1 asserted the old RangeError and is updated.

3. Enumerable#zip (9441c0b)

MRI's zip_i reads non-Array arguments with Enumerator#next, and here that is a fiber switch per element. The fast path applies only without a block, and only when at most one of the receiver and the arguments has an #each that runs someone else's code. The built-in #each of Hash, Struct, Set and an Integer Range does not, and never raises. A String Range is excluded: MRI walks it with a dynamically dispatched String#succ (661c495, found in review).

When it applies, the receiver is read first. Then each argument is read with #each, stopping at the receiver's length. That is exactly the elements #next would have asked for, in an order nothing can observe. Endless arguments still work, and an empty receiver starts no argument. Everything else goes through #next as before. Test: Enumerable_ZipEnumerated1, which logs side effects to show the order is CRuby's.

Interleaved CPU time, Debug net8.0, 1000 elements:

case master branch
Set#zip(Hash) 82–124 ms 3.5–5 ms
zip(custom Enumerable) 59–73 ms 3–3.5 ms

CRuby takes ~0.7 ms. What remains is IronRuby's general block cost.

4. String#count / #delete / #squeeze (943391a)

The costs were:

  • #squeeze called GetChar/SetChar once per character on a copy.
  • #count and #delete copied the characters out with ToString.
  • #delete also built a StringBuilder and copied it again.
  • The per-character ASCII test was a call that was never inlined.

The fix:

  • MutableString.GetCharacterData gives the characters (or one-for-one bytes) as a span.
  • The ASCII mask tests are inline.
  • #delete and #squeeze write the kept characters once, into an array the result takes over (CreateDerived(char[]/byte[], count)).

#delete! and #squeeze! now also check in MRI's order:

  • "".delete! and "".freeze.delete!("a") are nil, and "".delete is "".
  • The character sets are checked before the frozen check.
  • "a".freeze.squeeze! is a FrozenError; it used to answer nil.

Test: String_CountDeleteSqueeze2.

Interleaved CPU time, Release net8.0, 1140 ASCII characters:

call master branch CRuby
count("lo") 8.1–8.4 µs 5.8 µs ~2.0 µs
delete("l") 10.6–11.3 µs 7.3–8.2 µs ~3.8 µs
delete("a-m") 7.2–7.6 µs 3.6–3.8 µs ~2.6 µs
squeeze 18.4–24.6 µs 6.6–6.8 µs ~2.0 µs

In a steady loop, count takes ~2.6–3.6 µs (CRuby 1.4–1.7) and squeeze ~3.1 µs (CRuby 1.9).

Verification

  • ruby/spec, Debug net8.0, master baseline (git archive fork/master) against this branch: identical results. The failing and erroring examples are the same set in both.

    dir examples failures errors
    core/matchdata 185 0 0
    core/integer 598 0 2
    core/enumerable 536 0 0
    core/string 3963 0 1
    core/regexp 256 0 3

    The integer shift specs (left_shift, right_shift, element_reference) also pass on net10.0: 100 examples, 0 failures.

  • IronRuby.Tests: net8.0, 0 failures in a full run. In the full net10.0 run, Integer_HugeShifts1 was the only failure, from a stale build. After the .NET 9+ change it passes on both TFMs when run on its own, as does NumericOps1.

  • Differential scripts against CRuby 4.0.9: no differences for $~.string (34 cases), shifts (30), zip (35, including side-effect order) or count/delete/squeeze (~700). The only exception is FrozenError message text, which master already had.

Found, not changed

  • String#split with a Regexp leaves $~ alone; MRI leaves it nil, or the last match when a limit stops it, and it is visible to the split block.
  • 2 ** (2**31) raises ArgumentError ("exponent is too large"), while CRuby computes it.
  • FrozenError messages from RequireNotFrozen show the raw text and the class String, where MRI shows the inspected text and the subclass name. This was already the case on master.

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence Score: 3/5

Fix the new zip path before merging because it can return different values or raise unexpected errors.

Fix All in Claude CodeFindings

  1. P1 Zip reads changed values ▶
  2. P1 Zip changes iterator behavior ▶
Fix with agent prompt
### Issue 1
Src/StdLib/ironruby/ruby4.rb:957-958
The fast path finishes reading the receiver before reading any arguments, but a custom `each` can change those arguments. For example, let `h = {a: 1, b: 2}` and let the receiver's `each` yield `0`, set `h[:a] = 9`, then yield `1`. Calling `receiver.zip(h)` now puts `[:a, 9]` in the first row. The old interleaved path reads `[:a, 1]` before that change.

A built-in `each` does not make its collection independent of custom code. Keep interleaved reads whenever user code can change another source.

### Issue 2
Src/StdLib/ironruby/ruby4.rb:937-941
Calling a custom source's `each` directly does not preserve `Enumerator#next` behavior:

- If `each` wraps its yields in `ensure`, the new `break` runs cleanup immediately. The previous path stays suspended at the last requested yield. An `ensure` that raises can therefore make `(1..1).zip(source)` fail instead of returning a row.
- If `each` yields once and then raises `StopIteration`, `(1..2).zip(source)` now raises instead of filling the second row with `nil`.

Keep custom sources on the `next` path unless these behaviors are preserved.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR fixes the string saved after sub, expands huge integer shifts, and speeds up zip and character-selection methods.

  • $~.string after String#sub is a separate plain String.
  • Integer shifts and bit lookups reach values beyond 32-bit widths.
  • Enumerable#zip reads eligible arguments without a fiber switch per item.
  • count, delete, and squeeze scan string data directly and write kept characters once.

Reviews (1) · Last reviewed commit: "Enumerable#zip: a String Range is not a ..." · Reviewed by Greptile

Largo and others added 5 commits November 9, 2026 08:13
MRI's rb_str_sub runs sub! on str_duplicate(rb_cString, str), so after
String#sub the match's #string is of class String even for a subclass
receiver, and is never the receiver itself, even a frozen one. Every other
match already matched CRuby 4.0 (subclass kept, frozen receiver returned
as itself). The copy is made lazily on the first #string, from the frozen
subject the match already holds.

Part of #89.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 << 2**31 raised RangeError; MRI allocates the 2**31+1-bit Integer.
A width that does not fit an Int32 now goes to BigInteger in Int32.MaxValue
steps. Right shifts by such widths keep the bits a very large Integer still
has ((1 << 2**31) >> 2**31 was 0, now 1), and Integer#[] reaches bits past
index 2**31 (it answered from the sign alone).

From a left-shift width of 2**32 on it is still "shift width too big":
ruby/spec allows a non-MRI implementation that limit, and MRI's own
RangeError starts near 2**66, with NoMemoryError in between on most
machines; a .NET BigInteger cannot hold much past 2**36 bits.

Part of #89.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
MRI's zip_i reads an argument that is not an Array with Enumerator#next,
which costs a fiber switch per element here: (1000-element Set).zip(Hash)
took ~90 ms against ~0.8 ms in CRuby.

Without a block, and when at most one of the receiver and the arguments
has an #each that runs anyone else's code - the built-in #each of a Hash,
Struct, Set or String/Integer Range does not, and never raises - the order
the elements are read in cannot show. The receiver is then read first and
each argument with #each after it, stopping at the receiver's length:
exactly the elements #next would have asked for, an endless argument still
works, and an empty receiver starts no argument. Everything else (a block,
two arguments with their own #each, ...) still goes through #next.

Interleaved CPU time, 1000 elements, net8.0: Set#zip(Hash) 82-124 ms ->
3.5-5 ms; with a custom Enumerable argument 59-73 ms -> 3-3.5 ms.

Part of #89.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
#squeeze copied the receiver and then squeezed the copy with a GetChar and
a SetChar per character; #count and #delete copied the characters out
with ToString first, #delete gathered them in a StringBuilder and copied
that once more, and the ASCII test was a call per character (its loop for
non-ASCII kept it from being inlined).

MutableString.GetCharacterData hands out the characters - or, for a string
held as bytes that are its characters one for one, the bytes - as a span.
Count and delete test the ASCII masks inline in one loop; delete and
squeeze write the kept characters once, into an array the result takes
over (MutableString.CreateDerived(char[]/byte[], count)).

Along the way #delete! and #squeeze! check in MRI's order: #delete!
answers nil for an empty receiver before anything (and "".delete is ""),
both set up the character sets before refusing a frozen receiver, and
#squeeze! refuses a frozen one even with nothing to squeeze ("a".freeze
.squeeze! answered nil).

Interleaved CPU time, Release net8.0, 1140 ASCII characters (CRuby 4.0 on
the same box ~2.0 / 3.8 / 2.0 us): count("lo") 8.1-8.4 -> 5.8 us,
delete("l") 10.6-11.3 -> 7.3-8.2 us, delete("a-m") 7.2-7.6 -> 3.6-3.8 us,
squeeze 18.4-24.6 -> 6.6-6.8 us. In a steady loop count is ~2.6-3.6 us
and squeeze ~3.1 us against CRuby's 1.4-1.7 and 1.9.

Part of #89.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eption

.NET 9 and later cap a BigInteger at about 2**31 bits and throw
OverflowException past that, so on net10.0 1 << 2**31 - and already
1 << (2**31 - 33) on master - surfaced as a raw System::OverflowException.
Every shift now reports it as the failed allocation MRI raises
(NoMemoryError). The tests expect that on .NET 9+, and the computed result
on .NET 8.

NumericOps1 asserted the old RangeError for 1 >> Int32.MinValue.

Part of #89.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

  • Ask an admin to enable usage-based reviews

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Next included review available in 49 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available. Your 61 included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 9170dd0 and 661c495.

Files selected for processing: 14

  • Src/IronRuby.Tests/RubyTests.cs
  • Src/IronRuby.Tests/Runtime/ArrayTests.cs
  • Src/IronRuby.Tests/Runtime/IntegerTests.cs
  • Src/IronRuby.Tests/Runtime/MiscTests.cs
  • Src/IronRuby.Tests/Runtime/RegexTests.cs
  • Src/IronRuby.Tests/Runtime/StringTests.cs
  • Src/Libraries/Builtins/MutableStringOps.cs
  • Src/Libraries/Extensions/ClrBigInteger.cs
  • Src/Libraries/Extensions/ClrInteger.Int64.cs
  • Src/Libraries/Extensions/ClrInteger.cs
  • Src/Ruby/Builtins/MatchData.cs
  • Src/Ruby/Builtins/MutableString.BinaryContent.cs
  • Src/Ruby/Builtins/MutableString.cs
  • Src/StdLib/ironruby/ruby4.rb
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

MRI walks a String Range with a dynamically dispatched String#succ, so with
a redefined #succ the in-turn path ran it after the whole receiver instead
of between its elements (found by the review). Only Hash, Struct, Set and
Integer Ranges count as quiet now; a String Range goes through #next again.

Part of #89.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Largo

Largo commented Nov 9, 2026

Copy link
Copy Markdown
Owner Author

@greptileai review

Comment on lines +957 to +958
loud = enumerated.count { |source| !__zip_quiet_each__(source) }
return __zip_in_turn__(sources) if loud == 0 || (loud == 1 && __zip_quiet_each__(self))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Zip reads changed values

The fast path finishes reading the receiver before reading any arguments, but a custom each can change those arguments. For example, let h = {a: 1, b: 2} and let the receiver's each yield 0, set h[:a] = 9, then yield 1. Calling receiver.zip(h) now puts [:a, 9] in the first row. The old interleaved path reads [:a, 1] before that change.

A built-in each does not make its collection independent of custom code. Keep interleaved reads whenever user code can change another source.

Prompt To Fix With AI
This is a comment left during a code review.
Path: Src/StdLib/ironruby/ruby4.rb
Line: 957-958

Comment:
**Zip reads changed values**

The fast path finishes reading the receiver before reading any arguments, but a custom `each` can change those arguments. For example, let `h = {a: 1, b: 2}` and let the receiver's `each` yield `0`, set `h[:a] = 9`, then yield `1`. Calling `receiver.zip(h)` now puts `[:a, 9]` in the first row. The old interleaved path reads `[:a, 1]` before that change.

A built-in `each` does not make its collection independent of custom code. Keep interleaved reads whenever user code can change another source.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

Comment on lines +937 to +941
source.each do |*values|
# several yielded values make one element, as Enumerator#next packs them
rows[index] << (values.size <= 1 ? values[0] : values)
index += 1
break if index == count

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Zip changes iterator behavior

Calling a custom source's each directly does not preserve Enumerator#next behavior:

  • If each wraps its yields in ensure, the new break runs cleanup immediately. The previous path stays suspended at the last requested yield. An ensure that raises can therefore make (1..1).zip(source) fail instead of returning a row.
  • If each yields once and then raises StopIteration, (1..2).zip(source) now raises instead of filling the second row with nil.

Keep custom sources on the next path unless these behaviors are preserved.

Prompt To Fix With AI
This is a comment left during a code review.
Path: Src/StdLib/ironruby/ruby4.rb
Line: 937-941

Comment:
**Zip changes iterator behavior**

Calling a custom source's `each` directly does not preserve `Enumerator#next` behavior:

- If `each` wraps its yields in `ensure`, the new `break` runs cleanup immediately. The previous path stays suspended at the last requested yield. An `ensure` that raises can therefore make `(1..1).zip(source)` fail instead of returning a row.
- If `each` yields once and then raises `StopIteration`, `(1..2).zip(source)` now raises instead of filling the second row with `nil`.

Keep custom sources on the `next` path unless these behaviors are preserved.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

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.

1 participant