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

@@ -96,6 +96,30 @@
9696 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;}
9797 static inline char *sp_str_alloc_raw(size_t total_with_null); /* fwd decl */
9898 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;}
99+
100+/* Forward decls so sp_str_to_i_strict can use them. */
101+static void sp_raise_cls(const char *cls, const char *msg);
102+static const char *sp_sprintf(const char *fmt, ...);
103+
104+/* CRuby's `Integer(s)` raises ArgumentError for unparseable input
105+ (empty string, leading/trailing junk, all-whitespace). The bare
106+ `(mrb_int)strtoll(s, NULL, 10)` spinel previously emitted silently
107+ returned 0 instead, which made `Integer(s) rescue 0` always take
108+ the main branch. This helper matches CRuby semantics: skips
109+ leading/trailing whitespace, requires at least one valid digit,
110+ rejects trailing junk. Accepts an optional leading `+` / `-`. */
111+static mrb_int sp_str_to_i_strict(const char *s) {
112+ if (!s) sp_raise_cls("ArgumentError", "invalid value for Integer(): nil");
113+ const char *p = s;
114+ while (isspace((unsigned char)*p)) p++;
115+ if (*p == '\0') sp_raise_cls("ArgumentError", sp_sprintf("invalid value for Integer(): \"%s\"", s));
116+ char *endptr;
117+ long long v = strtoll(p, &endptr, 10);
118+ if (endptr == p) sp_raise_cls("ArgumentError", sp_sprintf("invalid value for Integer(): \"%s\"", s));
119+ while (isspace((unsigned char)*endptr)) endptr++;
120+ if (*endptr != '\0') sp_raise_cls("ArgumentError", sp_sprintf("invalid value for Integer(): \"%s\"", s));
121+ return (mrb_int)v;
122+}
99123 typedef struct{mrb_int first;mrb_int last;}sp_Range;
100124 static sp_Range sp_range_new(mrb_int f,mrb_int l){sp_Range r;r.first=f;r.last=l;return r;}
101125
@@ -856,6 +880,17 @@
856880 typedef struct{const char**data;mrb_int len;}sp_Argv;
857881 static sp_Argv sp_argv;
858882
883+/* Mark active in-flight exception messages. Most raises pass string
884+ literals (rodata, marker byte ≠ 0xfe → no-op for sp_mark_string),
885+ but raises that build messages dynamically via sp_sprintf (e.g.
886+ sp_str_to_i_strict's `"invalid value for Integer(): \"%s\""`)
887+ hand a heap-allocated string to sp_raise_cls. Without marking, a
888+ GC cycle between the raise and the rescue handler reading the
889+ message would sweep the message and leave sp_exc_msg[i] dangling.
890+ The helper itself is defined further down (after sp_exc_msg /
891+ sp_exc_top are declared); only the prototype lives here. */
892+static void sp_mark_in_flight_exceptions(void);
893+
859894 /* Mark the regex globals as live during GC. Each holds a pointer to a
860895 string allocated via sp_str_alloc_raw on the str-heap; without this
861896 sp_str_sweep would reap them on the next collect, leaving dangling
@@ -869,6 +904,7 @@
869904 sp_mark_string(sp_re_match_pre);
870905 sp_mark_string(sp_re_match_post);
871906 for (mrb_int i = 0; i < sp_argv.len; i++) sp_mark_string(sp_argv.data[i]);
907+ sp_mark_in_flight_exceptions();
872908 }
873909
874910 static void sp_re_set_captures(const char *str, int *caps, int ncaps) {
@@ -1363,6 +1399,7 @@
13631399 static volatile const char *sp_last_exc_cls = sp_str_empty;
13641400 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); }
13651401 static void sp_raise(const char *msg) { sp_raise_cls("RuntimeError", msg); }
1402+static void sp_mark_in_flight_exceptions(void) { for (int i = 0; i < sp_exc_top; i++) sp_mark_string(sp_exc_msg[i]); }
13661403
13671404 /* Cross-TU bridge for sp_bigint.c (compiled as a separate translation
13681405 unit; can't see static helpers in this header). Defined non-static