Commit 12838d1f

12838d1f308aMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 4 files · +2 added · ~2 modified

Description

fix(runtime): String#to_i accepts _ between digits, stops at junk

CRuby's String#to_i reads an optional sign, then runs of digits with _ allowed between consecutive digits, and stops at the first non-digit (returning what it has so far rather than raising). "1_2_3asdf" -> 123. spinel previously emitted (mrb_int)atoll(s) which treats _ as terminator and returns 1.

Adds sp_str_to_i_cruby next to sp_str_to_i_strict (the ArgumentError-raising sibling used by Integer(s)) and routes the two String#to_i codegen sites through it.

One of the puzzles in Refs #619.

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

Details

Commit
12838d1f308a
Parent
3bb3e30ec0fa

lib/sp_runtime.hmodifiedView file

@@ -121,6 +121,35 @@
121121 static void sp_raise_cls(const char *cls, const char *msg);
122122 static const char *sp_sprintf(const char *fmt, ...);
123123
124+/* CRuby's `String#to_i` accepts a leading sign, then digits with
125+ `_` between consecutive digits, and stops at the first non-digit
126+ (returning what it has so far rather than raising). `"1_2_3asdf"`
127+ -> 123. spinel previously emitted `(mrb_int)atoll(s)` which stops
128+ at the first `_`, returning 1 instead. Issue #619. */
129+static mrb_int sp_str_to_i_cruby(const char *s) {
130+ if (!s) return 0;
131+ const char *p = s;
132+ while (isspace((unsigned char)*p)) p++;
133+ int neg = 0;
134+ if (*p == '+') p++;
135+ else if (*p == '-') { neg = 1; p++; }
136+ mrb_int v = 0;
137+ int any = 0;
138+ while (*p) {
139+ if (*p >= '0' && *p <= '9') {
140+ v = v * 10 + (*p - '0');
141+ any = 1;
142+ p++;
143+ } else if (*p == '_' && any && p[1] >= '0' && p[1] <= '9') {
144+ p++;
145+ } else {
146+ break;
147+ }
148+ }
149+ if (!any) return 0;
150+ return neg ? -v : v;
151+}
152+
124153 /* CRuby's `Integer(s)` raises ArgumentError for unparseable input
125154 (empty string, leading/trailing junk, all-whitespace). The bare
126155 `(mrb_int)strtoll(s, NULL, 10)` spinel previously emitted silently