Commit 2a945df4
2a945df4172cMerged
Ryan Seys <[email protected]> · 6 months ago · 4 files · +2 added · ~2 modified
Description
fix(codegen,runtime): Integer() raises ArgumentError on unparseable input
CRuby raises ArgumentError on Integer("xyz"), Integer(""),
Integer("12abc"), etc. Spinel previously emitted a bare
(mrb_int)strtoll(s, NULL, 10) which silently returned 0 on any
unparseable input — meaning the natural CRuby idiom
def parse_int(s) = Integer(s) rescue 0
never actually triggered the rescue path. Integer("abc") returned
0 directly without raising; the rescue was effectively dead code
masking silent type-coercion bugs.
Runtime layer (lib/sp_runtime.h):
- New sp_str_to_i_strict helper that wraps strtoll with proper endptr / whitespace handling. Raises ArgumentError with a CRuby-shaped message ("invalid value for Integer(): "..."") for nil, empty / whitespace-only, no-leading-digits, or trailing-junk inputs. Whitespace skipping uses isspace() so it handles \v / \f in addition to space / tab / newline / CR.
- Forward declarations for sp_raise_cls and sp_sprintf so the new helper can call them.
- New sp_mark_in_flight_exceptions called by sp_re_mark_globals. sp_str_to_i_strict is the first runtime helper to hand a dynamically-allocated (sp_sprintf) message to sp_raise_cls; that pointer lands in sp_exc_msg[sp_exc_top-1] and lives until the rescue handler reads it. Without marking, a GC cycle between the longjmp and the handler would sweep the str-heap allocation and leave sp_exc_msg dangling. The new helper iterates in-flight slots and calls sp_mark_string on each (no-op for rodata literals, marks heap-allocated strings as live).
Codegen (spinel_codegen.rb):
- compile_no_recv_call_expr Integer() arm: routes the four string-typed dispatch sites (bare string arg, argv arg, and the two OrNode short-circuit branches) through sp_str_to_i_strict.
- @needs_setjmp = 1 so any function using Integer() gets the setjmp infrastructure for the rescue catch path.
New test: test/integer_argument_error.rb covers:
- Valid inputs unchanged (positive, zero, negative, +signed, whitespace-padded with all isspace classes including \v / \f)
- Sign-handling edge cases (+0, -0, sign with internal whitespace, double-sign, bare sign — all invalid except +0/-0)
- Edge magnitudes (LLONG_MAX / LLONG_MIN — within mrb_int range)
- Invalid inputs (xyz, "", " ", 12abc, 12.5)
- Trailing-junk variants (42x, 42 x, 42\n garbage, 42 trailing-ws)
- Leading-junk variants (x42, " x 42")
- Bare rescue with the formatted error message
- 100-raise stress loop exercising the GC-root fix: pre-fix this would non-deterministically read garbage from sp_exc_msg
- Backward-compat shape from test/endless_method_rescue.rb
test/endless_method_rescue.rb continues to pass unchanged. Integer("abc") now raises but the existing rescue catches it; same observable output as before.
Out of scope:
- Hex prefixes (Integer("0x10") → 16 in CRuby) and underscore separators (Integer("12_345") → 12345 in CRuby). Spinel's base-10 strtoll path doesn't parse these.
- Bigint auto-promotion (Integer("99999999999999999999999")). CRuby silently promotes to Bignum; Spinel currently saturates at LLONG_MAX. Strict ERANGE-raises-ArgumentError would be over-strict vs CRuby; true parity needs Bignum integration in this path.
- Mismatched-type rescue (Integer(s) rescue "default" int+string) — needs poly-boxing fix.
Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]
Details
- Commit
- 2a945df4172c
- Parent
- 1d5291554707
lib/sp_runtime.hmodifiedView file
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;}static inline char *sp_str_alloc_raw(size_t total_with_null); /* fwd decl */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;}/* Forward decls so sp_str_to_i_strict can use them. */static void sp_raise_cls(const char *cls, const char *msg);static const char *sp_sprintf(const char *fmt, ...);/* CRuby's `Integer(s)` raises ArgumentError for unparseable input (empty string, leading/trailing junk, all-whitespace). The bare `(mrb_int)strtoll(s, NULL, 10)` spinel previously emitted silently returned 0 instead, which made `Integer(s) rescue 0` always take the main branch. This helper matches CRuby semantics: skips leading/trailing whitespace, requires at least one valid digit, rejects trailing junk. Accepts an optional leading `+` / `-`. */static mrb_int sp_str_to_i_strict(const char *s) { if (!s) sp_raise_cls("ArgumentError", "invalid value for Integer(): nil"); const char *p = s; while (isspace((unsigned char)*p)) p++; if (*p == '\0') sp_raise_cls("ArgumentError", sp_sprintf("invalid value for Integer(): \"%s\"", s)); char *endptr; long long v = strtoll(p, &endptr, 10); if (endptr == p) sp_raise_cls("ArgumentError", sp_sprintf("invalid value for Integer(): \"%s\"", s)); while (isspace((unsigned char)*endptr)) endptr++; if (*endptr != '\0') sp_raise_cls("ArgumentError", sp_sprintf("invalid value for Integer(): \"%s\"", s)); return (mrb_int)v;}typedef struct{mrb_int first;mrb_int last;}sp_Range;static sp_Range sp_range_new(mrb_int f,mrb_int l){sp_Range r;r.first=f;r.last=l;return r;}typedef struct{const char**data;mrb_int len;}sp_Argv;static sp_Argv sp_argv;/* Mark active in-flight exception messages. Most raises pass string literals (rodata, marker byte ≠ 0xfe → no-op for sp_mark_string), but raises that build messages dynamically via sp_sprintf (e.g. sp_str_to_i_strict's `"invalid value for Integer(): \"%s\""`) hand a heap-allocated string to sp_raise_cls. Without marking, a GC cycle between the raise and the rescue handler reading the message would sweep the message and leave sp_exc_msg[i] dangling. The helper itself is defined further down (after sp_exc_msg / sp_exc_top are declared); only the prototype lives here. */static void sp_mark_in_flight_exceptions(void);/* Mark the regex globals as live during GC. Each holds a pointer to a string allocated via sp_str_alloc_raw on the str-heap; without this sp_str_sweep would reap them on the next collect, leaving dangling sp_mark_string(sp_re_match_pre); sp_mark_string(sp_re_match_post); for (mrb_int i = 0; i < sp_argv.len; i++) sp_mark_string(sp_argv.data[i]); sp_mark_in_flight_exceptions();}static void sp_re_set_captures(const char *str, int *caps, int ncaps) {static volatile const char *sp_last_exc_cls = sp_str_empty;static void sp_raise_cls(const char *cls, const char *msg) { if (sp_exc_top > 0) { sp_exc_msg[sp_exc_top-1] = msg; sp_exc_cls[sp_exc_top-1] = cls; sp_last_exc_cls = cls; longjmp(sp_exc_stack[sp_exc_top-1], 1); } fprintf(stderr, "unhandled exception: %s\n", msg); exit(1); }static void sp_raise(const char *msg) { sp_raise_cls("RuntimeError", msg); }static void sp_mark_in_flight_exceptions(void) { for (int i = 0; i < sp_exc_top; i++) sp_mark_string(sp_exc_msg[i]); }/* Cross-TU bridge for sp_bigint.c (compiled as a separate translation unit; can't see static helpers in this header). Defined non-staticspinel_codegen.rbmodifiedView file
Loading diff…
test/integer_argument_error.rbaddedView file
Loading diff…
test/integer_argument_error.rb.expectedaddedView file
Loading diff…