Commit 42d4ed1403 for perl

commit 42d4ed140334977ca219455f5cab87d15018ac87
Author: Richard Leach <rich+perl@hyphen-dash-hyphen.info>
Date:   Wed Nov 11 21:33:47 2026 +0000

    study_chunk: flattened branches could lead with a NOTHING

    When preparing for a TRIE, `Perl_study_chunk` did not expect a
    valid branch sequence to start with a `NOTHING` regop.

    With the addition of nested branch flattening, that could now
    arise. For example, an empty branch and a non-empty branch
    that are both flattened:

        /^(?:|(?:)a+)$/

    This commit adds a branch chain scan to detect this eventuality.

diff --git a/regcomp_study.c b/regcomp_study.c
index 38195f73d7..b9cbe6b7b1 100644
--- a/regcomp_study.c
+++ b/regcomp_study.c
@@ -2161,7 +2161,19 @@ Perl_study_chunk(pTHX_
                                  * is 'first' then we can turn the whole thing
                                  * into a NOTHING
                                  */
-                                if ( startbranch == first ) {
+                                bool empty = startbranch == first;
+                                regnode *br = startbranch;
+
+                                /* A branch starting with a NOTHING isn't guaranteed
+                                 * to be empty. Flattening of nested branches could
+                                 * cause this to occur. */
+                                for (; empty && br != scan; br = regnext(br)) {
+                                    regnode * const noper = REGNODE_AFTER(br);
+                                    if (OP(noper) != NOTHING || regnext(noper) < tail)
+                                        empty = false;
+                                }
+
+                                if (empty) {
                                     regnode *opt;
                                     /* the entire thing is a NOTHING sequence,
                                      * something like this: (?:|) So we can
diff --git a/t/re/re_tests b/t/re/re_tests
index f4091a137c..eea1e9fa8e 100644
--- a/t/re/re_tests
+++ b/t/re/re_tests
@@ -2213,6 +2213,11 @@ ABCF|BCD[Ee]|C[Gg]	ABCDE	y	$&	BCDE	-	# GH 22892 - AHO-CORASICK bug
 (?:zz|(?:a(*THEN)b|c)|d)	a	n	$&	a	-	(*THEN) stays nested (no match)
 (?:zz|(?:a(*THEN)b|c)|d)	d	y	$&	d	-	(*THEN) stays nested (match)

+# Nested branch flattening and NOTHING nodes are studied correctly
+^(?:|(?:)a+)$	aa	y	$&	aa	-	NOTHING branch followed by valid nodes
+^(?:|(?:(?:a+|b)|))$	aa	y	$&	aa	-	NOTHING branch followed by valid nodes
+^(?:|(?:(?:(a)|b)|))$	a	y	$1	a	-	NOTHING branch followed by valid nodes
+
 # Prefixes extracted from jump tries must remain attached to those tries.
 # Otherwise an enclosing trie pass can discard the branch structure needed
 # by backtracking control verbs.  Keep both failing and successful paths here