Commit 82ade25b

82ade25be1c2Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 5 files · ~5 modified

Description

fix(analyze,codegen,runtime): String#<< return-types as string; rindex(regex)

Refs #504 follow-up. Two of the remaining limitations called out when #504 closed are addressed:

  1. "foo".send(:<<) (which spinel_parse already rewrites to "foo".<<() at source level) used to print a meaningless integer. analyze's << arm returned int for any receiver that wasn't mutable_str or array; codegen then wrapped the sp_str_concat result (a const char *) in sp_int_to_s and printed the string pointer cast to int. Added a lt == "string" branch returning "string" so the surrounding p / interpolation emits sp_str_inspect (or the raw const char *) instead of int-stringifying.

  2. "foo".rindex(/regex/) SEGV'd because the codegen routed regex args through sp_str_rindex (which expects const char *) — the regex pat lowered to literal 0 and the helper called strlen(NULL). New sp_re_rindex runtime helper walks forward through successive re_exec hits and reports the latest match start. Codegen detects a regex arg via regex_pat_c_expr and routes accordingly.

rindex(regex) with no match still returns -1 (Ruby's nil shape doesn't fit the int return slot for an int-typed call); that's a deliberate limitation, not a behavior regression.

Test fixture updates: added "abcdabcd".rindex(/c/) (6) for the positive-match case and "foo".send(:<<) to lock in the inspect-as-string return.

Local: 477 tests pass, optcarrot checksum 59662.

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

Details

Commit
82ade25be1c2
Parent
79736a6c60b7

lib/sp_runtime.hmodifiedView file

@@ -973,6 +973,32 @@
973973 return 0;
974974 }
975975
976+/* `s.rindex(regex)` — last match start, in BYTE offset (matches
977+ the way sp_str_rindex reports indices for plain-string search;
978+ codepoint translation would require a UTF-8 walk and the
979+ handful of call sites that consume rindex don't need it).
980+ Walks forward through successive matches and remembers the
981+ latest start. Issue #504: previously the codegen routed
982+ `s.rindex(/re/)` to sp_str_rindex(s, 0) and SEGV'd at
983+ strlen(NULL). Returns -1 on no match. */
984+static mrb_int sp_re_rindex(mrb_regexp_pattern *pat, const char *str) {
985+ int64_t slen = (int64_t)strlen(str);
986+ int caps[2];
987+ int64_t pos = 0;
988+ mrb_int last = -1;
989+ while (pos <= slen) {
990+ int n = re_exec(pat, str, slen, pos, caps, 2);
991+ if (n <= 0) break;
992+ last = caps[0];
993+ /* Advance past the match; for zero-width matches step by 1
994+ to avoid an infinite loop. */
995+ int64_t next = caps[1];
996+ if (next <= pos) next = pos + 1;
997+ pos = next;
998+ }
999+ return last;
1000+}
1001+
9761002 static mrb_bool sp_re_match_p(mrb_regexp_pattern *pat, const char *str) {
9771003 int64_t slen = (int64_t)strlen(str);
9781004 int caps[2];