Skip to content

#89: Integer#[], Integer.sqrt, pow(b, m), Kernel#Integer parsing and tail calls, Data.define - #190

Merged
Largo merged 8 commits into
masterfrom
claude/issue-89-intops
Nov 10, 2026
Merged

Largo merged 8 commits into
masterfrom
claude/issue-89-intops

Conversation

@Largo

@Largo Largo commented Nov 10, 2026 •

Copy link
Copy Markdown
Owner

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

  • Release net8.0 builds of fork/master (31e508c) and of this branch.
  • Main-thread CPU time (/proc/thread-self/stat), pinned to one core with taskset.
  • Interleaved master / branch / branch / master.
  • Each run goes through the whole case list once as warm-up, then calibrates, then reports the best of 5 rounds of at least 200 ms.
  • CRuby 4.0.9 on the same core.

The box was loaded (load 5-15 for the final table, much more earlier), so the ranges are wide.

Results

master branch CRuby
x[3] 338-362 ns 48-65 ns 23 ns
x[2, 3] 1375-1750 ns 52-58 ns 41 ns
x[2..5] 1312 ns 50-60 ns 138 ns
x[1.5] 950-1000 ns 50-62 ns 288 ns
(2**70 + 12345)[3] 338-438 ns 120-138 ns 95 ns
(2**70 + 12345)[2, 3] 1312-1375 ns 200-244 ns 115 ns
Integer.sqrt(2**70) 1219-1375 ns 650-675 ns 288 ns
Integer.sqrt(2**2000 + 1) 37.5-43.8 us 13.1-20 us 5.75 us
12345.pow(5, 1000) 162-206 ns 95 ns 100 ns
3.pow(1000, 1_000_007) 262-275 ns 225-244 ns 212 ns
Integer("123") 110-162 ns 62-72 ns 58 ns
Integer("123", exception: false) 300-375 ns 212-250 ns 119 ns
Integer("12x", exception: false) 338-362 ns 238-288 ns 105 ns
Integer("123", 10) 219-300 ns 150-212 ns 100 ns
Integer(30-digit string) 2625-3625 ns 388 ns 325 ns
Data.define(:a, :b) (fresh process, 1000 classes) 110-120 us 90-100 us ~7 us
12345.digits (unchanged) 338-362 ns 312 ns 250 ns

1. Integer#[] (0f248e9, review fix c72fdde)

Integer#[] was a prelude def [](index, length = nil) in front of the C# bit read.

C# now answers these forms itself:

  • an Integer index;
  • a Fixnum offset and size, on a Fixnum or a Bignum;
  • a Float index;
  • a Range of Fixnums, on a Fixnum.

Every other form goes to ports of MRI's int_aref1 and int_aref2 in 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.
  • A nil size answered the unmasked bits. MRI raises TypeError.
  • A size of 0 answered the shifted value. MRI masks every bit away, giving 0.
  • A Range together with a size was an ArgumentError. MRI raises TypeError, because it converts the Range with #to_int.
  • These now also match MRI:
    • 2...2 and 3..3;
    • a reversed range (5..2 is self >> 5);
    • a beginless range with a negative end;
    • nil..nil;
    • a Bignum receiver's NUM2LONG errors for a Float or #to_int index.

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::OverflowException from the new C# paths. It now raises NoMemoryError through ShiftLeftOrFail, as Integer#<< does (#171).

Test: Integer_ElementReference1.

2. Integer.sqrt (983ce0e)

Newton's method started from 1 << ((bit_length + 1) / 2), so 2**70 took seven BigInteger divisions.

It now starts from Math.Sqrt of 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**31 keeps every product below 2**62.

Fix: 0.pow(x, m) with x != 0 is now 0 for any modulus, including 0, as rb_int_powm shortcuts it. It was a ZeroDivisionError for m == 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#Integer and Integer(s, exception: false) (60f1b66)

There were two costs.

Parsing. TryParseRubyInteger did a BigInteger multiply-add per digit. The digits now go into a long while x * radix + digit fits. 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.
  • The runtime makes such a tail call through its helpers (IL_STUB_StoreTailCallArgs / DispatchTailCalls), which allocate an argument buffer. perf showed them on every call.
  • RubyMethodGroupBase.KeepOutOfSlowTailCall now makes the call an ordinary one when the library method has more than six parameters. This applies to every such library method, not only Integer.
  • A same-build A/B with only this change toggled: Integer("123", 10) went from 156 to 90-95 ns.

What is left of exception: false is the keyword Hash that the call site builds, and TakeExceptionOption reading it.

Test: Kernel_IntegerParse1.

5. Data.define (3a0b81f)

IListOps.IsBuiltinMethod sits behind Enumerable.IsPlainList, so behind every Array each / map / group_by fast path.

  • It cached its answer against the global method version.
  • Whenever that version had moved, it read the method's RubyMethodAttributes again by reflection.
  • Data.define defines methods, so every call moved the version. About 13% of Data.define was GetCustomAttributes.

The cache now also remembers which method it checked. If the name still resolves to the same RubyLibraryMethodInfo, the answer stands.

Data.define also skips the setter-name Regexp for a member that does not end in =, and skips group_by unless there is a duplicate.

What remains (~90 us against CRuby's ~7) is DLR-level work on each new class and its singleton:

  • binding call sites (~18% rule binding);
  • define_method for each member;
  • four singleton methods per class.

Not done

Verification

  • IronRuby.Tests:

    • Debug net8.0, full run: PASSED, 0 failures. File_StatPredicatesToIo1, a known failure on this host, also passed.
    • The 4 new tests pass on net10.0.
  • ruby/spec at CI's SPEC_REF (dda28d04) and MSPEC_REF (b79c65ed), Release net8.0: master and this branch give identical results.

    dir examples failures errors
    core/integer 598 0 2
    core/float 260 0 0
    core/kernel 2230 0 4
    core/rational 158 0 0
    core/data 89 0 2
    core/numeric 326 0 0
  • 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.define members, errors and singleton methods: three inspect differences for odd member names, all also on master.

Not fixed, seen on the way: Data.define(:"a=b").new(0).inspect shows a=b=0 where CRuby shows :"a=b"=0. Master does the same.

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence 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.

  • Integer#[] reads bits, slices, and ranges with Ruby-compatible results.
  • Large Integer.sqrt calls start close to the integer root.
  • Fixnum modular powers use long arithmetic and handle a zero base like CRuby.
  • Kernel#Integer parses digits in long-sized chunks before using BigInteger.
  • Large library calls now skip the runtime's slow tail-call path.
  • Data.define creates classes with fewer repeated checks.

Reviews (2) · Last reviewed commit: "Integer#[]: 2.0**63 is past a long for a..." · Reviewed by Greptile

Largo and others added 6 commits November 10, 2026 09:50
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]>
@coderabbitai

coderabbitai Bot commented Nov 10, 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 45 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available. Your 71 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 60c639e and 55ef146.

Files ignored due to path filters: 1

  • Src/Libraries/Initializers.Generated.cs is excluded by !**/*.generated.*
Files selected for processing: 9

  • Src/IronRuby.Tests/RubyTests.cs
  • Src/IronRuby.Tests/Runtime/IntegerTests.cs
  • Src/Libraries/Builtins/Integer.cs
  • Src/Libraries/Builtins/KernelOps.cs
  • Src/Libraries/Extensions/ClrBigInteger.cs
  • Src/Libraries/Extensions/ClrInteger.cs
  • Src/Libraries/Extensions/IListOps.cs
  • Src/Ruby/Runtime/Calls/RubyMethodGroupBase.cs
  • Src/StdLib/ironruby/ruby4.rb
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment thread Src/Libraries/Builtins/Integer.cs Resolved
Comment thread Src/StdLib/ironruby/ruby4.rb Resolved
Largo and others added 2 commits November 10, 2026 11:02
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]>
@Largo
Largo merged commit 4ac1986 into master Nov 10, 2026
9 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.

1 participant