Commit b3d53645
b3d536453a1aMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified
Description
Implement String#index with a Regexp argument
"hello".index(/l/) failed to compile: the regex argument lowered to 0
and was fed to the plain-string sp_str_index_opt path, producing a
type-mismatched call. Route a Regexp argument through a new
sp_re_index_poly (first match start as boxed Integer | nil, mirroring the
existing sp_re_rindex_poly), which also sets $~ as CRuby's
String#index(regex) does.
Fixes #1310
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- b3d536453a1a
- Parent
- db9ce80450c4
lib/sp_runtime.hmodifiedView file
@@ -2456,6 +2456,12 @@
24562456
static mrb_int sp_str_index_from_opt(const char *s, const char *sub, mrb_int start) { mrb_int n = sp_str_index_from(s, sub, start); return n < 0 ? SP_INT_NIL : n; }24572457
static mrb_int sp_str_rindex_opt(const char *s, const char *sub) { mrb_int n = sp_str_rindex(s, sub); return n < 0 ? SP_INT_NIL : n; }24582458
static sp_RbVal sp_re_rindex_poly(mrb_regexp_pattern *pat, const char *str) { mrb_int n = sp_re_rindex(pat, str); return n < 0 ? sp_box_nil() : sp_box_int(n); }2459+
/* `s.index(regex)` -- first match start (byte offset, as sp_re_match reports;2460+
matches the rindex regex variant, which also reports bytes). sp_re_match2461+
sets $~ as a side effect, which CRuby's String#index(regex) also does.2462+
Boxed Integer | nil. The plain-string path would lower the regex pattern to2463+
0 and feed a bogus arg to sp_str_index_opt. */2464+
static sp_RbVal sp_re_index_poly(mrb_regexp_pattern *pat, const char *str) { mrb_int n = sp_re_match(pat, str); return n < 0 ? sp_box_nil() : sp_box_int(n); }24592465
/* CRuby-compatible =~ wrapper: SP_TAG_INT(pos) on match, SP_TAG_NIL24602466
on miss. Codegen routes the `=~` operator here so24612467
`("abc" =~ /xyz/).nil?` answers true and `puts("abc" =~ /xyz/)`spinel_codegen.rbmodifiedView file
Loading diff…
test/string_index_regex.rbaddedView file
Loading diff…
test/string_index_regex.rb.expectedaddedView file
Loading diff…