Commit 478826f8

478826f8b70aMerged

Ryan Seys <[email protected]> · 6 months ago · 4 files · ~4 modified

Description

feat(codegen,runtime): regex back-reference $+ returns last paren match

Prism delivers the symbolic regex back-reference $+ as a BackReferenceReadNode, but spinel_codegen rejected it as "not supported". The other symbolic back-references ($&, $~, $``, $') had already been threaded through sp_re_set_capturesruntime state;$+` was the last symbolic gap.

$+ is the contents of the highest-indexed capture group that participated in the match -- for /(a)(b)/ matching "ab" it's "b"; for /(a)(b)?/ matching just "a" it steps back to "a". Add a small runtime helper sp_re_last_paren_match that walks sp_re_captures[] from index 9 down and returns the first non-NULL entry, then add the codegen arms (both the BackReferenceReadNode path and the GlobalVariableReadNode path that prism uses for the non-back-ref symbolic globals) wrapping the helper in a null-guarded ternary mirroring the existing $& / $`` / $'` idiom.

The English-name aliases $LAST_MATCH_INFO / $LAST_PAREN_MATCH intentionally fall through to the bare-global path. In CRuby those require require 'English'; without it they're nil, and spinel without an English stdlib should match that "unbound global" behaviour rather than diverge by silently aliasing.

Test extends test/back_ref.rb with two $+ shapes (last-group participates; last-optional-group does not) alongside the existing $& / $`` / $'` regressions. Bootstrap fixpoint green; 618 / 618 pass.

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

Details

Commit
478826f8b70a
Parent
c360ff731f28

lib/sp_runtime.hmodifiedView file

@@ -1393,6 +1393,19 @@
13931393 sp_mark_fiber_root_storage();
13941394 }
13951395
1396+/* `$+` / `$LAST_PAREN_MATCH` — contents of the highest-indexed group
1397+ that participated in the match. Walks sp_re_captures[] from 9 down
1398+ and returns the first non-NULL entry. NULL when no group matched
1399+ (codegen ternary falls back to ""). Matches CRuby's behaviour:
1400+ for /(a)(b)?/ matching "a", $+ is "a"; for /(a)(b)/ matching "ab",
1401+ $+ is "b". */
1402+static const char *sp_re_last_paren_match(void) {
1403+ for (int i = 9; i >= 1; i--) {
1404+ if (sp_re_captures[i]) return sp_re_captures[i];
1405+ }
1406+ return NULL;
1407+}
1408+
13961409 static void sp_re_set_captures(const char *str, int *caps, int ncaps) {
13971410 sp_re_last_str = str;
13981411 for (int i = 0; i < 10; i++) sp_re_captures[i] = NULL;