← Back to Pull requests

Fixups to AHO-CORASICK matching. #24937

Merged
demerphq merged 26 files (4008 lines) on Oct 30, 2026 18:25 UTC
View on GitHub
demerphq demerphq commented on Oct 10, 2026 22:40 UTC
Author

Resolve https://github.com/Perl/perl5/issues/24934 and
https://github.com/Perl/perl5/issues/24935.

Implements a grab bag of optimizations to the AHO-CORASICK start class optimization.

Uses Boyer-Moore-Horspool matching to construct a shift table which can allow scanning for the start of a match at very high speeds. (Think Boyer-Moore for a list of words.) However, BMH can slow things down in certain pathological cases, which is where we use a start class filter (similar to the old bitmap) to filter out bad starts, this combines with some logic to detect repeated short strings and consume them very quickly. The end result is that for the cases where the old bitmap was very fast we aren't quite as fast, but for the places where the bitmap was no help at all we can sometimes scream. Overall we seem to be very consistently fast, and sometimes very fast.

At the same time I added support for a start-octet map which uses the fold-inversion logic to build a bitmap we can use with utf8 folded data, which means case insensitive matches are now faster as well. Not as fast as case sensitive ones, alas.

There were also some other bookkeeping refinements which improved trie/ac matching, so even the base case got faster as well.

Lastly I found a bug that was introduced by the more aggressive prefix extraction that the octet patch included. An edge case that we hadnt encountered before, it is now fixed.

Median elapsed seconds; lower is faster. All builds use matching GCC 13.3 -O2 settings, without debugging or threads.

| Workload | Perl 5.44 | blead/ | Previous patch | Latest patch |
|---|---:|---:|---:|---:|
| /walrus\|cat/, 200M As + cat, Latin-1 | 0.3312 | 1.8074 | 0.4887 | 0.0478 |
| Same, UTF-8 flagged | 1.4617 | 1.8524 | 0.5023 | 0.0485 |
| 575 SV identifiers, source corpus, Latin-1 | 0.2730 | 0.4970 | 0.3206 | 0.2988 |
| Same source, UTF-8 flagged | 0.4455 | 0.5267 | 0.3097 | 0.3037 |
| /walrus\|cat/, random ASCII, Latin-1 | 0.0176 | 0.1004 | 0.0266 | 0.0299 |
| /abcdefgh\|ijklmnop/, random ASCII, Latin-1 | 0.0178 | 0.1042 | 0.0101 | 0.0302 |
| Same, UTF-8 flagged | 0.0807 | 0.1028 | 0.0106 | 0.0327 |
| /fooA\|barB/, repeated AB, Latin-1 | 0.0683 | 0.4054 | 0.00572 | 0.00621 |

Medians of three trials. The previous-patch column comes from the preceding benchmark run; the other three columns are fresh measurements.

Workload sizes:

  • 200M A case: three scans.

  • Source corpus: 2,084,667 octets, scanned 50 times.

  • Random ASCII: 1 MiB, scanned 32 times.

  • Repeated AB: 1 MiB, scanned 128 times.
  • This set of changes requires a perldelta entry, and it is included.
  • Diff: 4008 lines (+3641 / -367) across 26 files Reviewer: richardleach Review duration: 28544m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.72) × (1 − Review Confidence (0.91)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 4008 lines diff across 26 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.90 · 5 substantive comment(s)
    0.90
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    91%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    49 items
    demerphq demerphq commented on Oct 11, 2026 09:36 UTC
    Author

    @khwilliamson can you check out the bitmap for folded data please. I am not sure i used the inverted fold data properly.

    khwilliamson khwilliamson commented on code on Oct 11, 2026 15:32 UTC
    Code Review
    regcomp_trie.c:1
    @@ -1720,6 +1732,84 @@ Perl_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
                  : MADE_TRIE;
     }
     
    +/* Convert one trie path to the octets seen in a Latin-1 target.  A path with
    + * one octet per source character contains only UTF-8 invariant characters,
    + * so its octets already have the target representation.  Longer paths are
    + * UTF-8 encodings and can be downgraded only when every character fits in
    + * Latin-1.  The caller excludes case-folded tries. */
    +static bool
    +S_ac_path_as_latin1(const U8 *path, const U32 path_len, const U32 source_chars,
    +                    U8 *latin1_path, U32 *latin1_len)
    +{
    +    if (path_len == source_chars) {
    +        Copy(path, latin1_path, path_len, U8);
    +        *latin1_len = path_len;
    +        return TRUE;
    +    }
    +
    +    if (path_len < source_chars)
    +        return FALSE;
    +
    +    {

    We don't need this kind of block in C99, and I think it's distracting. But I would understand if you have a plan to make the block conditionally executed, and want to pre-space it

    richardleach richardleach commented on Oct 14, 2026 12:15 UTC
    Contributor

    At first glance, on my dev VM.
    my $x = ("A"x200_000_000)."cat"; $x =~ /walrus|cat/;': has gone from 5-6 times slower than pre-24712 to 2-3 times faster.
    my $x = ("cat"x20_000_000)."cat"; while ($x =~ /walrus|cat/g) {} seems about 10% slower than on 5.44.0 though.

    I'll start going through the commits in a bit.

    richardleach richardleach commented on Oct 14, 2026 13:13 UTC
    Contributor

    * my $x = ("cat"x20_000_000)."cat"; while ($x =~ /walrus|cat/g) {} seems about 10% slower than on 5.44.0 though.

    Scrap that, I mustn't have had the latest updates from this branch.

    richardleach richardleach commented on code on Oct 14, 2026 13:20 UTC
    Code Review
    regexec.c:1
    @@ -2893,7 +2893,10 @@ S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
                  * where if there were no expansion we should fail.  Unclear if
                  * worth the expense */
     
    -            while (s <= e) {
    +            /* HOP3c clamps e to s when too few characters remain.  A
    +             * nonempty folded literal cannot match at strend, where
    +             * UTF8_SAFE_SKIP returns zero and cannot advance the loop. */
    +            while (s < strend && s <= e) {

    Does this need to check s < strend? Does s <= e not cover it (or could it not be made to cover it)?

    demerphq demerphq commented on code on Oct 15, 2026 11:11 UTC
    Code Review
    regexec.c:1
    @@ -2893,7 +2893,10 @@ S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
                  * where if there were no expansion we should fail.  Unclear if
                  * worth the expense */
     
    -            while (s <= e) {
    +            /* HOP3c clamps e to s when too few characters remain.  A
    +             * nonempty folded literal cannot match at strend, where
    +             * UTF8_SAFE_SKIP returns zero and cannot advance the loop. */
    +            while (s < strend && s <= e) {

    uh, good catch, fixed.

    demerphq demerphq commented on Oct 15, 2026 11:17 UTC
    Author

    my $x = ("cat"x20_000_000)."cat"; while ($x =~ /walrus|cat/g) {}

    FWIW, this is the kind of benchmark I personally try to avoid. It doesn't do any work, so the timing is very artificial. Often when you put some kind of sane workload in the loop all of a sudden the 10% increase is a negligible increase because the work in the body swamps everything else.

    richardleach richardleach commented on Oct 15, 2026 21:08 UTC
    Contributor

    S_regmatch comments at https://github.com/Perl/perl5/blob/e910fa18bdd07a8b2d0fe9247c03938a3882b3c9/regexec.c#L7318
    say that:

                    /* Start-class filtering is disabled while trie prefix
                     * extraction is being brought into alignment with the
                     * executable start state. */
    

    Could some of the same mechanisms introduced in this PR apply there too?

    richardleach richardleach commented on code on Oct 15, 2026 21:11 UTC
    Code Review
    regexec.c:1
    @@ -3385,12 +3446,41 @@ S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
                 /* what trie are we using right now */
                 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ TRIE_DATA_SLOT(c) ];
                 reg_trie_data *trie = (reg_trie_data*)progi->data->data[aho->trie];
    +            const U8 * const prefilter = aho->prefilter;
    +            const U8 *start_map = prefilter
    +                ? prefilter + REG_AC_PREFILTER_MAP_OFFSET : NULL;
    +            const U8 *bmh_shift = prefilter
    +                ? prefilter + (utf8_target
    +                    ? REG_AC_PREFILTER_UTF8_BMH_OFFSET
    +                    : REG_AC_PREFILTER_LATIN1_BMH_OFFSET) : NULL;
    +            const U8 bmh_minlen = utf8_target ? aho->utf8_minlen
    +                                               : aho->latin1_minlen;
    +            const U8 start_mask = utf8_target ? REG_AC_PREFILTER_UTF8_MASK
    +                                               : REG_AC_PREFILTER_LATIN1_MASK;
    +            const bool has_bmh = prefilter && bmh_minlen;
    +
    +            /* Every literal path requires a codepoint above Latin-1, so
    +             * an unflagged target cannot match this start-of-program trie. */
    +            if (!utf8_target && FLAGS(c) == EXACT
    +                && trie->startstate == 1
    +                && !trie->states[1].wordnum
    +                && !trie->prefixlen_octets && !trie->prefixlen_chars
    +                && (trie->prop_flags & TRIE_CP_NO_LATIN1_WORDS))

    1. Is this the optimum order of checks for the fastest fail?
    2. Could some of this be hoisted out of _S_find_byclass_ if it's unchanging across runs?

    richardleach richardleach commented on code on Oct 15, 2026 21:20 UTC
    Code Review
    regexec.c:1
    @@ -3463,14 +3551,75 @@ S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
                     while (state && (foldlen || octets_remaining
                                      || uc < (U8*)strend)) {
                         bool failed = false;
    +                    bool transitioned_from_root = false;
                         U32 word = aho->states[ state ].wordnum;
    +                    U8 *point;
    +                    bool point_may_be_start;
     
                         if( state == 1 ) {
                             if (uc >(U8*)last_start) break;
    +
    +                        /* A prefilter may skip only from the AC root.  Once
    +                         * AC has consumed a prefix, its failure state must
    +                         * retain that partial-match information. */
    +                        if (prefilter && !foldlen && !octets_remaining) {
    +                            /* BMH positions its anchor by encoded octet
    +                             * length.  Folded tries have no BMH table and
    +                             * use only the map of original target starts.
    +                             * Both require character boundaries in UTF-8. */
    +                            while (uc < (U8*)strend && uc <= (U8*)last_start) {
    +                                U8 distance = 0;
    +
    +                                if (utf8_target && UTF8_IS_CONTINUATION(*uc)) {
    +                                    uc++;
    +                                    pointpos = 0;
    +                                    continue;
    +                                }
    +                                if (has_bmh) {
    +                                    if ((STRLEN)((U8*)strend - uc) < bmh_minlen)
    +                                        break;
    +                                    distance = bmh_shift[uc[bmh_minlen - 1]];
    +                                }
    +
    +                                /* A start-map miss proves that no literal
    +                                 * starts here, regardless of the BMH shift.
    +                                 * The helper checks each later start
    +                                 * until it has a full rejected word.  Equal
    +                                 * following words repeat those rejected
    +                                 * octets, so they cannot contain a start.
    +                                 * UTF-8 continuation octets cannot be starts
    +                                 * either.  The checked window therefore lets
    +                                 * us skip equal windows without consulting
    +                                 * their BMH anchors. */
    +                                if (!(start_map[*uc] & start_mask))
    +                                {
    +                                    /* The helper consumes at least the
    +                                     * rejected octet at uc. */
    +                                    uc = (U8 *)S_scan_repeated_uv_blocks(
    +                                        uc, (U8*)strend,
    +                                        MIN((U8*)last_start, (U8*)strend - 1),
    +                                        start_map, start_mask, utf8_target);
    +                                    pointpos = 0;
    +                                    continue;
    +                                }
    +                                if (!distance)
    +                                    break;
    +                                uc += distance;
    +                                pointpos = 0;
    +                            }
    +                            if (uc >= (U8*)strend || uc > (U8*)last_start)
    +                                break;
    +                        }
                         }
     
    +                    /* The prefilter may have moved uc to a later candidate.
    +                     * Record that position if the root transition succeeds. */
    +                    point = uc;
    +                    point_may_be_start = !octets_remaining
    +                        && (!utf8_target || !UTF8_IS_CONTINUATION(*uc));

    Is this a per-character thing being tracked inside a per-octet loop? Does it need to be done per octet, or is there a way to amortize or otherwise keep track until the octet loop ends?

    richardleach richardleach commented on Oct 17, 2026 21:11 UTC
    Contributor

    Not sure if I'm understanding the implementation correctly, but I've got two main concerns that I'm still feeling out:
    1. If the space to search contains repetition with a periodicity that a word doesn't capture - such as "ABCABC..." or "ABCDEABCDE...", then it seems like the search will essentially fall back to octet-at-a-time. In particular, this seems like users operating in a three-octets-per-char alphabet get a raw deal.
    2. For users operating in a multi-octet alphabet, the start-octet of the trie might well match the start of every single character in that alphabet. For UTF8 patterns, would it be better the "start"-search to look for either (i) what looks like the final octet of the start-character, or (ii) the final octet that currently the BMH check looks for. Especially for longer automatons, should the UTF-8 case perform 2-3 more BHM probes to be more confident that the first/last characters really are a match?

    richardleach richardleach commented on Oct 17, 2026 21:56 UTC
    Contributor

    Oh, I see that the interplay between BMH and start-octet search isn't quite what I'd originally pictured for UTF-8, so it's not as bad as all that.

    demerphq demerphq commented on Oct 18, 2026 17:51 UTC
    Author

    @richardleach, following up on your last comment.

    So, a bit of context for those not familiar with it. Boyer–Moore–Horspool matching is a variant of Boyer–Moore matching. The usual description searches for one string. We use a version adapted to finding positions where one of a set of strings might match.

    It is easiest to picture with words of the same length. Suppose we have a bunch of six-octet words. BMH looks at the octet where a word would end, and uses a table to decide how far to advance. An entry of zero says “a word might end here, check further”. An entry of one says “advance one octet and check again”. An octet which appears nowhere in our words can have an entry of six, allowing us to skip six octets.

    With varying word lengths, we use a common prefix length determined by the shortest word, subject to the table’s size limit. So the anchor is not necessarily the last octet of a longer word. We build separate BMH tables for native and UTF-8 targets.

    We combine this with a check of the possible first octet. If the end-position check looks promising but the first octet cannot start any word, we can reject that position without entering Aho–Corasick proper.

    The repeat scanner handles another part of this process. After checking a machine-word-sized window and finding no possible starts, we know that identical following windows cannot contain a start either. We can then chew through repeated data a machine word at a time. This is useful for long runs of spaces, where repeatedly consulting the BMH table can cost more than comparing and skipping a whole word.

    Your point about odd-sized repeats led to another improvement. The scanner now handles periods of 3, 5, 6 and 7 octets as well. The trick is to compare enough machine words that the repeating sequence returns to the same position at each block boundary. On a 64-bit build, a three-octet repeat lines up again after three machine words, or 24 octets. This is particularly useful for Unicode whitespace, since many Unicode spaces occupy three UTF-8 octets.

    These shortcuts apply when AC is at its root, with no partial word in progress. Once matching has started, AC transitions and failure links keep track of the possible words. When it returns to the root, the scanning shortcuts become available again.

    I also tested restricting repeat detection according to the BMH shift, and adding a cheap probe before doing more repeat checks. Both helped some inputs and hurt others, so neither was retained as a general rule. The right choice depends on both the search words and the input. I do not think we have a useful universal cutoff yet.

    Anyway, here are some numbers from the latest version. Times are arithmetic means in microseconds per benchmark iteration, from twelve interleaved samples with matching compiler settings. Negative percentages mean less time. These compare the complete builds, rather than isolating any one optimisation.

    | Workload | 5.44 µs | blead µs | Latest µs | Change vs 5.44 | Change vs blead |
    |---|---:|---:|---:|---:|---:|
    | Native ASCII, period 1 | 26.25 | 139.45 | 3.51 | −86.6% | −97.5% |
    | Native ASCII, period 2 | 21.18 | 118.12 | 2.83 | −86.6% | −97.6% |
    | Native ASCII, period 3 | 20.91 | 114.83 | 3.81 | −81.8% | −96.7% |
    | Native ASCII, period 4 | 20.91 | 112.70 | 2.87 | −86.3% | −97.5% |
    | Native ASCII, period 5 | 21.11 | 117.03 | 3.00 | −85.8% | −97.4% |
    | Native ASCII, period 6 | 21.06 | 117.89 | 3.88 | −81.6% | −96.7% |
    | Native ASCII, period 7 | 22.02 | 121.35 | 3.07 | −86.0% | −97.5% |
    | Native ASCII, period 8 | 21.25 | 115.82 | 2.76 | −87.0% | −97.6% |
    | UTF-8, different first octet | 53.75 | 198.01 | 24.27 | −54.8% | −87.7% |
    | UTF-8, shared first octet | 154.39 | 150.13 | 32.47 | −79.0% | −78.4% |
    | UTF-8, shared first and last octets | 160.67 | 150.36 | 130.13 | −19.0% | −13.5% |
    | Unicode whitespace, period 3 | 27.19 | 98.47 | 2.61 | −90.4% | −97.3% |
    | Unicode whitespace, period 5 | 32.10 | 100.84 | 2.16 | −93.3% | −97.9% |
    | Unicode whitespace, period 6 | 26.52 | 101.99 | 2.59 | −90.2% | −97.5% |
    | Unicode whitespace, period 7 | 34.12 | 99.78 | 1.95 | −94.3% | −98.0% |
    | HTML, absent attribute names | 115.93 | 230.87 | 63.81 | −45.0% | −72.4% |
    | Variable search in Perl source | 185.94 | 280.20 | 220.86 | +18.8% | −21.2% |
    | Variable search in heavily indented Perl | 38.33 | 117.84 | 51.39 | +34.1% | −56.4% |
    | Anchored native Latin-1, long words | 1.15 | 1.52 | 1.41 | +22.7% | −7.0% |
    | Anchored UTF-8 Latin-1, long words | 1.32 | 1.69 | 1.55 | +17.2% | −8.5% |
    | Dense matches: 4,096 copies of cat | 5,427.46 | 5,717.69 | 6,124.62 | +12.8% | +7.1% |

    The repeated-input cases have about 32 KiB before a final match. The whitespace cases use actual Unicode spaces. The document cases scan 32,768 characters. Each anchored iteration tries three strings: two successful matches and one failure. The dense case returns 4,096 matches and includes counting them and accumulating their lengths. Input preparation and initial pattern construction are outside the timer.

    So, for example, scanning three-octet Unicode whitespace fell from 98.47 µs on blead to 2.61 µs here.

    There are also metrics which have degraded since 5.44. The source-search and anchored Latin-1 cases above all improve with this patch sequence relative to blead, although they have not recovered all the lost ground. I have plans to address the remaining representation costs in a follow-up. Dense matching is a separate remaining case where the new code is still slower.

    I have worked through the implementation feedback too: removed redundant bounds checks, reduced position tracking, and avoided conversions where the input is already in the representation the trie needs. Some apparently obvious changes consistently lost in measurement, so I left them out. Code layout also proved sensitive: changing how the loop was expressed changed the generated branches enough to matter.

    Construction costs are separate. Building the folded start maps adds a few microseconds to the small compilation cases we measured. That is paid when constructing the regex, while the scanning improvements apply each time it runs.

    I think we are now in good territory. Next PR I want to try a hypothetical TRIE V2, with completely separate native and UTF-8 tables and structs, so that we can remove more of the representation-handling work from execution. Tries starting using codepoints, switched to utf8, and now I think they need to do latin-1 codepoints and utf8 octets. Sigh. Suggestions for further improvements are very welcome.

    demerphq demerphq commented on code on Oct 18, 2026 18:44 UTC
    Code Review
    regexec.c:1
    @@ -3385,12 +3446,41 @@ S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
                 /* what trie are we using right now */
                 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ TRIE_DATA_SLOT(c) ];
                 reg_trie_data *trie = (reg_trie_data*)progi->data->data[aho->trie];
    +            const U8 * const prefilter = aho->prefilter;
    +            const U8 *start_map = prefilter
    +                ? prefilter + REG_AC_PREFILTER_MAP_OFFSET : NULL;
    +            const U8 *bmh_shift = prefilter
    +                ? prefilter + (utf8_target
    +                    ? REG_AC_PREFILTER_UTF8_BMH_OFFSET
    +                    : REG_AC_PREFILTER_LATIN1_BMH_OFFSET) : NULL;
    +            const U8 bmh_minlen = utf8_target ? aho->utf8_minlen
    +                                               : aho->latin1_minlen;
    +            const U8 start_mask = utf8_target ? REG_AC_PREFILTER_UTF8_MASK
    +                                               : REG_AC_PREFILTER_LATIN1_MASK;
    +            const bool has_bmh = prefilter && bmh_minlen;
    +
    +            /* Every literal path requires a codepoint above Latin-1, so
    +             * an unflagged target cannot match this start-of-program trie. */
    +            if (!utf8_target && FLAGS(c) == EXACT
    +                && trie->startstate == 1
    +                && !trie->states[1].wordnum
    +                && !trie->prefixlen_octets && !trie->prefixlen_chars
    +                && (trie->prop_flags & TRIE_CP_NO_LATIN1_WORDS))

    1. We now check NO_LATIN1_WORDS before the defensive trie-shape checks. We kept that change.

    2. I also tried caching the invariant rejection condition and delaying the UTF-8 boundary calculation. Those versions helped some cases but slowed down Latin-1 and folded scans, so I dropped them.

    demerphq demerphq commented on code on Oct 18, 2026 18:44 UTC
    Code Review
    regexec.c:1
    @@ -3463,14 +3551,75 @@ S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
                     while (state && (foldlen || octets_remaining
                                      || uc < (U8*)strend)) {
                         bool failed = false;
    +                    bool transitioned_from_root = false;
                         U32 word = aho->states[ state ].wordnum;
    +                    U8 *point;
    +                    bool point_may_be_start;
     
                         if( state == 1 ) {
                             if (uc >(U8*)last_start) break;
    +
    +                        /* A prefilter may skip only from the AC root.  Once
    +                         * AC has consumed a prefix, its failure state must
    +                         * retain that partial-match information. */
    +                        if (prefilter && !foldlen && !octets_remaining) {
    +                            /* BMH positions its anchor by encoded octet
    +                             * length.  Folded tries have no BMH table and
    +                             * use only the map of original target starts.
    +                             * Both require character boundaries in UTF-8. */
    +                            while (uc < (U8*)strend && uc <= (U8*)last_start) {
    +                                U8 distance = 0;
    +
    +                                if (utf8_target && UTF8_IS_CONTINUATION(*uc)) {
    +                                    uc++;
    +                                    pointpos = 0;
    +                                    continue;
    +                                }
    +                                if (has_bmh) {
    +                                    if ((STRLEN)((U8*)strend - uc) < bmh_minlen)
    +                                        break;
    +                                    distance = bmh_shift[uc[bmh_minlen - 1]];
    +                                }
    +
    +                                /* A start-map miss proves that no literal
    +                                 * starts here, regardless of the BMH shift.
    +                                 * The helper checks each later start
    +                                 * until it has a full rejected word.  Equal
    +                                 * following words repeat those rejected
    +                                 * octets, so they cannot contain a start.
    +                                 * UTF-8 continuation octets cannot be starts
    +                                 * either.  The checked window therefore lets
    +                                 * us skip equal windows without consulting
    +                                 * their BMH anchors. */
    +                                if (!(start_map[*uc] & start_mask))
    +                                {
    +                                    /* The helper consumes at least the
    +                                     * rejected octet at uc. */
    +                                    uc = (U8 *)S_scan_repeated_uv_blocks(
    +                                        uc, (U8*)strend,
    +                                        MIN((U8*)last_start, (U8*)strend - 1),
    +                                        start_map, start_mask, utf8_target);
    +                                    pointpos = 0;
    +                                    continue;
    +                                }
    +                                if (!distance)
    +                                    break;
    +                                uc += distance;
    +                                pointpos = 0;
    +                            }
    +                            if (uc >= (U8*)strend || uc > (U8*)last_start)
    +                                break;
    +                        }
                         }
     
    +                    /* The prefilter may have moved uc to a later candidate.
    +                     * Record that position if the root transition succeeds. */
    +                    point = uc;
    +                    point_may_be_start = !octets_remaining
    +                        && (!utf8_target || !UTF8_IS_CONTINUATION(*uc));

    Yes, good point. We removed the position ring entirely for case-sensitive matching, for both native and UTF-8 strings. We can subtract the matched word's input length instead. The UTF-8 case uses a byte length saved when we build the trie.

    Folding still needs the ring because one input character can produce several folded characters. We now record character starts only, skip failed root transitions, and reset the cursor when a new candidate starts. The cursor also wraps with a comparison instead of modulo.

    khwilliamson khwilliamson commented on code on Oct 19, 2026 18:28 UTC
    Code Review
    t/re/pat.t:1
    @@ -88,6 +88,20 @@ sub run_tests {
                 [ 'empty alternative',      "\x{100}x|",         'abc' ],
                 [ 'wide-only alternatives', "\x{100}x|\x{200}y", 'plain' ],
                 [ 'mixed alternatives',     "\x{100}x|cat",      'catcat' ],
    +            [ 'UTF-8 failure suffix', "\x{100}ab|b\x{1f600}",
    +                "\x{100}ab\x{100}acb\x{1f600}" ],
    +            [ 'UTF-8 unequal byte lengths', "\x{e9}x|\x{100}x|\x{1f600}x",

    Never hardcode e9 or anything else below 0x100 unless you use one that is explicitly mentioned in perlhacktips.pod under "Assuming the character set is ASCIIish" which gives a pair usable in folding tests; or you can wrap strings in a sub from t/charset_tools.pl

    khwilliamson khwilliamson commented on code on Oct 19, 2026 19:44 UTC
    Code Review
    regcomp_trie.c:1
    @@ -1772,6 +1772,69 @@ S_ac_path_as_latin1(const U8 *path, const U32 path_len, const U32 source_chars,
         return TRUE;
     }
     
    +/* The map describes original target octets, rather than trie transitions.
    + * A wide codepoint has only a UTF-8 entry.  Native Latin-1 codepoints have
    + * an entry for each target encoding. */
    +static void
    +S_ac_map_start_codepoint(pTHX_ U8 *map, const UV cp)
    +{
    +    U8 encoded[UTF8_MAXBYTES + 1];
    +
    +    if (cp <= 255)
    +        map[(U8)cp] |= REG_AC_PREFILTER_LATIN1_MASK;
    +    uvchr_to_utf8(encoded, cp);
    +    map[encoded[0]] |= REG_AC_PREFILTER_UTF8_MASK;
    +}
    +
    +/* Folded trie paths are UTF-8 encoded.  Visit only the first codepoint of
    + * each path, not every accepting word sharing that initial codepoint. */
    +static void
    +S_ac_map_folded_starts(pTHX_ const reg_trie_data *trie, const U32 state,
    +                       U8 *path, const U32 path_len, U8 *map,
    +                       SV **first_folds)
    +{
    +    const U32 base = trie->states[state].trans.base;
    +
    +    for (U32 ch = trie->states[state].min_octet;
    +         base && ch <= trie->states[state].max_octet; ch++)
    +    {
    +        const U32 next = S_trie_trans_state(trie, state, base, ch, 0);
    +
    +        if (!next)
    +            continue;
    +
    +        assert(path_len < UTF8_MAXBYTES);
    +        path[path_len] = (U8)ch;
    +        if (path_len + 1 == UTF8SKIP(path)) {
    +            U8 folded[UTF8_MAXBYTES_CASE + 1];
    +            STRLEN folded_len;
    +            U32 first;
    +            const U32 *remaining;
    +            const UV cp = valid_utf8_to_uv(path, NULL);
    +            const UV initial = to_uni_fold(cp, folded, &folded_len);
    +            const Size_t count = inverse_folds_(initial, &first, &remaining);
    +
    +            /* Unicode closure is a safe superset for /d and /aa.  Extra
    +             * candidates reach AC, which applies the actual folding rules.
    +             * Keep the literal itself and native /d's paired character too. */

    You must have just revised this comment, as it makes more sense to me now. I've looked at it several times, and it didn't make sense.

    I wonder, but do not claim to know, if it would make sense to exclude the /aa matches here, as it could be safely done here. I haven't looked at where the exclusion happens, though I've started to several times.

    khwilliamson khwilliamson commented on code on Oct 20, 2026 03:53 UTC
    Code Review
    t/re/pat.t:1
    @@ -28,14 +28,326 @@ skip_all_without_unicode_tables();
     my $has_locales = locales_enabled('LC_CTYPE');
     my $utf8_locale = find_utf8_ctype_locale();
     
    -plan tests => 1315;  # Update this when adding/deleting tests.
    +plan tests => 1588;  # Update this when adding/deleting tests.
     
     run_tests() unless caller;
     
     #
     # Tests start here.
     #
     sub run_tests {
    +    {
    +        my $haystack = ("A" x 5000) . "cat";
    +        ok($haystack =~ /walrus|cat/, 'AC finds a literal after a long rejected run');
    +
    +        $haystack = ("A" x 5000) . "dog";
    +        ok($haystack !~ /walrus|cat/, 'AC rejects a long run with no literal');
    +
    +        my $zero_shift_match = "cacc" . ("c" x 5000);
    +        ok($zero_shift_match =~ /acc|zdd/ && $-[0] == 1,
    +           'AC zero-shift rejection does not skip a later match');
    +
    +        my $zero_shift_run = ("c" x 5000) . "acc";
    +        ok($zero_shift_run =~ /acc|zdd/ && $-[0] == 5000,
    +           'AC zero-shift map rejection skips a repeated octet run');
    +
    +        utf8::upgrade($zero_shift_run);
    +        ok($zero_shift_run =~ /acc|zdd/ && $-[0] == 5000,
    +           'AC zero-shift map rejection skips an ASCII run in UTF-8');
    +
    +        $zero_shift_run = "c" x 5000;
    +        ok($zero_shift_run !~ /acc|zdd/,
    +           'AC zero-shift map rejection handles a run ending at string end');
    +
    +        my $shift_one_run = ("e" x 5000) . "fghijY";
    +        ok($shift_one_run =~ /abcdeX|fghijY/ && $-[0] == 5000,
    +           'AC repeated-sequence scan handles rejected starts with shift one');
    +
    +        utf8::upgrade($shift_one_run);
    +        ok($shift_one_run =~ /abcdeX|fghijY/ && $-[0] == 5000,
    +           'AC shift-one repeated-sequence scan handles UTF-8 targets');
    +
    +        $shift_one_run = "e" x 5000;
    +        ok($shift_one_run !~ /abcdeX|fghijY/,
    +           'AC shift-one repeated-sequence scan rejects a long non-match');
    +
    +        my $alternating_run = ("AB" x 5001) . "barB";
    +        ok($alternating_run =~ /fooA|barB/ && $-[0] == 10002,
    +           'AC skips repeated UV blocks with rejected alternating starts');
    +
    +        for my $offset (0 .. 7) {
    +            my $aligned_run = ("X" x $offset) . ("AB" x 5000) . "barB";
    +            ok($aligned_run =~ /fooA|barB/ && $-[0] == $offset + 10000,
    +               "AC repeated-block scan finds the match at offset $offset");
    +        }
    +
    +        utf8::upgrade($alternating_run);
    +        ok($alternating_run =~ /fooA|barB/ && $-[0] == 10002,
    +           'AC skips repeated UV blocks in a UTF-8 target');
    +
    +        for my $offset (0 .. 7) {
    +            my $aligned_run = ("X" x $offset) . ("AB" x 5000) . "barB";
    +            utf8::upgrade($aligned_run);
    +            ok($aligned_run =~ /fooA|barB/ && $-[0] == $offset + 10000,
    +               "AC UTF-8 repeated-block scan finds offset $offset");
    +        }
    +
    +        my $wide_alternating_run = ("\x{100}" x 5001) . "ba\x{200}";
    +        ok($wide_alternating_run =~ /fo\x{100}|ba\x{200}/
    +           && $-[0] == 5001,
    +           'AC skips repeated UTF-8 character blocks at character boundaries');
    +
    +        $wide_alternating_run = "\x{100}" x 5001;
    +        ok($wide_alternating_run !~ /fo\x{100}|ba\x{200}/,
    +           'AC rejects repeated UTF-8 character blocks without a match');
    +
    +        $haystack = ("A" x 5000) . "cat";
    +        ok($haystack =~ /(?:|walrus|cat)/ && $-[0] == 0 && $+[0] == 0,
    +           'AC with an empty alternative keeps the earliest empty match');
    +
    +        my $six_octet_haystack = ("A" x 5000) . "catcat";
    +        ok($six_octet_haystack =~ /walruswalrus|catcat/,
    +           'AC combined prefilter handles six-octet literals');
    +
    +        $six_octet_haystack = ("A" x 5000) . "dogdog";
    +        ok($six_octet_haystack !~ /walruswalrus|catcat/,
    +           'AC combined prefilter rejects a six-octet near miss');
    +
    +        my $seven_octet_haystack = ("A" x 5000) . "catcatx";
    +        ok($seven_octet_haystack =~ /walrusx|catcatx/,
    +           'AC combined prefilter handles seven-octet literals');
    +
    +        $seven_octet_haystack = ("x" x 5000);
    +        ok($seven_octet_haystack !~ /walrusx|catcatx/,
    +           'AC BMH prefilter handles frequent anchor-octet candidates');
    +
    +        my $long_haystack = ("A" x 5000) . "catcatcatcat";
    +        ok($long_haystack =~ /walruswalruswalruswalrus|catcatcatcat/,
    +           'AC BMH prefilter finds a long literal after rejected input');
    +
    +        $long_haystack = ("A" x 5000) . "dogdogdogdog";
    +        ok($long_haystack !~ /walruswalruswalruswalrus|catcatcatcat/,
    +           'AC BMH prefilter rejects a long run with no literal');
    +
    +        my $very_long_a = "walrus" x 50;
    +        my $very_long_b = "cat" x 100;
    +        my $very_long_re = qr/\Q$very_long_a\E|\Q$very_long_b\E/;
    +        my $very_long_haystack = ("A" x 5000) . $very_long_b;
    +        ok($very_long_haystack =~ $very_long_re,
    +           'AC BMH prefilter finds a 300-octet literal with capped shifts');
    +
    +        $very_long_haystack = ("A" x 5000) . ("dog" x 100);
    +        ok($very_long_haystack !~ $very_long_re,
    +           'AC BMH prefilter rejects a 300-octet near miss');
    +
    +        my @many_literals = map {
    +            chr(ord('a') + $_ % 26) . sprintf('%06d', $_)
    +        } 0 .. 255;
    +        my $many_pattern = join '|', map { quotemeta($_) } @many_literals;
    +        my $many_re = qr/(?:$many_pattern)/;
    +        my $many_haystack = ("Z" x 5000) . $many_literals[-1];
    +        ok($many_haystack =~ $many_re && $-[0] == 5000,
    +           'AC high-alternative-count prefilter finds a late match');
    +
    +        $many_haystack = "Z" x 5000;
    +        ok($many_haystack !~ $many_re,
    +           'AC high-alternative-count prefilter rejects a non-match');
    +
    +        my $overlap_haystack = ("A" x 5000) . "abcdefghijk";
    +        ok($overlap_haystack =~ /abcdefghij|defghijk/ && $-[0] == 5000
    +           && $+[0] == 5010,
    +           'AC BMH preserves the leftmost overlapping match');
    +
    +        my $utf8_ascii_haystack = ("A" x 5000) . "cat";
    +        utf8::upgrade($utf8_ascii_haystack);
    +        ok($utf8_ascii_haystack =~ /walrus|cat/ && $-[0] == 5000,
    +           'AC start-octet table works for UTF-8 invariant literals');
    +
    +        my $latin1_ascii_haystack = ("A" x 5000) . "cat";
    +        utf8::downgrade($latin1_ascii_haystack, 1);
    +        ok($latin1_ascii_haystack =~ /walrus|cat/ && $-[0] == 5000,
    +           'AC start-octet table works for Latin-1 invariant literals');
    +
    +        my $wide_only_re = qr/\x{400}foo|\x{800}bar/;
    +        my $latin1_wide_haystack = "A" x 5000;
    +        ok($latin1_wide_haystack !~ $wide_only_re,
    +           'AC with only wide literals rejects a Latin-1 target');
    +
    +        my $utf8_wide_haystack = ("A" x 5000) . "\x{800}bar";
    +        utf8::upgrade($utf8_wide_haystack);
    +        ok($utf8_wide_haystack =~ $wide_only_re && $-[0] == 5000,
    +           'AC with only wide literals still matches a UTF-8 target');
    +
    +        my $mixed_wide_re = qr/\x{400}foo|cat/;
    +        $latin1_wide_haystack .= "cat";
    +        ok($latin1_wide_haystack =~ $mixed_wide_re && $-[0] == 5000,
    +           'AC wide-literal shortcut preserves Latin-1 alternatives');
    +
    +        ok("abc" =~ /(?:|\x{400}foo)/ && $-[0] == 0 && $+[0] == 0,
    +           'AC wide-literal shortcut preserves an empty alternative');
    +
    +        my $trie_wide_re = qr/common\x{400}foo|common\x{800}bar/;
    +        my $latin1_trie_haystack = ("X" x 5000) . "common";
    +        ok($latin1_trie_haystack !~ $trie_wide_re,
    +           'Trie with only wide suffixes rejects a Latin-1 target');
    +
    +        my $utf8_trie_haystack = ("X" x 5000) . "common\x{800}bar";
    +        utf8::upgrade($utf8_trie_haystack);
    +        ok($utf8_trie_haystack =~ $trie_wide_re && $-[0] == 5000,
    +           'Trie with only wide suffixes still matches a UTF-8 target');
    +        my $mixed_trie_re = qr/common\x{400}foo|commoncat/;
    +        $latin1_trie_haystack .= "cat";
    +        ok($latin1_trie_haystack =~ $mixed_trie_re && $-[0] == 5000,
    +           'Trie wide-literal shortcut preserves Latin-1 alternatives');
    +
    +        my $utf8_haystack = ("\x{e9}" x 5000) . "\x{e9}cat";

    As explained in other comments. Don't use e9. This is 'Z' in EBCDIC, which I don't think is what you want.

    khwilliamson khwilliamson commented on code on Oct 20, 2026 03:56 UTC
    Code Review
    t/re/pat.t:1
    @@ -28,14 +28,326 @@ skip_all_without_unicode_tables();
     my $has_locales = locales_enabled('LC_CTYPE');
     my $utf8_locale = find_utf8_ctype_locale();
     
    -plan tests => 1315;  # Update this when adding/deleting tests.
    +plan tests => 1588;  # Update this when adding/deleting tests.
     
     run_tests() unless caller;
     
     #
     # Tests start here.
     #
     sub run_tests {
    +    {
    +        my $haystack = ("A" x 5000) . "cat";
    +        ok($haystack =~ /walrus|cat/, 'AC finds a literal after a long rejected run');
    +
    +        $haystack = ("A" x 5000) . "dog";
    +        ok($haystack !~ /walrus|cat/, 'AC rejects a long run with no literal');
    +
    +        my $zero_shift_match = "cacc" . ("c" x 5000);
    +        ok($zero_shift_match =~ /acc|zdd/ && $-[0] == 1,
    +           'AC zero-shift rejection does not skip a later match');
    +
    +        my $zero_shift_run = ("c" x 5000) . "acc";
    +        ok($zero_shift_run =~ /acc|zdd/ && $-[0] == 5000,
    +           'AC zero-shift map rejection skips a repeated octet run');
    +
    +        utf8::upgrade($zero_shift_run);
    +        ok($zero_shift_run =~ /acc|zdd/ && $-[0] == 5000,
    +           'AC zero-shift map rejection skips an ASCII run in UTF-8');
    +
    +        $zero_shift_run = "c" x 5000;
    +        ok($zero_shift_run !~ /acc|zdd/,
    +           'AC zero-shift map rejection handles a run ending at string end');
    +
    +        my $shift_one_run = ("e" x 5000) . "fghijY";
    +        ok($shift_one_run =~ /abcdeX|fghijY/ && $-[0] == 5000,
    +           'AC repeated-sequence scan handles rejected starts with shift one');
    +
    +        utf8::upgrade($shift_one_run);
    +        ok($shift_one_run =~ /abcdeX|fghijY/ && $-[0] == 5000,
    +           'AC shift-one repeated-sequence scan handles UTF-8 targets');
    +
    +        $shift_one_run = "e" x 5000;
    +        ok($shift_one_run !~ /abcdeX|fghijY/,
    +           'AC shift-one repeated-sequence scan rejects a long non-match');
    +
    +        my $alternating_run = ("AB" x 5001) . "barB";
    +        ok($alternating_run =~ /fooA|barB/ && $-[0] == 10002,
    +           'AC skips repeated UV blocks with rejected alternating starts');
    +
    +        for my $offset (0 .. 7) {
    +            my $aligned_run = ("X" x $offset) . ("AB" x 5000) . "barB";
    +            ok($aligned_run =~ /fooA|barB/ && $-[0] == $offset + 10000,
    +               "AC repeated-block scan finds the match at offset $offset");
    +        }
    +
    +        utf8::upgrade($alternating_run);
    +        ok($alternating_run =~ /fooA|barB/ && $-[0] == 10002,
    +           'AC skips repeated UV blocks in a UTF-8 target');
    +
    +        for my $offset (0 .. 7) {
    +            my $aligned_run = ("X" x $offset) . ("AB" x 5000) . "barB";
    +            utf8::upgrade($aligned_run);
    +            ok($aligned_run =~ /fooA|barB/ && $-[0] == $offset + 10000,
    +               "AC UTF-8 repeated-block scan finds offset $offset");
    +        }
    +
    +        my $wide_alternating_run = ("\x{100}" x 5001) . "ba\x{200}";
    +        ok($wide_alternating_run =~ /fo\x{100}|ba\x{200}/
    +           && $-[0] == 5001,
    +           'AC skips repeated UTF-8 character blocks at character boundaries');
    +
    +        $wide_alternating_run = "\x{100}" x 5001;
    +        ok($wide_alternating_run !~ /fo\x{100}|ba\x{200}/,
    +           'AC rejects repeated UTF-8 character blocks without a match');
    +
    +        $haystack = ("A" x 5000) . "cat";
    +        ok($haystack =~ /(?:|walrus|cat)/ && $-[0] == 0 && $+[0] == 0,
    +           'AC with an empty alternative keeps the earliest empty match');
    +
    +        my $six_octet_haystack = ("A" x 5000) . "catcat";
    +        ok($six_octet_haystack =~ /walruswalrus|catcat/,
    +           'AC combined prefilter handles six-octet literals');
    +
    +        $six_octet_haystack = ("A" x 5000) . "dogdog";
    +        ok($six_octet_haystack !~ /walruswalrus|catcat/,
    +           'AC combined prefilter rejects a six-octet near miss');
    +
    +        my $seven_octet_haystack = ("A" x 5000) . "catcatx";
    +        ok($seven_octet_haystack =~ /walrusx|catcatx/,
    +           'AC combined prefilter handles seven-octet literals');
    +
    +        $seven_octet_haystack = ("x" x 5000);
    +        ok($seven_octet_haystack !~ /walrusx|catcatx/,
    +           'AC BMH prefilter handles frequent anchor-octet candidates');
    +
    +        my $long_haystack = ("A" x 5000) . "catcatcatcat";
    +        ok($long_haystack =~ /walruswalruswalruswalrus|catcatcatcat/,
    +           'AC BMH prefilter finds a long literal after rejected input');
    +
    +        $long_haystack = ("A" x 5000) . "dogdogdogdog";
    +        ok($long_haystack !~ /walruswalruswalruswalrus|catcatcatcat/,
    +           'AC BMH prefilter rejects a long run with no literal');
    +
    +        my $very_long_a = "walrus" x 50;
    +        my $very_long_b = "cat" x 100;
    +        my $very_long_re = qr/\Q$very_long_a\E|\Q$very_long_b\E/;
    +        my $very_long_haystack = ("A" x 5000) . $very_long_b;
    +        ok($very_long_haystack =~ $very_long_re,
    +           'AC BMH prefilter finds a 300-octet literal with capped shifts');
    +
    +        $very_long_haystack = ("A" x 5000) . ("dog" x 100);
    +        ok($very_long_haystack !~ $very_long_re,
    +           'AC BMH prefilter rejects a 300-octet near miss');
    +
    +        my @many_literals = map {
    +            chr(ord('a') + $_ % 26) . sprintf('%06d', $_)
    +        } 0 .. 255;
    +        my $many_pattern = join '|', map { quotemeta($_) } @many_literals;
    +        my $many_re = qr/(?:$many_pattern)/;
    +        my $many_haystack = ("Z" x 5000) . $many_literals[-1];
    +        ok($many_haystack =~ $many_re && $-[0] == 5000,
    +           'AC high-alternative-count prefilter finds a late match');
    +
    +        $many_haystack = "Z" x 5000;
    +        ok($many_haystack !~ $many_re,
    +           'AC high-alternative-count prefilter rejects a non-match');
    +
    +        my $overlap_haystack = ("A" x 5000) . "abcdefghijk";
    +        ok($overlap_haystack =~ /abcdefghij|defghijk/ && $-[0] == 5000
    +           && $+[0] == 5010,
    +           'AC BMH preserves the leftmost overlapping match');
    +
    +        my $utf8_ascii_haystack = ("A" x 5000) . "cat";
    +        utf8::upgrade($utf8_ascii_haystack);
    +        ok($utf8_ascii_haystack =~ /walrus|cat/ && $-[0] == 5000,
    +           'AC start-octet table works for UTF-8 invariant literals');
    +
    +        my $latin1_ascii_haystack = ("A" x 5000) . "cat";
    +        utf8::downgrade($latin1_ascii_haystack, 1);
    +        ok($latin1_ascii_haystack =~ /walrus|cat/ && $-[0] == 5000,
    +           'AC start-octet table works for Latin-1 invariant literals');
    +
    +        my $wide_only_re = qr/\x{400}foo|\x{800}bar/;
    +        my $latin1_wide_haystack = "A" x 5000;
    +        ok($latin1_wide_haystack !~ $wide_only_re,
    +           'AC with only wide literals rejects a Latin-1 target');
    +
    +        my $utf8_wide_haystack = ("A" x 5000) . "\x{800}bar";
    +        utf8::upgrade($utf8_wide_haystack);
    +        ok($utf8_wide_haystack =~ $wide_only_re && $-[0] == 5000,
    +           'AC with only wide literals still matches a UTF-8 target');
    +
    +        my $mixed_wide_re = qr/\x{400}foo|cat/;
    +        $latin1_wide_haystack .= "cat";
    +        ok($latin1_wide_haystack =~ $mixed_wide_re && $-[0] == 5000,
    +           'AC wide-literal shortcut preserves Latin-1 alternatives');
    +
    +        ok("abc" =~ /(?:|\x{400}foo)/ && $-[0] == 0 && $+[0] == 0,
    +           'AC wide-literal shortcut preserves an empty alternative');
    +
    +        my $trie_wide_re = qr/common\x{400}foo|common\x{800}bar/;
    +        my $latin1_trie_haystack = ("X" x 5000) . "common";
    +        ok($latin1_trie_haystack !~ $trie_wide_re,
    +           'Trie with only wide suffixes rejects a Latin-1 target');
    +
    +        my $utf8_trie_haystack = ("X" x 5000) . "common\x{800}bar";
    +        utf8::upgrade($utf8_trie_haystack);
    +        ok($utf8_trie_haystack =~ $trie_wide_re && $-[0] == 5000,
    +           'Trie with only wide suffixes still matches a UTF-8 target');
    +        my $mixed_trie_re = qr/common\x{400}foo|commoncat/;
    +        $latin1_trie_haystack .= "cat";
    +        ok($latin1_trie_haystack =~ $mixed_trie_re && $-[0] == 5000,
    +           'Trie wide-literal shortcut preserves Latin-1 alternatives');
    +
    +        my $utf8_haystack = ("\x{e9}" x 5000) . "\x{e9}cat";
    +        utf8::upgrade($utf8_haystack);
    +        ok($utf8_haystack =~ /\x{e9}cat|zebra/,
    +           'UTF-8 AC finds a multi-byte literal after rejected input');
    +
    +        my $latin1_haystack = ("\xE9" x 5000) . "\xE9cat";
    +        ok($latin1_haystack =~ /\x{e9}cat|zebra/,
    +           'Latin-1 AC preserves matching for an awkward code point');
    +
    +        for my $encoding ('Latin-1', 'UTF-8') {
    +            # The shortest word occupies two Latin-1 octets or three UTF-8
    +            # octets.  Check both alternatives with each target encoding.
    +            my $different_lengths_re = qr/\x{e9}a|zbc/;
    +
    +            for my $suffix ("\x{e9}a", 'zbc') {
    +                my $target = ('Q' x 17) . $suffix;
    +                utf8::upgrade($target) if $encoding eq 'UTF-8';
    +
    +                ok($target =~ $different_lengths_re && $-[0] == 17
    +                   && $+[0] == length($target),
    +                   "AC uses the effective literal length for $encoding");
    +            }
    +
    +            # Excluding the wide word gives a nine-octet Latin-1 minimum.
    +            # Including it gives a three-octet UTF-8 minimum.
    +            my $mixed_lengths_re = qr/\x{100}x|abcdefghi/;
    +            my $mixed_target = ('x' x 17) . 'abcdefghi';
    +            utf8::upgrade($mixed_target) if $encoding eq 'UTF-8';
    +
    +            ok($mixed_target =~ $mixed_lengths_re && $-[0] == 17,
    +               "AC mixed wide alternatives find a narrow word in $encoding");
    +
    +            $mixed_target = 'x' x 17;
    +            utf8::upgrade($mixed_target) if $encoding eq 'UTF-8';
    +
    +            ok($mixed_target !~ $mixed_lengths_re,
    +               "AC mixed wide alternatives reject a short miss in $encoding");
    +
    +            my $root_restart = ('a' x 17) . 'de';
    +            utf8::upgrade($root_restart) if $encoding eq 'UTF-8';
    +
    +            ok($root_restart =~ /abc|de/ && $-[0] == 17 && $+[0] == 19,
    +               "AC resets the point ring on repeated root transitions in $encoding");
    +
    +            my $fallback_target = 'abcdgu';
    +            utf8::upgrade($fallback_target) if $encoding eq 'UTF-8';
    +
    +            ok($fallback_target =~ /abcdefg|cdgu/
    +               && $-[0] == 2 && $+[0] == 6,
    +               "AC keeps the point ring across a suffix failure transition in $encoding");
    +
    +            my $retry_target = 'abcdX';
    +            utf8::upgrade($retry_target) if $encoding eq 'UTF-8';
    +
    +            ok($retry_target =~ /(?:abc|bcd)X/ && $-[0] == 1 && $+[0] == 5,
    +               "AC retries an overlapping start after full-match rejection in $encoding");
    +
    +            # Prefilters are disabled for folds, but the point-ring changes
    +            # apply there too.  One sharp s contributes two folded characters.
    +            for my $case (["\x{df}x", 0, 2],

    No hard-coding constants < 0x100 in tests

    khwilliamson khwilliamson commented on code on Oct 20, 2026 04:06 UTC
    Code Review
    regcomp_trie.c:1
    @@ -2035,6 +2098,44 @@ Perl_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *s
             Safefree(path_depths);
             Safefree(parents);
         }
    +    else if (TRIE_IS_FOLDED(trie)
    +             && FLAGS(source) != EXACTFLU8
    +             && trie->startstate == 1 && !trie->states[1].wordnum
    +             && !trie->prefixlen_octets && !trie->prefixlen_chars)
    +    {
    +        SV *first_folds = NULL;
    +        U8 path[UTF8_MAXBYTES + 1];
    +        U8 *start_map;
    +        UV start, end;
    +
    +        /* BMH offsets in folded data do not describe the original target.
    +         * Leave both anchor lengths zero and use only the start map.  Locale
    +         * folding is excluded because its rules can change at execution. */
    +        aho->prefilter = (U8 *)PerlMemShared_calloc(
    +            REG_AC_PREFILTER_SIZE, sizeof(U8));
    +        start_map = aho->prefilter + REG_AC_PREFILTER_MAP_OFFSET;
    +        S_ac_map_folded_starts(aTHX_ trie, 1, path, 0, start_map, &first_folds);
    +
    +        /* A single target codepoint can supply several folded characters.
    +         * Add every such codepoint whose fold begins with a possible first
    +         * folded character.  We need not compare the rest of its fold: false
    +         * positives are safe, including folds extending beyond a trie word
    +         * into its following regex nodes. */
    +        invlist_iterinit(PL_HasMultiCharFold);

    Here, and elsewhere there may be macros that could avoid work for you that I just added documentation of to perlintern is_FOLDS_TO_MULTI_utf8 returns 0 if the UTF-8 input sequence does not fold to more than one character; otherwise it returns the number of bytes the foldable character occupies.

    khwilliamson khwilliamson commented on code on Oct 20, 2026 04:16 UTC
    Code Review
    regcomp_trie.c:1
    @@ -2035,6 +2098,44 @@ Perl_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *s
             Safefree(path_depths);
             Safefree(parents);
         }
    +    else if (TRIE_IS_FOLDED(trie)
    +             && FLAGS(source) != EXACTFLU8
    +             && trie->startstate == 1 && !trie->states[1].wordnum
    +             && !trie->prefixlen_octets && !trie->prefixlen_chars)
    +    {
    +        SV *first_folds = NULL;
    +        U8 path[UTF8_MAXBYTES + 1];
    +        U8 *start_map;
    +        UV start, end;
    +
    +        /* BMH offsets in folded data do not describe the original target.
    +         * Leave both anchor lengths zero and use only the start map.  Locale
    +         * folding is excluded because its rules can change at execution. */
    +        aho->prefilter = (U8 *)PerlMemShared_calloc(
    +            REG_AC_PREFILTER_SIZE, sizeof(U8));
    +        start_map = aho->prefilter + REG_AC_PREFILTER_MAP_OFFSET;
    +        S_ac_map_folded_starts(aTHX_ trie, 1, path, 0, start_map, &first_folds);
    +
    +        /* A single target codepoint can supply several folded characters.
    +         * Add every such codepoint whose fold begins with a possible first
    +         * folded character.  We need not compare the rest of its fold: false
    +         * positives are safe, including folds extending beyond a trie word
    +         * into its following regex nodes. */
    +        invlist_iterinit(PL_HasMultiCharFold);
    +        while (invlist_iternext(PL_HasMultiCharFold, &start, &end)) {
    +            for (UV cp = start; cp <= end; cp++) {
    +                U8 folded[UTF8_MAXBYTES_CASE + 1];
    +                STRLEN folded_len;
    +                const UV native_cp = UNI_TO_NATIVE(cp);

    This is wrong. Like I said in an earlier review, you rarely have to worry about native vs Unicode in your code. Most operations are done in terms of native values. In this case, PL_HasMultiCharFold returns native values.

    You're often doing the exact opposite of what is required. A bunch of tests use specific code points that are Unicode specific, ignoring that these have to be native values; whereas the code assumes you have to deal with native vs Unicode; and you don't. That may have been the original design, but it isn't any longer, so there's hardly any mention of EBCDIC in the current code base. But the test files still have to deal with it.

    I think the rule to remember is that nearly everything is native. It's like Encode. It translates to/from the external character encoding. But the internal stuff is in the internal encoding, so you don't have to worry about it in your code. But you have to remember in tests to use that internal encoding

    khwilliamson khwilliamson commented on code on Oct 20, 2026 04:23 UTC
    Code Review
    regcomp_trie.c:1
    @@ -2035,6 +2098,44 @@ Perl_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *s
             Safefree(path_depths);
             Safefree(parents);
         }
    +    else if (TRIE_IS_FOLDED(trie)
    +             && FLAGS(source) != EXACTFLU8
    +             && trie->startstate == 1 && !trie->states[1].wordnum
    +             && !trie->prefixlen_octets && !trie->prefixlen_chars)
    +    {
    +        SV *first_folds = NULL;
    +        U8 path[UTF8_MAXBYTES + 1];
    +        U8 *start_map;
    +        UV start, end;
    +
    +        /* BMH offsets in folded data do not describe the original target.
    +         * Leave both anchor lengths zero and use only the start map.  Locale
    +         * folding is excluded because its rules can change at execution. */
    +        aho->prefilter = (U8 *)PerlMemShared_calloc(
    +            REG_AC_PREFILTER_SIZE, sizeof(U8));
    +        start_map = aho->prefilter + REG_AC_PREFILTER_MAP_OFFSET;
    +        S_ac_map_folded_starts(aTHX_ trie, 1, path, 0, start_map, &first_folds);
    +
    +        /* A single target codepoint can supply several folded characters.
    +         * Add every such codepoint whose fold begins with a possible first
    +         * folded character.  We need not compare the rest of its fold: false
    +         * positives are safe, including folds extending beyond a trie word
    +         * into its following regex nodes. */
    +        invlist_iterinit(PL_HasMultiCharFold);
    +        while (invlist_iternext(PL_HasMultiCharFold, &start, &end)) {
    +            for (UV cp = start; cp <= end; cp++) {
    +                U8 folded[UTF8_MAXBYTES_CASE + 1];
    +                STRLEN folded_len;
    +                const UV native_cp = UNI_TO_NATIVE(cp);
    +                const UV initial = to_uni_fold(native_cp, folded, &folded_len);

    Otherwise, the algorithm looks right to me

    demerphq demerphq commented on code on Oct 20, 2026 13:39 UTC
    Code Review
    regcomp_trie.c:1
    @@ -2035,6 +2098,44 @@ Perl_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *s
             Safefree(path_depths);
             Safefree(parents);
         }
    +    else if (TRIE_IS_FOLDED(trie)
    +             && FLAGS(source) != EXACTFLU8
    +             && trie->startstate == 1 && !trie->states[1].wordnum
    +             && !trie->prefixlen_octets && !trie->prefixlen_chars)
    +    {
    +        SV *first_folds = NULL;
    +        U8 path[UTF8_MAXBYTES + 1];
    +        U8 *start_map;
    +        UV start, end;
    +
    +        /* BMH offsets in folded data do not describe the original target.
    +         * Leave both anchor lengths zero and use only the start map.  Locale
    +         * folding is excluded because its rules can change at execution. */
    +        aho->prefilter = (U8 *)PerlMemShared_calloc(
    +            REG_AC_PREFILTER_SIZE, sizeof(U8));
    +        start_map = aho->prefilter + REG_AC_PREFILTER_MAP_OFFSET;
    +        S_ac_map_folded_starts(aTHX_ trie, 1, path, 0, start_map, &first_folds);
    +
    +        /* A single target codepoint can supply several folded characters.
    +         * Add every such codepoint whose fold begins with a possible first
    +         * folded character.  We need not compare the rest of its fold: false
    +         * positives are safe, including folds extending beyond a trie word
    +         * into its following regex nodes. */
    +        invlist_iterinit(PL_HasMultiCharFold);
    +        while (invlist_iternext(PL_HasMultiCharFold, &start, &end)) {
    +            for (UV cp = start; cp <= end; cp++) {
    +                U8 folded[UTF8_MAXBYTES_CASE + 1];
    +                STRLEN folded_len;
    +                const UV native_cp = UNI_TO_NATIVE(cp);

    Ok, sorry, yes i admit part of the lesson from before didnt sink in, but while I was following up on this I think I realized something that had been confusing me.

    In the docs we say "Unicode" in places where as far as I now understand it we really accept a sort of hybrid "native-Unicode" where it is native codepoints for 0-255 and true Unicode for over 255. Is that correct? I mean, if i check the tests for toUPPER_uvchr that clearly show it accepts (and returns) the hybrid native-Unicode not true Unicode.

    I wonder if the confusion related to this can be avoided by maybe using the term 'ncp' for 'native-(unicode)-codepoint' and use the term native-Unicode when we are talking about it in the docs. IMO this is one of the main reason I kept getting confused.

    We have the functions NATIVE_TO_UNI() and UNI_TO_NATIVE() but it isnt really clear when they are needed. From what you say it seems like almost never in the internals?

    I tried to rewrite some of the docs so others avoid my particular confusion. What do you think?

    demerphq demerphq commented on code on Oct 20, 2026 13:41 UTC
    Code Review
    regcomp_trie.c:1
    @@ -1720,6 +1732,84 @@ Perl_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
                  : MADE_TRIE;
     }
     
    +/* Convert one trie path to the octets seen in a Latin-1 target.  A path with
    + * one octet per source character contains only UTF-8 invariant characters,
    + * so its octets already have the target representation.  Longer paths are
    + * UTF-8 encodings and can be downgraded only when every character fits in
    + * Latin-1.  The caller excludes case-folded tries. */
    +static bool
    +S_ac_path_as_latin1(const U8 *path, const U32 path_len, const U32 source_chars,
    +                    U8 *latin1_path, U32 *latin1_len)
    +{
    +    if (path_len == source_chars) {
    +        Copy(path, latin1_path, path_len, U8);
    +        *latin1_len = path_len;
    +        return TRUE;
    +    }
    +
    +    if (path_len < source_chars)
    +        return FALSE;
    +
    +    {

    Yeah, sorry, that was left over from a refactor. Removed.

    demerphq demerphq commented on code on Oct 20, 2026 13:41 UTC
    Code Review
    t/re/pat.t:1
    @@ -88,6 +88,20 @@ sub run_tests {
                 [ 'empty alternative',      "\x{100}x|",         'abc' ],
                 [ 'wide-only alternatives', "\x{100}x|\x{200}y", 'plain' ],
                 [ 'mixed alternatives',     "\x{100}x|cat",      'catcat' ],
    +            [ 'UTF-8 failure suffix', "\x{100}ab|b\x{1f600}",
    +                "\x{100}ab\x{100}acb\x{1f600}" ],
    +            [ 'UTF-8 unequal byte lengths', "\x{e9}x|\x{100}x|\x{1f600}x",

    Right. Willdo in the future. Fixed.

    demerphq demerphq commented on code on Oct 20, 2026 13:54 UTC
    Code Review
    regcomp_trie.c:1
    @@ -1772,6 +1772,69 @@ S_ac_path_as_latin1(const U8 *path, const U32 path_len, const U32 source_chars,
         return TRUE;
     }
     
    +/* The map describes original target octets, rather than trie transitions.
    + * A wide codepoint has only a UTF-8 entry.  Native Latin-1 codepoints have
    + * an entry for each target encoding. */
    +static void
    +S_ac_map_start_codepoint(pTHX_ U8 *map, const UV cp)
    +{
    +    U8 encoded[UTF8_MAXBYTES + 1];
    +
    +    if (cp <= 255)
    +        map[(U8)cp] |= REG_AC_PREFILTER_LATIN1_MASK;
    +    uvchr_to_utf8(encoded, cp);
    +    map[encoded[0]] |= REG_AC_PREFILTER_UTF8_MASK;
    +}
    +
    +/* Folded trie paths are UTF-8 encoded.  Visit only the first codepoint of
    + * each path, not every accepting word sharing that initial codepoint. */
    +static void
    +S_ac_map_folded_starts(pTHX_ const reg_trie_data *trie, const U32 state,
    +                       U8 *path, const U32 path_len, U8 *map,
    +                       SV **first_folds)
    +{
    +    const U32 base = trie->states[state].trans.base;
    +
    +    for (U32 ch = trie->states[state].min_octet;
    +         base && ch <= trie->states[state].max_octet; ch++)
    +    {
    +        const U32 next = S_trie_trans_state(trie, state, base, ch, 0);
    +
    +        if (!next)
    +            continue;
    +
    +        assert(path_len < UTF8_MAXBYTES);
    +        path[path_len] = (U8)ch;
    +        if (path_len + 1 == UTF8SKIP(path)) {
    +            U8 folded[UTF8_MAXBYTES_CASE + 1];
    +            STRLEN folded_len;
    +            U32 first;
    +            const U32 *remaining;
    +            const UV cp = valid_utf8_to_uv(path, NULL);
    +            const UV initial = to_uni_fold(cp, folded, &folded_len);
    +            const Size_t count = inverse_folds_(initial, &first, &remaining);
    +
    +            /* Unicode closure is a safe superset for /d and /aa.  Extra
    +             * candidates reach AC, which applies the actual folding rules.
    +             * Keep the literal itself and native /d's paired character too. */

    >You must have just revised this comment,

    Yes, and I just revised it again.

    I wonder, but do not claim to know, if it would make sense to exclude the /aa matches here,

    I am not sure I follow so I havent done anything with this yet.

    demerphq demerphq commented on code on Oct 20, 2026 13:54 UTC
    Code Review
    t/re/pat.t:1
    @@ -28,14 +28,326 @@ skip_all_without_unicode_tables();
     my $has_locales = locales_enabled('LC_CTYPE');
     my $utf8_locale = find_utf8_ctype_locale();
     
    -plan tests => 1315;  # Update this when adding/deleting tests.
    +plan tests => 1588;  # Update this when adding/deleting tests.
     
     run_tests() unless caller;
     
     #
     # Tests start here.
     #
     sub run_tests {
    +    {
    +        my $haystack = ("A" x 5000) . "cat";
    +        ok($haystack =~ /walrus|cat/, 'AC finds a literal after a long rejected run');
    +
    +        $haystack = ("A" x 5000) . "dog";
    +        ok($haystack !~ /walrus|cat/, 'AC rejects a long run with no literal');
    +
    +        my $zero_shift_match = "cacc" . ("c" x 5000);
    +        ok($zero_shift_match =~ /acc|zdd/ && $-[0] == 1,
    +           'AC zero-shift rejection does not skip a later match');
    +
    +        my $zero_shift_run = ("c" x 5000) . "acc";
    +        ok($zero_shift_run =~ /acc|zdd/ && $-[0] == 5000,
    +           'AC zero-shift map rejection skips a repeated octet run');
    +
    +        utf8::upgrade($zero_shift_run);
    +        ok($zero_shift_run =~ /acc|zdd/ && $-[0] == 5000,
    +           'AC zero-shift map rejection skips an ASCII run in UTF-8');
    +
    +        $zero_shift_run = "c" x 5000;
    +        ok($zero_shift_run !~ /acc|zdd/,
    +           'AC zero-shift map rejection handles a run ending at string end');
    +
    +        my $shift_one_run = ("e" x 5000) . "fghijY";
    +        ok($shift_one_run =~ /abcdeX|fghijY/ && $-[0] == 5000,
    +           'AC repeated-sequence scan handles rejected starts with shift one');
    +
    +        utf8::upgrade($shift_one_run);
    +        ok($shift_one_run =~ /abcdeX|fghijY/ && $-[0] == 5000,
    +           'AC shift-one repeated-sequence scan handles UTF-8 targets');
    +
    +        $shift_one_run = "e" x 5000;
    +        ok($shift_one_run !~ /abcdeX|fghijY/,
    +           'AC shift-one repeated-sequence scan rejects a long non-match');
    +
    +        my $alternating_run = ("AB" x 5001) . "barB";
    +        ok($alternating_run =~ /fooA|barB/ && $-[0] == 10002,
    +           'AC skips repeated UV blocks with rejected alternating starts');
    +
    +        for my $offset (0 .. 7) {
    +            my $aligned_run = ("X" x $offset) . ("AB" x 5000) . "barB";
    +            ok($aligned_run =~ /fooA|barB/ && $-[0] == $offset + 10000,
    +               "AC repeated-block scan finds the match at offset $offset");
    +        }
    +
    +        utf8::upgrade($alternating_run);
    +        ok($alternating_run =~ /fooA|barB/ && $-[0] == 10002,
    +           'AC skips repeated UV blocks in a UTF-8 target');
    +
    +        for my $offset (0 .. 7) {
    +            my $aligned_run = ("X" x $offset) . ("AB" x 5000) . "barB";
    +            utf8::upgrade($aligned_run);
    +            ok($aligned_run =~ /fooA|barB/ && $-[0] == $offset + 10000,
    +               "AC UTF-8 repeated-block scan finds offset $offset");
    +        }
    +
    +        my $wide_alternating_run = ("\x{100}" x 5001) . "ba\x{200}";
    +        ok($wide_alternating_run =~ /fo\x{100}|ba\x{200}/
    +           && $-[0] == 5001,
    +           'AC skips repeated UTF-8 character blocks at character boundaries');
    +
    +        $wide_alternating_run = "\x{100}" x 5001;
    +        ok($wide_alternating_run !~ /fo\x{100}|ba\x{200}/,
    +           'AC rejects repeated UTF-8 character blocks without a match');
    +
    +        $haystack = ("A" x 5000) . "cat";
    +        ok($haystack =~ /(?:|walrus|cat)/ && $-[0] == 0 && $+[0] == 0,
    +           'AC with an empty alternative keeps the earliest empty match');
    +
    +        my $six_octet_haystack = ("A" x 5000) . "catcat";
    +        ok($six_octet_haystack =~ /walruswalrus|catcat/,
    +           'AC combined prefilter handles six-octet literals');
    +
    +        $six_octet_haystack = ("A" x 5000) . "dogdog";
    +        ok($six_octet_haystack !~ /walruswalrus|catcat/,
    +           'AC combined prefilter rejects a six-octet near miss');
    +
    +        my $seven_octet_haystack = ("A" x 5000) . "catcatx";
    +        ok($seven_octet_haystack =~ /walrusx|catcatx/,
    +           'AC combined prefilter handles seven-octet literals');
    +
    +        $seven_octet_haystack = ("x" x 5000);
    +        ok($seven_octet_haystack !~ /walrusx|catcatx/,
    +           'AC BMH prefilter handles frequent anchor-octet candidates');
    +
    +        my $long_haystack = ("A" x 5000) . "catcatcatcat";
    +        ok($long_haystack =~ /walruswalruswalruswalrus|catcatcatcat/,
    +           'AC BMH prefilter finds a long literal after rejected input');
    +
    +        $long_haystack = ("A" x 5000) . "dogdogdogdog";
    +        ok($long_haystack !~ /walruswalruswalruswalrus|catcatcatcat/,
    +           'AC BMH prefilter rejects a long run with no literal');
    +
    +        my $very_long_a = "walrus" x 50;
    +        my $very_long_b = "cat" x 100;
    +        my $very_long_re = qr/\Q$very_long_a\E|\Q$very_long_b\E/;
    +        my $very_long_haystack = ("A" x 5000) . $very_long_b;
    +        ok($very_long_haystack =~ $very_long_re,
    +           'AC BMH prefilter finds a 300-octet literal with capped shifts');
    +
    +        $very_long_haystack = ("A" x 5000) . ("dog" x 100);
    +        ok($very_long_haystack !~ $very_long_re,
    +           'AC BMH prefilter rejects a 300-octet near miss');
    +
    +        my @many_literals = map {
    +            chr(ord('a') + $_ % 26) . sprintf('%06d', $_)
    +        } 0 .. 255;
    +        my $many_pattern = join '|', map { quotemeta($_) } @many_literals;
    +        my $many_re = qr/(?:$many_pattern)/;
    +        my $many_haystack = ("Z" x 5000) . $many_literals[-1];
    +        ok($many_haystack =~ $many_re && $-[0] == 5000,
    +           'AC high-alternative-count prefilter finds a late match');
    +
    +        $many_haystack = "Z" x 5000;
    +        ok($many_haystack !~ $many_re,
    +           'AC high-alternative-count prefilter rejects a non-match');
    +
    +        my $overlap_haystack = ("A" x 5000) . "abcdefghijk";
    +        ok($overlap_haystack =~ /abcdefghij|defghijk/ && $-[0] == 5000
    +           && $+[0] == 5010,
    +           'AC BMH preserves the leftmost overlapping match');
    +
    +        my $utf8_ascii_haystack = ("A" x 5000) . "cat";
    +        utf8::upgrade($utf8_ascii_haystack);
    +        ok($utf8_ascii_haystack =~ /walrus|cat/ && $-[0] == 5000,
    +           'AC start-octet table works for UTF-8 invariant literals');
    +
    +        my $latin1_ascii_haystack = ("A" x 5000) . "cat";
    +        utf8::downgrade($latin1_ascii_haystack, 1);
    +        ok($latin1_ascii_haystack =~ /walrus|cat/ && $-[0] == 5000,
    +           'AC start-octet table works for Latin-1 invariant literals');
    +
    +        my $wide_only_re = qr/\x{400}foo|\x{800}bar/;
    +        my $latin1_wide_haystack = "A" x 5000;
    +        ok($latin1_wide_haystack !~ $wide_only_re,
    +           'AC with only wide literals rejects a Latin-1 target');
    +
    +        my $utf8_wide_haystack = ("A" x 5000) . "\x{800}bar";
    +        utf8::upgrade($utf8_wide_haystack);
    +        ok($utf8_wide_haystack =~ $wide_only_re && $-[0] == 5000,
    +           'AC with only wide literals still matches a UTF-8 target');
    +
    +        my $mixed_wide_re = qr/\x{400}foo|cat/;
    +        $latin1_wide_haystack .= "cat";
    +        ok($latin1_wide_haystack =~ $mixed_wide_re && $-[0] == 5000,
    +           'AC wide-literal shortcut preserves Latin-1 alternatives');
    +
    +        ok("abc" =~ /(?:|\x{400}foo)/ && $-[0] == 0 && $+[0] == 0,
    +           'AC wide-literal shortcut preserves an empty alternative');
    +
    +        my $trie_wide_re = qr/common\x{400}foo|common\x{800}bar/;
    +        my $latin1_trie_haystack = ("X" x 5000) . "common";
    +        ok($latin1_trie_haystack !~ $trie_wide_re,
    +           'Trie with only wide suffixes rejects a Latin-1 target');
    +
    +        my $utf8_trie_haystack = ("X" x 5000) . "common\x{800}bar";
    +        utf8::upgrade($utf8_trie_haystack);
    +        ok($utf8_trie_haystack =~ $trie_wide_re && $-[0] == 5000,
    +           'Trie with only wide suffixes still matches a UTF-8 target');
    +        my $mixed_trie_re = qr/common\x{400}foo|commoncat/;
    +        $latin1_trie_haystack .= "cat";
    +        ok($latin1_trie_haystack =~ $mixed_trie_re && $-[0] == 5000,
    +           'Trie wide-literal shortcut preserves Latin-1 alternatives');
    +
    +        my $utf8_haystack = ("\x{e9}" x 5000) . "\x{e9}cat";

    Understood, fixed.

    demerphq demerphq commented on code on Oct 20, 2026 13:58 UTC
    Code Review
    regcomp_trie.c:1
    @@ -2035,6 +2098,44 @@ Perl_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *s
             Safefree(path_depths);
             Safefree(parents);
         }
    +    else if (TRIE_IS_FOLDED(trie)
    +             && FLAGS(source) != EXACTFLU8
    +             && trie->startstate == 1 && !trie->states[1].wordnum
    +             && !trie->prefixlen_octets && !trie->prefixlen_chars)
    +    {
    +        SV *first_folds = NULL;
    +        U8 path[UTF8_MAXBYTES + 1];
    +        U8 *start_map;
    +        UV start, end;
    +
    +        /* BMH offsets in folded data do not describe the original target.
    +         * Leave both anchor lengths zero and use only the start map.  Locale
    +         * folding is excluded because its rules can change at execution. */
    +        aho->prefilter = (U8 *)PerlMemShared_calloc(
    +            REG_AC_PREFILTER_SIZE, sizeof(U8));
    +        start_map = aho->prefilter + REG_AC_PREFILTER_MAP_OFFSET;
    +        S_ac_map_folded_starts(aTHX_ trie, 1, path, 0, start_map, &first_folds);
    +
    +        /* A single target codepoint can supply several folded characters.
    +         * Add every such codepoint whose fold begins with a possible first
    +         * folded character.  We need not compare the rest of its fold: false
    +         * positives are safe, including folds extending beyond a trie word
    +         * into its following regex nodes. */
    +        invlist_iterinit(PL_HasMultiCharFold);

    Thanks, I followed up on this. We are already iterating over PL_HasMultiCharFold, so we know each character folds to multiple characters. AFAICT we still need the folding call to find its first folded character, so the macro wouldn't save work in this loop. Am I missing something?

    demerphq demerphq commented on Oct 26, 2026 08:44 UTC
    Author

    Hey @khwilliamson and @richardleach you have any objections on this? IMO it moves the needle in the right direction and I have further steps predicated on merging it.

    khwilliamson khwilliamson commented on Oct 27, 2026 00:22 UTC
    Reviewer

    A bunch of your commit messages begin with

    fixup!

    which makes no sense to me. I'm guessing these are notes to yourself; perhaps to squash.

    khwilliamson khwilliamson commented on code on Oct 27, 2026 00:39 UTC
    Code Review
    regcomp_trie.c:1
    @@ -803,6 +804,20 @@ Perl_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
                             uvc = (U32)*uc;
                             len = 1;
                         }
    +                    /* An input character can fold to several source
    +                     * characters. Do not extract a prefix ending inside
    +                     * that fold, including overlapping folds in "sss". */
    +                    if (folder && UTF && wordlen < 256) {
    +                        const STRLEN folded_octets
    +                            = is_MULTI_CHAR_FOLD_utf8_safe(uc, e);
    +                        if (folded_octets) {
    +                            const U32 folded_chars
    +                                = utf8_length(uc, uc + folded_octets);

    Unicode guarantees that all folds contain 1, 2, or 3 characters. Hence at this point we know the answer is 2 or 3. There exists some macros that check the UTF-8 bytes to see if they are 3 character folds. That might be faster than calculating the length and the compiler might be able to optimize it better. Note that speed isn't particularly important during parsing. If you choose to go this route, the existing is_THREE_CHAR_FOLD_HEAD_utf8_safe would be best. It would be trivial for me or you to create a non-safe version with fewer checks by adding that to regen/regcharclass.pl. The is_MULTI_CHAR_FOLD_utf8_safe call has already ruled out non-safety.

    khwilliamson khwilliamson commented on Oct 27, 2026 00:59 UTC
    Reviewer

    I like the explanations about "'native-Unicode". There is text at the beginning of perlapi.pod that could stand to be updated with something like this. That might not need to go into this PR.

    I'm not bothered by 'cp' vs 'ncp', but I'm more familiar with this stuff, so I would defer to you on this. But when I see 'ncp', I think of 'new' and not 'native'. Maybe there's a better term, such as 'vcp' or 'nvcp' or 'ntvcp'. In any case, it needs to be explained somewhere.

    Many elements with 'uni' in their names DO refer to the Unicode values, not native. I'm trying to create and document 'uv' instead for people to use almost everywhere to mean the native-Unicode. Almost no one needs the straight Unicode

    demerphq demerphq commented on Oct 27, 2026 09:52 UTC
    Author

    A bunch of your commit messages begin with

    > > fixup!

    > which makes no sense to me. I'm guessing these are notes to yourself; perhaps to squash.

    They are specially formatted patches intended for autosquash.

    git rebase -i --autosquash $branch

    will automerge them into the relevant patch based on the subject line. Its so you can create a fixup patch and show it to someone without rebasing it together and obscuring the change. I did it to make my followups easier to review.

    cheers,
    Yves

    demerphq demerphq commented on Oct 27, 2026 10:11 UTC
    Author

    I'm not bothered by 'cp' vs 'ncp', but I'm more familiar with this stuff, so I would defer to you on this. But when I see 'ncp', I think of 'new' and not 'native'. Maybe there's a better term, such as 'vcp' or 'nvcp' or 'ntvcp'. In any case, it needs to be explained somewhere.

    I am not fussed on the names, but I think it would be nice to have a standard convention for stuff so arguments are self documenting to a certain extent.

    So just in terms of getting this patch approved what do you want me to do? Undo the ncp change?

    khwilliamson khwilliamson commented on code on Oct 27, 2026 10:54 UTC
    Code Review
    perl.c:1
    @@ -112,10 +112,12 @@ S_init_native_octet_utf8(pTHX)
          * another interpreter is constructed.  It depends only on the character
          * set selected at compile time. */
         for (i = 0; i < 256; i++) {
    -        U8 * const end = uv_to_utf8_flags(
    -            PL_native_octet_utf8[i].bytes, i, 0);
    -        PL_native_octet_utf8[i].len = (U8)(end -
    -                                          PL_native_octet_utf8[i].bytes);
    +        U8 encoded[UTF8_MAXBYTES + 1];
    +        U8 * const end = uv_to_utf8_flags(encoded, i, 0);
    +        assert(end - encoded == 1 || end - encoded == 2);
    +        assert(end - encoded == 1 || encoded[1]);
    +        PL_native_octet_utf8[i] = encoded[0]

    Several things that hardly are worth mentioning, except to educate readers of this not intimately familiar with these kinds of things. But this whole construct can be greatly simplified. See the comment below on the next source line.

  • I'm unsure why you feel the need to assert the basic operation of uv_to_utf8. If it is broken, perl likely won't even compile. Maybe a non-reviewer would just skip over it. My guess is that you're checking that the new code's expectations are being met.

  • Plain uv_to_utf8 is probably better here. Seeing the current text makes me wonder why does the code need to use a 0 flag?

  • assert(inRANGE(end - encoded, 1, 2)) could be used; it uses a single conditional. I've gotten in the habit of using it, so not using it stands out to me. Other readers might prefer the current text. Performance isn't an issue here; so it comes down to clarity for an average reader. I don't know the answer to that.

  • Since you're going to the trouble of checking this validity, why not do a stricter check. I'd rewrite the second assert as assert(end - encoded == 1 || UTF8_IS_CONTINUATION(encoded[1]));

  • You don't check that if the length is 1 that the upper byte is 0
  • khwilliamson khwilliamson commented on code on Oct 27, 2026 11:07 UTC
    Code Review
    perl.c:1
    @@ -112,10 +112,12 @@ S_init_native_octet_utf8(pTHX)
          * another interpreter is constructed.  It depends only on the character
          * set selected at compile time. */
         for (i = 0; i < 256; i++) {
    -        U8 * const end = uv_to_utf8_flags(
    -            PL_native_octet_utf8[i].bytes, i, 0);
    -        PL_native_octet_utf8[i].len = (U8)(end -
    -                                          PL_native_octet_utf8[i].bytes);
    +        U8 encoded[UTF8_MAXBYTES + 1];
    +        U8 * const end = uv_to_utf8_flags(encoded, i, 0);
    +        assert(end - encoded == 1 || end - encoded == 2);
    +        assert(end - encoded == 1 || encoded[1]);
    +        PL_native_octet_utf8[i] = encoded[0]
    +            | (end - encoded == 2 ? (U16)encoded[1] << 8 : 0);

    There already exist some macros that make this loop simpler, and clearer.

        for (i = 0; i < 256; i++) {
            if (UVCHR_IS_INVARIANT(i)) {
                PL_native_octet_utf8[i] = i;
            }
            else {
                PL_native_octet_utf8[i] =  (UTF8_EIGHT_BIT_HI(i) << 8)
                                          | UTF8_EIGHT_BIT_LO(i);
            }
        }
    

    demerphq demerphq commented on code on Oct 27, 2026 11:13 UTC
    Code Review
    perl.c:1
    @@ -112,10 +112,12 @@ S_init_native_octet_utf8(pTHX)
          * another interpreter is constructed.  It depends only on the character
          * set selected at compile time. */
         for (i = 0; i < 256; i++) {
    -        U8 * const end = uv_to_utf8_flags(
    -            PL_native_octet_utf8[i].bytes, i, 0);
    -        PL_native_octet_utf8[i].len = (U8)(end -
    -                                          PL_native_octet_utf8[i].bytes);
    +        U8 encoded[UTF8_MAXBYTES + 1];
    +        U8 * const end = uv_to_utf8_flags(encoded, i, 0);
    +        assert(end - encoded == 1 || end - encoded == 2);
    +        assert(end - encoded == 1 || encoded[1]);
    +        PL_native_octet_utf8[i] = encoded[0]
    +            | (end - encoded == 2 ? (U16)encoded[1] << 8 : 0);

    I applied this macro-based approach with one order adjustment. The trie table stores the first encoded octet in the low byte of the U16 and the second in the high byte, as the executor reads the low byte first and then shifts by 8. So the packing is UTF8_EIGHT_BIT_HI(i) | ((U16)UTF8_EIGHT_BIT_LO(i) << 8). The expression in the example would reverse the order seen by the executor.

    demerphq demerphq commented on code on Oct 27, 2026 11:13 UTC
    Code Review
    perl.c:1
    @@ -112,10 +112,12 @@ S_init_native_octet_utf8(pTHX)
          * another interpreter is constructed.  It depends only on the character
          * set selected at compile time. */
         for (i = 0; i < 256; i++) {
    -        U8 * const end = uv_to_utf8_flags(
    -            PL_native_octet_utf8[i].bytes, i, 0);
    -        PL_native_octet_utf8[i].len = (U8)(end -
    -                                          PL_native_octet_utf8[i].bytes);
    +        U8 encoded[UTF8_MAXBYTES + 1];
    +        U8 * const end = uv_to_utf8_flags(encoded, i, 0);
    +        assert(end - encoded == 1 || end - encoded == 2);
    +        assert(end - encoded == 1 || encoded[1]);
    +        PL_native_octet_utf8[i] = encoded[0]

    Agreed, thanks. The input is constrained to native values 0..255, so the length and validity assertions duplicate guarantees of the encoder. I replaced the encoder call, temporary buffer, and assertions with an invariant check and the existing UTF8_EIGHT_BIT_HI/LO macros.

    The asserts were from when I was debugging during dev, and thought I had misunderstood how the function worked so added the asserts to be sure.

    demerphq demerphq commented on code on Oct 27, 2026 11:15 UTC
    Code Review
    regcomp_trie.c:1
    @@ -803,6 +804,20 @@ Perl_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
                             uvc = (U32)*uc;
                             len = 1;
                         }
    +                    /* An input character can fold to several source
    +                     * characters. Do not extract a prefix ending inside
    +                     * that fold, including overlapping folds in "sss". */
    +                    if (folder && UTF && wordlen < 256) {
    +                        const STRLEN folded_octets
    +                            = is_MULTI_CHAR_FOLD_utf8_safe(uc, e);
    +                        if (folded_octets) {
    +                            const U32 folded_chars
    +                                = utf8_length(uc, uc + folded_octets);

    Thanks. I replaced utf8_length() with is_THREE_CHAR_FOLD_HEAD_utf8_safe() after the multi-character-fold check. That distinguishes the three-character folds from the two-character folds without counting UTF-8 characters during parsing.

    demerphq demerphq commented on code on Oct 27, 2026 11:15 UTC
    Code Review
    t/re/pat.t:1
    @@ -28,14 +28,326 @@ skip_all_without_unicode_tables();
     my $has_locales = locales_enabled('LC_CTYPE');
     my $utf8_locale = find_utf8_ctype_locale();
     
    -plan tests => 1315;  # Update this when adding/deleting tests.
    +plan tests => 1588;  # Update this when adding/deleting tests.
     
     run_tests() unless caller;
     
     #
     # Tests start here.
     #
     sub run_tests {
    +    {
    +        my $haystack = ("A" x 5000) . "cat";
    +        ok($haystack =~ /walrus|cat/, 'AC finds a literal after a long rejected run');
    +
    +        $haystack = ("A" x 5000) . "dog";
    +        ok($haystack !~ /walrus|cat/, 'AC rejects a long run with no literal');
    +
    +        my $zero_shift_match = "cacc" . ("c" x 5000);
    +        ok($zero_shift_match =~ /acc|zdd/ && $-[0] == 1,
    +           'AC zero-shift rejection does not skip a later match');
    +
    +        my $zero_shift_run = ("c" x 5000) . "acc";
    +        ok($zero_shift_run =~ /acc|zdd/ && $-[0] == 5000,
    +           'AC zero-shift map rejection skips a repeated octet run');
    +
    +        utf8::upgrade($zero_shift_run);
    +        ok($zero_shift_run =~ /acc|zdd/ && $-[0] == 5000,
    +           'AC zero-shift map rejection skips an ASCII run in UTF-8');
    +
    +        $zero_shift_run = "c" x 5000;
    +        ok($zero_shift_run !~ /acc|zdd/,
    +           'AC zero-shift map rejection handles a run ending at string end');
    +
    +        my $shift_one_run = ("e" x 5000) . "fghijY";
    +        ok($shift_one_run =~ /abcdeX|fghijY/ && $-[0] == 5000,
    +           'AC repeated-sequence scan handles rejected starts with shift one');
    +
    +        utf8::upgrade($shift_one_run);
    +        ok($shift_one_run =~ /abcdeX|fghijY/ && $-[0] == 5000,
    +           'AC shift-one repeated-sequence scan handles UTF-8 targets');
    +
    +        $shift_one_run = "e" x 5000;
    +        ok($shift_one_run !~ /abcdeX|fghijY/,
    +           'AC shift-one repeated-sequence scan rejects a long non-match');
    +
    +        my $alternating_run = ("AB" x 5001) . "barB";
    +        ok($alternating_run =~ /fooA|barB/ && $-[0] == 10002,
    +           'AC skips repeated UV blocks with rejected alternating starts');
    +
    +        for my $offset (0 .. 7) {
    +            my $aligned_run = ("X" x $offset) . ("AB" x 5000) . "barB";
    +            ok($aligned_run =~ /fooA|barB/ && $-[0] == $offset + 10000,
    +               "AC repeated-block scan finds the match at offset $offset");
    +        }
    +
    +        utf8::upgrade($alternating_run);
    +        ok($alternating_run =~ /fooA|barB/ && $-[0] == 10002,
    +           'AC skips repeated UV blocks in a UTF-8 target');
    +
    +        for my $offset (0 .. 7) {
    +            my $aligned_run = ("X" x $offset) . ("AB" x 5000) . "barB";
    +            utf8::upgrade($aligned_run);
    +            ok($aligned_run =~ /fooA|barB/ && $-[0] == $offset + 10000,
    +               "AC UTF-8 repeated-block scan finds offset $offset");
    +        }
    +
    +        my $wide_alternating_run = ("\x{100}" x 5001) . "ba\x{200}";
    +        ok($wide_alternating_run =~ /fo\x{100}|ba\x{200}/
    +           && $-[0] == 5001,
    +           'AC skips repeated UTF-8 character blocks at character boundaries');
    +
    +        $wide_alternating_run = "\x{100}" x 5001;
    +        ok($wide_alternating_run !~ /fo\x{100}|ba\x{200}/,
    +           'AC rejects repeated UTF-8 character blocks without a match');
    +
    +        $haystack = ("A" x 5000) . "cat";
    +        ok($haystack =~ /(?:|walrus|cat)/ && $-[0] == 0 && $+[0] == 0,
    +           'AC with an empty alternative keeps the earliest empty match');
    +
    +        my $six_octet_haystack = ("A" x 5000) . "catcat";
    +        ok($six_octet_haystack =~ /walruswalrus|catcat/,
    +           'AC combined prefilter handles six-octet literals');
    +
    +        $six_octet_haystack = ("A" x 5000) . "dogdog";
    +        ok($six_octet_haystack !~ /walruswalrus|catcat/,
    +           'AC combined prefilter rejects a six-octet near miss');
    +
    +        my $seven_octet_haystack = ("A" x 5000) . "catcatx";
    +        ok($seven_octet_haystack =~ /walrusx|catcatx/,
    +           'AC combined prefilter handles seven-octet literals');
    +
    +        $seven_octet_haystack = ("x" x 5000);
    +        ok($seven_octet_haystack !~ /walrusx|catcatx/,
    +           'AC BMH prefilter handles frequent anchor-octet candidates');
    +
    +        my $long_haystack = ("A" x 5000) . "catcatcatcat";
    +        ok($long_haystack =~ /walruswalruswalruswalrus|catcatcatcat/,
    +           'AC BMH prefilter finds a long literal after rejected input');
    +
    +        $long_haystack = ("A" x 5000) . "dogdogdogdog";
    +        ok($long_haystack !~ /walruswalruswalruswalrus|catcatcatcat/,
    +           'AC BMH prefilter rejects a long run with no literal');
    +
    +        my $very_long_a = "walrus" x 50;
    +        my $very_long_b = "cat" x 100;
    +        my $very_long_re = qr/\Q$very_long_a\E|\Q$very_long_b\E/;
    +        my $very_long_haystack = ("A" x 5000) . $very_long_b;
    +        ok($very_long_haystack =~ $very_long_re,
    +           'AC BMH prefilter finds a 300-octet literal with capped shifts');
    +
    +        $very_long_haystack = ("A" x 5000) . ("dog" x 100);
    +        ok($very_long_haystack !~ $very_long_re,
    +           'AC BMH prefilter rejects a 300-octet near miss');
    +
    +        my @many_literals = map {
    +            chr(ord('a') + $_ % 26) . sprintf('%06d', $_)
    +        } 0 .. 255;
    +        my $many_pattern = join '|', map { quotemeta($_) } @many_literals;
    +        my $many_re = qr/(?:$many_pattern)/;
    +        my $many_haystack = ("Z" x 5000) . $many_literals[-1];
    +        ok($many_haystack =~ $many_re && $-[0] == 5000,
    +           'AC high-alternative-count prefilter finds a late match');
    +
    +        $many_haystack = "Z" x 5000;
    +        ok($many_haystack !~ $many_re,
    +           'AC high-alternative-count prefilter rejects a non-match');
    +
    +        my $overlap_haystack = ("A" x 5000) . "abcdefghijk";
    +        ok($overlap_haystack =~ /abcdefghij|defghijk/ && $-[0] == 5000
    +           && $+[0] == 5010,
    +           'AC BMH preserves the leftmost overlapping match');
    +
    +        my $utf8_ascii_haystack = ("A" x 5000) . "cat";
    +        utf8::upgrade($utf8_ascii_haystack);
    +        ok($utf8_ascii_haystack =~ /walrus|cat/ && $-[0] == 5000,
    +           'AC start-octet table works for UTF-8 invariant literals');
    +
    +        my $latin1_ascii_haystack = ("A" x 5000) . "cat";
    +        utf8::downgrade($latin1_ascii_haystack, 1);
    +        ok($latin1_ascii_haystack =~ /walrus|cat/ && $-[0] == 5000,
    +           'AC start-octet table works for Latin-1 invariant literals');
    +
    +        my $wide_only_re = qr/\x{400}foo|\x{800}bar/;
    +        my $latin1_wide_haystack = "A" x 5000;
    +        ok($latin1_wide_haystack !~ $wide_only_re,
    +           'AC with only wide literals rejects a Latin-1 target');
    +
    +        my $utf8_wide_haystack = ("A" x 5000) . "\x{800}bar";
    +        utf8::upgrade($utf8_wide_haystack);
    +        ok($utf8_wide_haystack =~ $wide_only_re && $-[0] == 5000,
    +           'AC with only wide literals still matches a UTF-8 target');
    +
    +        my $mixed_wide_re = qr/\x{400}foo|cat/;
    +        $latin1_wide_haystack .= "cat";
    +        ok($latin1_wide_haystack =~ $mixed_wide_re && $-[0] == 5000,
    +           'AC wide-literal shortcut preserves Latin-1 alternatives');
    +
    +        ok("abc" =~ /(?:|\x{400}foo)/ && $-[0] == 0 && $+[0] == 0,
    +           'AC wide-literal shortcut preserves an empty alternative');
    +
    +        my $trie_wide_re = qr/common\x{400}foo|common\x{800}bar/;
    +        my $latin1_trie_haystack = ("X" x 5000) . "common";
    +        ok($latin1_trie_haystack !~ $trie_wide_re,
    +           'Trie with only wide suffixes rejects a Latin-1 target');
    +
    +        my $utf8_trie_haystack = ("X" x 5000) . "common\x{800}bar";
    +        utf8::upgrade($utf8_trie_haystack);
    +        ok($utf8_trie_haystack =~ $trie_wide_re && $-[0] == 5000,
    +           'Trie with only wide suffixes still matches a UTF-8 target');
    +        my $mixed_trie_re = qr/common\x{400}foo|commoncat/;
    +        $latin1_trie_haystack .= "cat";
    +        ok($latin1_trie_haystack =~ $mixed_trie_re && $-[0] == 5000,
    +           'Trie wide-literal shortcut preserves Latin-1 alternatives');
    +
    +        my $utf8_haystack = ("\x{e9}" x 5000) . "\x{e9}cat";
    +        utf8::upgrade($utf8_haystack);
    +        ok($utf8_haystack =~ /\x{e9}cat|zebra/,
    +           'UTF-8 AC finds a multi-byte literal after rejected input');
    +
    +        my $latin1_haystack = ("\xE9" x 5000) . "\xE9cat";
    +        ok($latin1_haystack =~ /\x{e9}cat|zebra/,
    +           'Latin-1 AC preserves matching for an awkward code point');
    +
    +        for my $encoding ('Latin-1', 'UTF-8') {
    +            # The shortest word occupies two Latin-1 octets or three UTF-8
    +            # octets.  Check both alternatives with each target encoding.
    +            my $different_lengths_re = qr/\x{e9}a|zbc/;
    +
    +            for my $suffix ("\x{e9}a", 'zbc') {
    +                my $target = ('Q' x 17) . $suffix;
    +                utf8::upgrade($target) if $encoding eq 'UTF-8';
    +
    +                ok($target =~ $different_lengths_re && $-[0] == 17
    +                   && $+[0] == length($target),
    +                   "AC uses the effective literal length for $encoding");
    +            }
    +
    +            # Excluding the wide word gives a nine-octet Latin-1 minimum.
    +            # Including it gives a three-octet UTF-8 minimum.
    +            my $mixed_lengths_re = qr/\x{100}x|abcdefghi/;
    +            my $mixed_target = ('x' x 17) . 'abcdefghi';
    +            utf8::upgrade($mixed_target) if $encoding eq 'UTF-8';
    +
    +            ok($mixed_target =~ $mixed_lengths_re && $-[0] == 17,
    +               "AC mixed wide alternatives find a narrow word in $encoding");
    +
    +            $mixed_target = 'x' x 17;
    +            utf8::upgrade($mixed_target) if $encoding eq 'UTF-8';
    +
    +            ok($mixed_target !~ $mixed_lengths_re,
    +               "AC mixed wide alternatives reject a short miss in $encoding");
    +
    +            my $root_restart = ('a' x 17) . 'de';
    +            utf8::upgrade($root_restart) if $encoding eq 'UTF-8';
    +
    +            ok($root_restart =~ /abc|de/ && $-[0] == 17 && $+[0] == 19,
    +               "AC resets the point ring on repeated root transitions in $encoding");
    +
    +            my $fallback_target = 'abcdgu';
    +            utf8::upgrade($fallback_target) if $encoding eq 'UTF-8';
    +
    +            ok($fallback_target =~ /abcdefg|cdgu/
    +               && $-[0] == 2 && $+[0] == 6,
    +               "AC keeps the point ring across a suffix failure transition in $encoding");
    +
    +            my $retry_target = 'abcdX';
    +            utf8::upgrade($retry_target) if $encoding eq 'UTF-8';
    +
    +            ok($retry_target =~ /(?:abc|bcd)X/ && $-[0] == 1 && $+[0] == 5,
    +               "AC retries an overlapping start after full-match rejection in $encoding");
    +
    +            # Prefilters are disabled for folds, but the point-ring changes
    +            # apply there too.  One sharp s contributes two folded characters.
    +            for my $case (["\x{df}x", 0, 2],

    Fixed: the test now converts U+00E9 with uni_to_native(), and the table-driven cases construct native characters with chr(). It no longer assumes that a value below 0x100 has the same character meaning on ASCII and EBCDIC.

    demerphq demerphq commented on Oct 27, 2026 11:15 UTC
    Author

    Following up on your review: I renamed the to_uni_upper parameter from ncp to uv in the declaration and implementation, and added an explanation of native-Unicode numbering near the start of the generated perlapi documentation. The API introduction now explains the 0..255/native and above-255/Unicode split, when NATIVE_TO_UNI and UNI_TO_NATIVE are useful, and that older names containing uni may use native-Unicode values.

    demerphq demerphq commented on code on Oct 27, 2026 12:46 UTC
    Code Review
    regcomp_trie.c:1
    @@ -1772,6 +1772,69 @@ S_ac_path_as_latin1(const U8 *path, const U32 path_len, const U32 source_chars,
         return TRUE;
     }
     
    +/* The map describes original target octets, rather than trie transitions.
    + * A wide codepoint has only a UTF-8 entry.  Native Latin-1 codepoints have
    + * an entry for each target encoding. */
    +static void
    +S_ac_map_start_codepoint(pTHX_ U8 *map, const UV cp)
    +{
    +    U8 encoded[UTF8_MAXBYTES + 1];
    +
    +    if (cp <= 255)
    +        map[(U8)cp] |= REG_AC_PREFILTER_LATIN1_MASK;
    +    uvchr_to_utf8(encoded, cp);
    +    map[encoded[0]] |= REG_AC_PREFILTER_UTF8_MASK;
    +}
    +
    +/* Folded trie paths are UTF-8 encoded.  Visit only the first codepoint of
    + * each path, not every accepting word sharing that initial codepoint. */
    +static void
    +S_ac_map_folded_starts(pTHX_ const reg_trie_data *trie, const U32 state,
    +                       U8 *path, const U32 path_len, U8 *map,
    +                       SV **first_folds)
    +{
    +    const U32 base = trie->states[state].trans.base;
    +
    +    for (U32 ch = trie->states[state].min_octet;
    +         base && ch <= trie->states[state].max_octet; ch++)
    +    {
    +        const U32 next = S_trie_trans_state(trie, state, base, ch, 0);
    +
    +        if (!next)
    +            continue;
    +
    +        assert(path_len < UTF8_MAXBYTES);
    +        path[path_len] = (U8)ch;
    +        if (path_len + 1 == UTF8SKIP(path)) {
    +            U8 folded[UTF8_MAXBYTES_CASE + 1];
    +            STRLEN folded_len;
    +            U32 first;
    +            const U32 *remaining;
    +            const UV cp = valid_utf8_to_uv(path, NULL);
    +            const UV initial = to_uni_fold(cp, folded, &folded_len);
    +            const Size_t count = inverse_folds_(initial, &first, &remaining);
    +
    +            /* Unicode closure is a safe superset for /d and /aa.  Extra
    +             * candidates reach AC, which applies the actual folding rules.
    +             * Keep the literal itself and native /d's paired character too. */

    I left the start map as a conservative superset for /aa. The Unicode closure may admit extra candidates, but the executor applies the actual /aa folding rules, so those candidates cannot become false matches. A mode-specific restriction could reduce map hits, but it is a separate performance optimization; I did not add it without measuring a benefit.

    khwilliamson khwilliamson commented on code on Oct 28, 2026 10:10 UTC
    Code Review
    regcomp_trie.c:1
    @@ -1779,6 +1779,69 @@ S_ac_path_as_latin1(const U8 *path, const U32 path_len, const U32 source_chars,
         return TRUE;
     }
     
    +/* The map describes original target octets, rather than trie transitions.
    + * A wide codepoint has only a UTF-8 entry.  Native Latin-1 codepoints have
    + * an entry for each target encoding. */
    +static void
    +S_ac_map_start_codepoint(pTHX_ U8 *map, const UV cp)
    +{
    +    U8 encoded[UTF8_MAXBYTES + 1];
    +
    +    if (cp <= 255)
    +        map[(U8)cp] |= REG_AC_PREFILTER_LATIN1_MASK;
    +    uvchr_to_utf8(encoded, cp);

    Here and elsewhere. As I've mentioned elsewhere, I'm trying to standardize on a single style for naming functions and macros like this, so that you don't have to remember to use uvchr here and uni there, etc. And that new style is uv everywhere. As such, I'd prefer if you use uv_to_utf8 since it is new code. I need to mark in perlapi that the uvchr form is back-compat.

    There's several places in this PR that a new uvchr is introduced

    richardleach richardleach commented on Oct 28, 2026 11:12 UTC
    Contributor

    Hey @khwilliamson and @richardleach you have any objections on this? IMO it moves the needle in the right direction and I have further steps predicated on merging it.

    I've not looked closely in more than a week. Will look this afternoon, but probably not going to be anything from me.

    (In terms of juicing finding the start position: where 1-4 masks is enough to describe the possible start octet, a S_find_next_masked_n applying to 64 octets-at-a-time seems to have the potentially to be very fast, but I've not fully worked through it and wouldn't know how to wire it in / with what fallback. I can play with it some more / tidy ready to share if it sounds useful. Don't know what your follow-on plans are.)

    khwilliamson khwilliamson commented on code on Oct 28, 2026 18:36 UTC
    Code Review
    regexec.c:1
    @@ -1983,29 +1986,26 @@ STMT_START {                                                                \
         case trie_utf8:                                                         \
             (void) utf8_to_uv_flags( (const U8*) uc, uc_end, &uvc, &len,        \
                                      (uniflags|UTF8_DIE_IF_MALFORMED));         \
    +        skiplen = uvchr_to_utf8(octet_buffer, uvc) - octet_buffer;          \
    +        trie_bytes = octet_buffer;                                          \

    I don't understand this. Isn't skiplen the same as UTF8SKIP(uc) (or SAFE_SKIP), and couldn't one just Copy uc to octet_buffer

    demerphq demerphq commented on Oct 29, 2026 19:23 UTC
    Author

    Id like to get this applied, it has multiple good things in it, and I think does no new harm. Also I have a bunch of work predicated on it.

    richardleach richardleach commented on Oct 29, 2026 22:22 UTC
    Contributor

    Id like to get this applied, it has multiple good things in it, and I think does no new harm. Also I have a bunch of work predicated on it.

    I've got no new comments at present and don't want to hold you up at this stage in the dev cycle.

    Only lingering concern is: how likely do you expect repeated UV blocks to feature in real-world workloads? Is it going to be enough for that part of the scanner to kick-in?

    demerphq demerphq commented on Oct 30, 2026 08:09 UTC
    Author

    Only lingering concern is: how likely do you expect repeated UV blocks to feature in real-world workloads? Is it going to be enough for that part of the scanner to kick-in?

    Anecdotally I think scanning documents with lots of whitespace is pretty common. But its a good question.

    Reviewers
    Assignees
    demerphq demerphq
    Labels
    risk: low confidence: 91.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 91.2% · Lower = rushed or shallow review
    91.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.3% · Safe to merge
    6.3%
    Repository