Commit e5ac4b5c

e5ac4b5c910bMerged

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

Description

runtime,codegen: regex backref returns nil for OOB / no-match

Two parts:

  • codegen: NumberedReferenceReadNode used to coerce a NULL backref to "" via cap ? cap : "". Return the raw sp_re_captures[N] (NULL when the group didn't participate or the pattern has fewer captures) so downstream nil-aware paths (.inspect / puts / || / nil?) render it correctly.
  • runtime: sp_re_match used to leave the global sp_re_captures array populated from the previous successful match when the current match failed. Clear the whole table on no-match so subsequent $1 reads as nil per MRI.

Refs #848

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
e5ac4b5c910b
Parent
caa3993ceda8

lib/sp_runtime.hmodifiedView file

@@ -1895,6 +1895,13 @@
18951895 int ncaps = 32;
18961896 int n = re_exec(pat, str, slen, 0, sp_re_caps, ncaps);
18971897 if (n > 0) { sp_re_set_captures(str, sp_re_caps, n/2); return sp_re_caps[0]; }
1898+ /* Issue #848: clear backrefs on no-match so a subsequent `$1`
1899+ reads as nil rather than the previous match's group. */
1900+ for (int i = 0; i < 10; i++) sp_re_captures[i] = NULL;
1901+ sp_re_last_str = NULL;
1902+ sp_re_match_str = NULL;
1903+ sp_re_match_pre = NULL;
1904+ sp_re_match_post = NULL;
18981905 return -1;
18991906 }
19001907