Commit dfb930ff

dfb930ffa39fMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 7 months ago · 2 files · ~2 modified

Description

feat: bigint type support with auto-promotion from loop multiplication

Bigint integration:

  • Auto-detect variables that need bigint promotion: x = x * y (or x *= y) pattern inside while loops
  • Propagate bigint type to variables involved in bigint expressions
  • Compile bigint arithmetic: +, -, *, /, %, **, comparisons
  • Both operands can be int or bigint (auto-conversion via sp_bigint_new_int)
  • puts/print support for bigint via sp_bigint_to_s
  • bigint.to_s and bigint.to_i methods
  • Type inference: bigint ops return bigint, propagation through expressions

Bigint library fixes:

  • sp_bigint_to_s: fast path for small numbers (sz <= 2) using sprintf
  • Fixed infinite loop in large number to_s

Known limitation: pidigits n>7 is very slow due to mpz_mdiv cost and bigint objects are not GC-managed (leaked). Future work: integrate bigint with Spinel GC.

67 tests pass (bm_ao_render FAIL is pre-existing self-compiled issue).

Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]

Details

Commit
dfb930ffa39f
Parent
b422aedfc2cc

lib/sp_bigint.cmodifiedView file

@@ -5357,27 +5357,30 @@
53575357 const char *sp_bigint_to_s(sp_Bigint *b) {
53585358 sp_bigint_init_ctx();
53595359 mpz_t *z = &b->mpz;
5360- if (z->sz == 0 || (z->sz == 1 && z->p[0] == 0)) {
5361- char *s = (char*)malloc(2); s[0] = '0'; s[1] = 0; return s;
5360+ /* Small number fast path */
5361+ if (z->sz <= 2) {
5362+ int64_t v = sp_bigint_to_int(b);
5363+ char *s = (char*)malloc(24);
5364+ snprintf(s, 24, "%lld", (long long)v);
5365+ return s;
53625366 }
5367+ /* Large number: use mpz_sizeinbase for allocation, repeated div/mod for digits */
53635368 size_t est = mpz_sizeinbase(z, 10) + 2;
5364- char *buf = (char*)malloc(est);
5365- char *p = buf + est - 1;
5369+ char *buf = (char*)malloc(est + 1);
5370+ char *p = buf + est;
53665371 *p = 0;
5367- mpz_t tmp;
5372+ mpz_t tmp, rem, ten;
53685373 mpz_init_set(sp_mpz_ctx, &tmp, z);
53695374 if (tmp.sn < 0) tmp.sn = 1;
5370- mpz_t ten, rem;
53715375 mpz_init_set_int(sp_mpz_ctx, &ten, 10);
53725376 mpz_init(sp_mpz_ctx, &rem);
5373- while (mpz_cmp(sp_mpz_ctx, &tmp, &ten) >= 0 || (tmp.sz > 0 && !(tmp.sz == 1 && tmp.p[0] == 0))) {
5377+ while (tmp.sz > 0 && !(tmp.sz == 1 && tmp.p[0] == 0)) {
53745378 mpz_mmod(sp_mpz_ctx, &rem, &tmp, &ten);
53755379 int digit = (rem.sz > 0) ? (int)(rem.p[0]) : 0;
53765380 *--p = '0' + digit;
53775381 mpz_mdiv(sp_mpz_ctx, &tmp, &tmp, &ten);
5378- if (tmp.sz == 0 || (tmp.sz == 1 && tmp.p[0] == 0)) break;
53795382 }
5380- if (p == buf + est - 1 || *p == 0) *--p = '0';
5383+ if (*p == 0) *--p = '0';
53815384 if (z->sn < 0) *--p = '-';
53825385 char *result = (char*)malloc(strlen(p) + 1);
53835386 strcpy(result, p);