Commit 7819b258
7819b258d2beMerged
Ryan Seys <[email protected]> · 6 months ago · 4 files · +2 added · ~2 modified
Description
fix(codegen): Integer.sqrt(n) integer square root
Integer.sqrt was unsupported and emitted 0. Adds two arms:
- infer_call_type: Integer.sqrt → "int" (so result type-checks at use sites and routes through the int print path).
- compile_constant_recv_expr: lower to
(mrb_int)sqrt((double)n)using the libm sqrt and a cast back to integer.
Distinct from Math.sqrt, which returns a float.
Test: integer_sqrt covers 0, 1, 16, 99, 100, 101, 1_000_000.
Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]
Details
- Commit
- 7819b258d2be
- Parent
- 8ff9aa915a30
lib/sp_runtime.hmodifiedView file
@@ -81,6 +81,11 @@
8181
static mrb_int sp_powmod(mrb_int base,mrb_int exp,mrb_int mod){if(mod==0)return 0;mrb_int r=1;mrb_int m=mod<0?-mod:mod;if(m==1){r=0;}else{base=base%m;if(base<0)base+=m;while(exp>0){if(exp%2==1)r=r*base%m;exp=exp/2;base=base*base%m;}}if(mod<0&&r>0)r-=m;return r;}8282
static mrb_int sp_ceildiv(mrb_int a,mrb_int b){if(b==0)return 0;if(b==-1)return -a;mrb_int q=a/b;if(a%b!=0&&((a^b)>=0))q++;return q;}8383
static mrb_int sp_int_clamp(mrb_int v,mrb_int lo,mrb_int hi){return v<lo?lo:v>hi?hi:v;}84+
/* Integer square root via Newton's method — exact for the full mrb_int85+
range (no double-precision rounding loss for n > 2^53). CRuby raises86+
on negative input; we mirror Spinel's other arithmetic helpers and87+
return 0 to avoid an exception path. */88+
static mrb_int sp_int_sqrt(mrb_int n){if(n<0)return 0;if(n<2)return n;mrb_int x=n,y=(x+1)/2;while(y<x){x=y;y=(x+n/x)/2;}return x;}8489
static inline char *sp_str_alloc_raw(size_t total_with_null); /* fwd decl */8590
static const char*sp_int_chr(mrb_int n){char*s=sp_str_alloc_raw(2);s[0]=(char)n;s[1]=0;return s;}8691
typedef struct{mrb_int first;mrb_int last;}sp_Range;spinel_codegen.rbmodifiedView file
Loading diff…
test/integer_sqrt.rbaddedView file
Loading diff…
test/integer_sqrt.rb.expectedaddedView file
Loading diff…