Repository navigation
#89: $~.string after sub, huge shift widths, faster Enumerable#zip and String#count/delete/squeeze - #171
Conversation
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]>
|
Warning Review limit reachedEnable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
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. View limit details
|
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]>
|
@greptileai review |
| loud = enumerated.count { |source| !__zip_quiet_each__(source) } | ||
| return __zip_in_turn__(sources) if loud == 0 || (loud == 1 && __zip_quiet_each__(self)) |
There was a problem hiding this comment.
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.| 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 |
There was a problem hiding this comment.
Calling a custom source's each directly does not preserve Enumerator#next behavior:
- If
eachwraps its yields inensure, the newbreakruns cleanup immediately. The previous path stays suspended at the last requested yield. Anensurethat raises can therefore make(1..1).zip(source)fail instead of returning a row. - If
eachyields once and then raisesStopIteration,(1..2).zip(source)now raises instead of filling the second row withnil.
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.Enumerable#zip: fast path only when every #each is built in (Greptile on #171)
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.classfor a String subclass is String; a frozen source is copied (Strings and regexps)Integer << 2**31raises RangeError (Numerics)Enumerable#zipwith an Enumerable argument goes throughEnumerator#next(Collections and iteration)String#count,#deleteand#squeezeare 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,$~.stringwas the receiver's class and, for a frozen receiver, the receiver itself. MRI'srb_str_subrunssub!onstr_duplicate(rb_cString, str), so there it is a String copy.MatchData.DetachStringmakes 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**31now builds the 231+1-bit Integer, as MRI does. Right shifts by widths past Int32 keep the real bits ((1 << 2**31) >> 2**31was 0, now 1), andInteger#[]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**31is NoMemoryError, the error MRI raises when an allocation fails. Before this PR, master already raised a rawSystem::OverflowExceptionon net10.0 for1 << (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**40here). ruby/spec'sleft_shift_spec/right_shift_speclet 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.NumericOps1asserted the old RangeError and is updated.3.
Enumerable#zip(9441c0b)MRI's
zip_ireads non-Array arguments withEnumerator#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#eachthat runs someone else's code. The built-in#eachof Hash, Struct, Set and an Integer Range does not, and never raises. A String Range is excluded: MRI walks it with a dynamically dispatchedString#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#nextwould have asked for, in an order nothing can observe. Endless arguments still work, and an empty receiver starts no argument. Everything else goes through#nextas before. Test:Enumerable_ZipEnumerated1, which logs side effects to show the order is CRuby's.Interleaved CPU time, Debug net8.0, 1000 elements:
Set#zip(Hash)zip(custom Enumerable)CRuby takes ~0.7 ms. What remains is IronRuby's general block cost.
4.
String#count/#delete/#squeeze(943391a)The costs were:
#squeezecalledGetChar/SetCharonce per character on a copy.#countand#deletecopied the characters out withToString.#deletealso built a StringBuilder and copied it again.The fix:
MutableString.GetCharacterDatagives the characters (or one-for-one bytes) as a span.#deleteand#squeezewrite 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"".deleteis""."a".freeze.squeeze!is a FrozenError; it used to answer nil.Test:
String_CountDeleteSqueeze2.Interleaved CPU time, Release net8.0, 1140 ASCII characters:
count("lo")delete("l")delete("a-m")squeezeIn a steady loop,
counttakes ~2.6–3.6 µs (CRuby 1.4–1.7) andsqueeze~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.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_HugeShifts1was the only failure, from a stale build. After the .NET 9+ change it passes on both TFMs when run on its own, as doesNumericOps1.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#splitwith 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.RequireNotFrozenshow the raw text and the classString, where MRI shows the inspected text and the subclass name. This was already the case on master.🤖 Generated with Claude Code
Fix the new
zippath before merging because it can return different values or raise unexpected errors.Fix with agent prompt
Summary
The PR fixes the string saved after
sub, expands huge integer shifts, and speeds upzipand character-selection methods.$~.stringafterString#subis a separate plain String.Enumerable#zipreads eligible arguments without a fiber switch per item.count,delete, andsqueezescan string data directly and write kept characters once.Reviews (1) · Last reviewed commit: "Enumerable#zip: a String Range is not a ..." · Reviewed by Greptile