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
static void sp_raise_cls(const char *cls, const char *msg);static const char *sp_sprintf(const char *fmt, ...);/* CRuby's `String#to_i` accepts a leading sign, then digits with `_` 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 stops at the first `_`, returning 1 instead. Issue #619. */static mrb_int sp_str_to_i_cruby(const char *s) { if (!s) return 0; const char *p = s; while (isspace((unsigned char)*p)) p++; int neg = 0; if (*p == '+') p++; else if (*p == '-') { neg = 1; p++; } mrb_int v = 0; int any = 0; while (*p) { if (*p >= '0' && *p <= '9') { v = v * 10 + (*p - '0'); any = 1; p++; } else if (*p == '_' && any && p[1] >= '0' && p[1] <= '9') { p++; } else { break; } } if (!any) return 0; return neg ? -v : v;}/* 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 silentlyspinel_codegen.rbmodifiedView file
Loading diff…
test/string_to_i_underscore.rbaddedView file
Loading diff…
test/string_to_i_underscore.rb.expectedaddedView file
Loading diff…