Commit 7b31ed9d

7b31ed9d93d5Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 5 files · +2 added · ~3 modified

Description

Fix bigint **, << and >> to keep arbitrary precision

bigint ** int already inferred TY_BIGINT (it flows through the numeric promotion branch), but codegen had no wiring: bigint_arith_fn maps only +,-,*,/,% so ** fell through to the int path. Bigint shifts were worse: <</>> are not arith ops, so they were never inferred as TY_BIGINT and the result type collapsed to UNKNOWN (an "unsupported call" at compile time).

Wire all three:

  • analyze_infer: a bigint receiver shifted by an int stays bigint.
  • codegen_call: widen the int-arith gate so bigint shifts reach the TY_BIGINT branch, and emit **, <<, >> directly as sp_bigint_pow / sp_bigint_shl / sp_bigint_shr (each takes an int64 second operand).

The runtime shift primitives were also truncating: sp_bigint_shl/shr did to_int << n / to_int >> n, narrowing the bigint to 64 bits first. Reexpress them at arbitrary precision: x << n == x * 2^n and x >> n == floor(x / 2^n) (sp_bigint_div floors toward -inf, matching Ruby's arithmetic right shift for negatives too).

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
7b31ed9d93d5
Parent
4ee5eb75f3a1

lib/sp_bigint.cmodifiedView file

@@ -5427,17 +5427,17 @@
54275427
54285428 sp_Bigint *sp_bigint_shl(sp_Bigint *a, int64_t n) {
54295429 if (n < 0) return sp_bigint_shr(a, -n);
5430- if (n >= 64) return sp_bigint_new_int(0);
5431- return sp_bigint_new_int(sp_bigint_to_int(a) << n);
5430+ /* x << n == x * 2^n at arbitrary precision (the old `to_int << n` truncated
5431+ the bigint to 64 bits and overflowed the shift). */
5432+ return sp_bigint_mul(a, sp_bigint_pow(sp_bigint_new_int(2), n));
54325433 }
54335434
54345435 sp_Bigint *sp_bigint_shr(sp_Bigint *a, int64_t n) {
54355436 if (n < 0) return sp_bigint_shl(a, -n);
5436- if (n >= 64) {
5437- /* arithmetic right shift: negative -> -1, positive -> 0 */
5438- return sp_bigint_new_int(sp_bigint_to_int(a) < 0 ? -1 : 0);
5439- }
5440- return sp_bigint_new_int(sp_bigint_to_int(a) >> n);
5437+ /* x >> n == floor(x / 2^n) at arbitrary precision (the old `to_int >> n`
5438+ truncated the bigint to 64 bits). sp_bigint_div floors toward -inf, which
5439+ matches Ruby's arithmetic right shift for negative values too. */
5440+ return sp_bigint_div(a, sp_bigint_pow(sp_bigint_new_int(2), n));
54415441 }
54425442
54435443 sp_Bigint *sp_bigint_not(sp_Bigint *a) {