Commit ae955567e2 for perl
commit ae955567e2234d56edf7f31fae3b7347d800f013
Author: Richard Leach <rich+perl@hyphen-dash-hyphen.info>
Date: Thu Nov 12 10:26:54 2026 +0000
S_flatten_inner_branches: don't flatten if capture group exists
Flattening of nested branches didn't always preserve capture group
behaviour as intended.
While it might be possible to fix things up so that such branches
_can_ be flattened, this commit chooses the cautious approach first,
adding a check for capture groups and returning without flattening
if any are found.
diff --git a/regcomp.c b/regcomp.c
index 55a44c3246..a50fd0284c 100644
--- a/regcomp.c
+++ b/regcomp.c
@@ -3087,6 +3087,18 @@ S_flatten_inner_branches(pTHX_ RExC_state_t *pRExC_state, regnode *first_outer_b
regnode *prev_outer_br = NULL;
regnode *outer_br = first_outer_br;
+ /* Don't flatten if the outer branch contains capture group(s), as these
+ * may not be correctly reset if the match backtracks.
+ * Note: This is a conservative approach, it may be possible to fix up
+ * the capture groups with more work. */
+ regnode *last_br = first_outer_br;
+ regnode *next;
+ while ( (next = regnext(last_br)) && OP(next) == BRANCH) {
+ last_br = next;
+ }
+ if (BRANCH_LAST_CAPTURE(last_br) != BRANCH_CAPTURE_FLOOR(first_outer_br))
+ return;
+
while (outer_br && OP(outer_br) == BRANCH) {
/* Get next outer BRANCH node - or the tail */
regnode *outer_successor = regnext(outer_br);
diff --git a/t/re/re_tests b/t/re/re_tests
index eea1e9fa8e..482d6c63a8 100644
--- a/t/re/re_tests
+++ b/t/re/re_tests
@@ -2408,6 +2408,8 @@ a+X(*COMMIT)j aXaXj n - - - PLUS skip after (*COMMIT) [ASCII]
(?{})\A(?:(a)?b)+(?(1)a|c)\z abbc y $& abbc - conditional sees the skipped capture as unset
(?{})\A(?:(\x{100})?b)+\z \x{100}bb y ${\(defined($1) ? $1 : q(undef))} undef - Unicode optional capture
(?{})\A(?:(a)?b)+\z abab y $1 a - final participating capture is preserved
+(?:(?:y(b)|a)|x)+ ybx y ${\(defined($1) ? $1 : q(undef))} undef - branch flattening preserves capture reset
+(?:x(b)|(?:(?:y|z)|w))+ xby y ${\(defined($1) ? $1 : q(undef))} undef - branch flattening preserves capture reset
# GH #24944
/\A\ba*\z/m a y $& a - SBOL and BOUND start class should match