Repository navigation
#89: Integer#[], Integer.sqrt, pow(b, m), Kernel#Integer parsing and tail calls, Data.define - #190
Merged
Merged
Conversation
Integer#[] was a prelude `def [](index, length = nil)` in front of the C# bit read, ~0.3-0.45 us a call. ClrInteger now answers an Integer index, a Fixnum offset and size (on a Fixnum or a Bignum), a Float index and a Range of Fixnums on a Fixnum itself; everything else goes to ports of MRI's int_aref1 and int_aref2 in ruby4.rb. Fixes, all against CRuby 4.0.9: - 5[32] was 1: C#'s shift count is taken mod 32, so it read bit 0. - a nil size answered the unmasked bits; it is a TypeError. - a size of 0 answered the shifted value; MRI masks every bit away. - a Range with a size argument was an ArgumentError; MRI converts the Range with #to_int (TypeError). - an empty (2...2) or equal-ended Range, a reversed one (5..2, self >> 5), a beginless one with a negative end, nil..nil and a Bignum receiver's NUM2LONG errors for a Float or a #to_int index. Differential script, 14372 cases: master differed from CRuby in 1712, this branch in none. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Integer.sqrt of a Bignum started from 1 << ((bit_length + 1) / 2), half a bit right, so 2**70 took seven BigInteger divisions. It now starts from Math.Sqrt of the leading ~1000 bits, raised by more than that root's rounding error (so it stays above the true root, as Newton's method from above needs) and shifted back: right to ~50 bits, it settles in one or two divisions. Integer.sqrt(2**70) ~2000 -> ~850 ns, (2**2000 + 1) ~55 -> ~21 us (CRuby 4.0.9: ~410 ns, ~9 us). Differential: 40 edge values and 3000 random and perfect-square checks up to 3000 bits match CRuby. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…89) pow(b, m) made BigIntegers of all three and called BigInteger.ModPow. For three Fixnums it now squares and multiplies in a long: |m| <= 2**31 keeps every product below 2**62. Fix: 0.pow(x, m) with x != 0 is 0 for any modulus, 0 included, as rb_int_powm shortcuts it before looking at m; it was a ZeroDivisionError for m == 0. Differential (10700 cases incl. 5000 random Fixnum triples): master differed from CRuby 4.0.9 in 13, this branch in none. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ral overload (#89) Two costs of Integer(s, exception: false) (~270 ns, CRuby ~105): - TryParseRubyInteger did a BigInteger multiply-add per digit. The digits now go into a long while x * radix + digit fits (for any radix up to 36), and past that into long chunks folded into the BigInteger once per chunk. A 30-digit number went from ~3 us to ~0.3-0.5 us (CRuby ~0.31). - A rule's lambda is compiled with tail calls, so the call into the library method was a `tail.' call. Kernel#Integer's general overload has eight parameters, more stack arguments than the rule's own, and the runtime makes such a tail call through its helpers (IL_STUB_StoreTailCallArgs, DispatchTailCalls), which allocate a buffer for the arguments. A call into a method of more than six parameters (the argument registers of x64 Unix) is now an ordinary call: Integer("123", 10) ~155 -> ~90 ns. Integer("123") 95 -> 70 ns, Integer("123", exception: false) ~270 -> ~210 ns (CRuby 60 / 105). What is left of the latter is the keyword Hash the call builds and TakeExceptionOption reading it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…on (#89) IListOps.IsBuiltinMethod (behind Enumerable.IsPlainList, so behind every Array#each/map/group_by fast path) cached its answer against the global method version, and re-read the method's RubyMethodAttributes by reflection whenever the version had moved. Data.define defines methods, so every call moved it, and ~13% of Data.define was GetCustomAttributes. The cache now also remembers the method it checked: when the name still resolves to that same RubyLibraryMethodInfo, its attributes have not changed and the answer stands. Data.define also no longer runs the setter-name Regexp for a member that does not end in "=", nor group_by for the duplicate check unless there is a duplicate. Data.define(:a, :b) 110-120 -> 90-100 us in a fresh process (CRuby ~7 us). The rest is binding call sites and defining methods on each new class and its singleton. Co-Authored-By: Claude Opus 5.5 <[email protected]>
#89) Found in review: on net10.0, whose BigInteger is capped near 2**31 bits, -5[1, 2**31 - 1], (-5)[0..(2**31 - 2)] and a Bignum's [-(2**31) + 1, 3] raised a raw System::OverflowException from the new C# paths. They now shift through ShiftLeftOrFail, as Integer#<< does since #171, and raise NoMemoryError (what MRI raises when the allocation fails). net8.0 builds the value, as before. 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 45 minutes. View limit details
|
32 of 36 tasks
Found in review (Greptile, P1): the seed computed 2 * halfShift in an int. For a value past 2**31 + 1000 bits, which a .NET 8 BigInteger can hold, that wrapped negative: the right shift became a left one, the double was Infinity and new BigInteger(Infinity) threw. The seed is now Integer.SqrtSeed, whose shifts are counted in a long and made in Int32-sized steps. Test: Integer_SqrtSeedHuge1 (net8.0 only: .NET 9+ caps a BigInteger near 2**31 bits) builds 2**(2**31 + 1024) and checks that the seed is at or above its root and within a bit of it; the previous seed threw there. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Found in review (Greptile, P2): the NUM2LONG range check for a Float index
on a Bignum used between?(-2.0**63, 9223372036854775807.0), and that upper
literal is 2.0**63 itself, so (2**70)[9223372036854775808.0] answered 0
where CRuby 4.0.9 raises RangeError ("float 9.223372037e+18 out of range
of integer"). The upper bound is now exclusive.
Test: Integer_ElementReferenceFloatBound1 (2.0**63, -2.0**63 and their
neighbouring doubles, both signs of the receiver; CRuby's output).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #89. This PR covers the numeric items that #188 does not touch: one commit per item, plus one fix from review. (#188 covers Float() parsing,
3 ** -2, huge powers, Float#step and String#to_c.) The expected outputs of the new tests are CRuby 4.0.9's.This branch merges cleanly with #188's branch (checked with merge-tree). After merging both, regenerate
Initializers.Generated.cs.How the numbers were measured
fork/master(31e508c) and of this branch./proc/thread-self/stat), pinned to one core withtaskset.The box was loaded (load 5-15 for the final table, much more earlier), so the ranges are wide.
Results
x[3]x[2, 3]x[2..5]x[1.5](2**70 + 12345)[3](2**70 + 12345)[2, 3]Integer.sqrt(2**70)Integer.sqrt(2**2000 + 1)12345.pow(5, 1000)3.pow(1000, 1_000_007)Integer("123")Integer("123", exception: false)Integer("12x", exception: false)Integer("123", 10)Integer(30-digit string)Data.define(:a, :b)(fresh process, 1000 classes)12345.digits(unchanged)1.
Integer#[](0f248e9, review fix c72fdde)Integer#[]was a preludedef [](index, length = nil)in front of the C# bit read.C# now answers these forms itself:
Every other form goes to ports of MRI's
int_aref1andint_aref2in ruby4.rb.Fixes (all already wrong on master):
5[32]was 1. C#'s shift count is taken mod 32, so it read bit 0.#to_int.2...2and3..3;5..2isself >> 5);nil..nil;#to_intindex.A differential script runs 14372 cases. Master differs from CRuby in 1712 of them, this branch in none.
Review fix: on net10.0, BigInteger is capped near 2**31 bits. A mask or shift past that cap raised a raw
System::OverflowExceptionfrom the new C# paths. It now raises NoMemoryError throughShiftLeftOrFail, asInteger#<<does (#171).Test:
Integer_ElementReference1.2.
Integer.sqrt(983ce0e)Newton's method started from
1 << ((bit_length + 1) / 2), so2**70took seven BigInteger divisions.It now starts from
Math.Sqrtof the leading ~1000 bits, shifted back. That start is raised by more than the root's rounding error, so it stays above the true root. It is right to ~50 bits, so the iteration settles in one or two divisions.Checked against CRuby: 40 edge values, plus 3000 random and perfect-square checks up to 3000 bits, all match.
Test:
Integer_SqrtLarge1.3.
Integer#pow(b, m)(26878c4)For three Fixnums, the square-and-multiply now runs in a long.
|m| <= 2**31keeps every product below 2**62.Fix:
0.pow(x, m)withx != 0is now 0 for any modulus, including 0, asrb_int_powmshortcuts it. It was a ZeroDivisionError form == 0.A differential run of 10700 cases includes 5000 random Fixnum triples. Master differs from CRuby in 13 cases, this branch in none.
Test:
Integer_PowModulo1.4.
Kernel#IntegerandInteger(s, exception: false)(60f1b66)There were two costs.
Parsing.
TryParseRubyIntegerdid a BigInteger multiply-add per digit. The digits now go into a long whilex * radix + digitfits. Past that, they go into long chunks, and each chunk is folded into the BigInteger once.A slow tail call. A rule's lambda is compiled with tail calls, so its call into a library method is a
tail.call.Kernel#Integer's general overload has eight parameters, so it needs more stack arguments than the rule has.IL_STUB_StoreTailCallArgs/DispatchTailCalls), which allocate an argument buffer. perf showed them on every call.RubyMethodGroupBase.KeepOutOfSlowTailCallnow makes the call an ordinary one when the library method has more than six parameters. This applies to every such library method, not onlyInteger.Integer("123", 10)went from 156 to 90-95 ns.What is left of
exception: falseis the keyword Hash that the call site builds, andTakeExceptionOptionreading it.Test:
Kernel_IntegerParse1.5.
Data.define(3a0b81f)IListOps.IsBuiltinMethodsits behindEnumerable.IsPlainList, so behind every Arrayeach/map/group_byfast path.RubyMethodAttributes again by reflection.Data.definedefines methods, so every call moved the version. About 13% ofData.definewasGetCustomAttributes.The cache now also remembers which method it checked. If the name still resolves to the same
RubyLibraryMethodInfo, the answer stands.Data.definealso skips the setter-name Regexp for a member that does not end in=, and skipsgroup_byunless there is a duplicate.What remains (~90 us against CRuby's ~7) is DLR-level work on each new class and its singleton:
define_methodfor each member;Not done
Integer#digits: already near CRuby (312 against 250 ns). The rest is the general call cost.3 ** -2, huge**powers and Float#step are left to #89: Float() parsing, 3 ** -2, huge powers, Float#step, String#to_c, split and $~ #188.Verification
IronRuby.Tests:
File_StatPredicatesToIo1, a known failure on this host, also passed.ruby/spec at CI's SPEC_REF (dda28d04) and MSPEC_REF (b79c65ed), Release net8.0: master and this branch give identical results.
Differential scripts against CRuby 4.0.9:
Integer#[]: 14372 cases, no differences.**/pow/Integer.sqrt: 6973 lines, no differences.pow(b, m): 10700 cases, no differences.Integer()/Float()strings: 2123 lines. The one difference, also on master, is how an invalid-Float message quotes non-ASCII digits.Data.definemembers, errors and singleton methods: threeinspectdifferences for odd member names, all also on master.Not fixed, seen on the way:
Data.define(:"a=b").new(0).inspectshowsa=b=0where CRuby shows:"a=b"=0. Master does the same.🤖 Generated with Claude Code


Confidence Score: 5/5
The PR appears safe to merge; both previous findings are fixed and no new blocking issue was found.Summary
This PR speeds up integer bit reads, square roots, modular powers, integer parsing, and
Data.define.Reviews (2) · Last reviewed commit: "Integer#[]: 2.0**63 is past a long for a..." · Reviewed by Greptile