Commit 7f2fadbd
7f2fadbd9c76Merged
Ryan Seys <[email protected]> · 5 months ago · 6 files · +2 added · ~4 modified
Description
fix(math): raise Math::DomainError on out-of-domain Math.* input
CRuby raises Math::DomainError for Math.sqrt(-1), Math.log(-1),
Math.acos(2), Math.asin(-2), Math.acosh(0.5), Math.atanh(2),
Math.log(x, negative_base), and Integer.sqrt(-4). Spinel called bare
libc (silent NaN), so the idiom x = Math.sqrt(v) rescue 0.0 never fired.
Add sp_math_sqrt/log/log2/log10/acos/asin/acosh/atanh
inline wrappers in sp_runtime.h that guard each function's domain and
raise; sp_int_sqrt raises on negative input. Route the domain-restricted
Math.* dispatch through the wrappers. Wire the flattened runtime name
Math_DomainError into both exception-hierarchy tables and is_exc_name
(the StringScanner::Error -> StringScanner_Error precedent) so a
rescue Math::DomainError clause matches.
Messages match CRuby exactly: Math.* names the function WITHOUT quotes
(... out of domain - sqrt), while Integer.sqrt quotes "isqrt".
atanh raises only for |x| > 1 -- the endpoints ±1 yield ±Infinity and do
not raise. The sp_int_sqrt Newton seed is n/2, not (n+1)/2, which
overflows (signed UB) at MRB_INT_MAX. A 2-arg Math.log(x, base) raises
on a negative base (log of a negative); base 0.0/1.0 yield -0.0/NaN and do
not raise, per CRuby.
Adds test/math_domain_error.rb; expected output generated from ruby.
Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]
Details
- Commit
- 7f2fadbd9c76
- Parent
- 34f8cd5461a2
lib/sp_core.cmodifiedView file
mrb_int sp_ceildiv(mrb_int a,mrb_int b){if(b==0)sp_raise_cls("ZeroDivisionError","divided by 0");if(b==-1)return -a;mrb_int q=a/b;if(a%b!=0&&((a^b)>=0))q++;return q;}mrb_int sp_int_clamp(mrb_int v,mrb_int lo,mrb_int hi){return v<lo?lo:v>hi?hi:v;}/* Integer square root via Newton's method -- exact for the full mrb_int range. Negative input returns 0 (no exception path). */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;} mrb_int range. CRuby raises Math::DomainError on negative input (flattened runtime name "Math_DomainError"). The seed is n/2, not (n+1)/2: at n == MRB_INT_MAX the latter overflows (signed UB), and n/2 is a valid Newton seed for all n >= 2. */mrb_int sp_int_sqrt(mrb_int n){if(n<0)sp_raise_cls("Math_DomainError","Numerical argument is out of domain - \"isqrt\"");if(n<2)return n;mrb_int x=n,y=n/2;while(y<x){x=y;y=(x+n/x)/2;}return x;}/* Integer#round/ceil/floor/truncate at 10^(-ndigits). Pure integer arithmetic (no double precision loss above 2^53). 10^p fits mrb_int only for p<=18; p>=19 collapses to 0. Round-up multiply is overflow-lib/sp_runtime.hmodifiedView file
Loading diff…
src/codegen.cmodifiedView file
Loading diff…
src/codegen_call.cmodifiedView file
Loading diff…
test/math_domain_error.rbaddedView file
Loading diff…
test/math_domain_error.rb.expectedaddedView file
Loading diff…