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
sp_Bigint *sp_bigint_shl(sp_Bigint *a, int64_t n) { if (n < 0) return sp_bigint_shr(a, -n); if (n >= 64) return sp_bigint_new_int(0); return sp_bigint_new_int(sp_bigint_to_int(a) << n); /* x << n == x * 2^n at arbitrary precision (the old `to_int << n` truncated the bigint to 64 bits and overflowed the shift). */ return sp_bigint_mul(a, sp_bigint_pow(sp_bigint_new_int(2), n));}sp_Bigint *sp_bigint_shr(sp_Bigint *a, int64_t n) { if (n < 0) return sp_bigint_shl(a, -n); if (n >= 64) { /* arithmetic right shift: negative -> -1, positive -> 0 */ return sp_bigint_new_int(sp_bigint_to_int(a) < 0 ? -1 : 0); } return sp_bigint_new_int(sp_bigint_to_int(a) >> n); /* x >> n == floor(x / 2^n) at arbitrary precision (the old `to_int >> n` truncated the bigint to 64 bits). sp_bigint_div floors toward -inf, which matches Ruby's arithmetic right shift for negative values too. */ return sp_bigint_div(a, sp_bigint_pow(sp_bigint_new_int(2), n));}sp_Bigint *sp_bigint_not(sp_Bigint *a) {src/analyze_infer.cmodifiedView file
Loading diff…
src/codegen_call.cmodifiedView file
Loading diff…
test/bigint_pow_shift.rbaddedView file
Loading diff…
test/bigint_pow_shift.rb.expectedaddedView file
Loading diff…