This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Change private function to static
[perl5.git] / regcomp.c
1 /*    regcomp.c
2  */
3
4 /*
5  * 'A fair jaw-cracker dwarf-language must be.'            --Samwise Gamgee
6  *
7  *     [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
8  */
9
10 /* This file contains functions for compiling a regular expression.  See
11  * also regexec.c which funnily enough, contains functions for executing
12  * a regular expression.
13  *
14  * This file is also copied at build time to ext/re/re_comp.c, where
15  * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
16  * This causes the main functions to be compiled under new names and with
17  * debugging support added, which makes "use re 'debug'" work.
18  */
19
20 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
21  * confused with the original package (see point 3 below).  Thanks, Henry!
22  */
23
24 /* Additional note: this code is very heavily munged from Henry's version
25  * in places.  In some spots I've traded clarity for efficiency, so don't
26  * blame Henry for some of the lack of readability.
27  */
28
29 /* The names of the functions have been changed from regcomp and
30  * regexec to pregcomp and pregexec in order to avoid conflicts
31  * with the POSIX routines of the same names.
32 */
33
34 #ifdef PERL_EXT_RE_BUILD
35 #include "re_top.h"
36 #endif
37
38 /*
39  * pregcomp and pregexec -- regsub and regerror are not used in perl
40  *
41  *      Copyright (c) 1986 by University of Toronto.
42  *      Written by Henry Spencer.  Not derived from licensed software.
43  *
44  *      Permission is granted to anyone to use this software for any
45  *      purpose on any computer system, and to redistribute it freely,
46  *      subject to the following restrictions:
47  *
48  *      1. The author is not responsible for the consequences of use of
49  *              this software, no matter how awful, even if they arise
50  *              from defects in it.
51  *
52  *      2. The origin of this software must not be misrepresented, either
53  *              by explicit claim or by omission.
54  *
55  *      3. Altered versions must be plainly marked as such, and must not
56  *              be misrepresented as being the original software.
57  *
58  *
59  ****    Alterations to Henry's code are...
60  ****
61  ****    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
62  ****    2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
63  ****    by Larry Wall and others
64  ****
65  ****    You may distribute under the terms of either the GNU General Public
66  ****    License or the Artistic License, as specified in the README file.
67
68  *
69  * Beware that some of this code is subtly aware of the way operator
70  * precedence is structured in regular expressions.  Serious changes in
71  * regular-expression syntax might require a total rethink.
72  */
73 #include "EXTERN.h"
74 #define PERL_IN_REGCOMP_C
75 #include "perl.h"
76
77 #ifndef PERL_IN_XSUB_RE
78 #  include "INTERN.h"
79 #endif
80
81 #define REG_COMP_C
82 #ifdef PERL_IN_XSUB_RE
83 #  include "re_comp.h"
84 EXTERN_C const struct regexp_engine my_reg_engine;
85 #else
86 #  include "regcomp.h"
87 #endif
88
89 #include "dquote_inline.h"
90 #include "invlist_inline.h"
91 #include "unicode_constants.h"
92
93 #define HAS_NONLATIN1_FOLD_CLOSURE(i) \
94  _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
95 #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
96  _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
97 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
98 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
99
100 #ifndef STATIC
101 #define STATIC  static
102 #endif
103
104 #ifndef MIN
105 #define MIN(a,b) ((a) < (b) ? (a) : (b))
106 #endif
107
108 /* this is a chain of data about sub patterns we are processing that
109    need to be handled separately/specially in study_chunk. Its so
110    we can simulate recursion without losing state.  */
111 struct scan_frame;
112 typedef struct scan_frame {
113     regnode *last_regnode;      /* last node to process in this frame */
114     regnode *next_regnode;      /* next node to process when last is reached */
115     U32 prev_recursed_depth;
116     I32 stopparen;              /* what stopparen do we use */
117     U32 is_top_frame;           /* what flags do we use? */
118
119     struct scan_frame *this_prev_frame; /* this previous frame */
120     struct scan_frame *prev_frame;      /* previous frame */
121     struct scan_frame *next_frame;      /* next frame */
122 } scan_frame;
123
124 /* Certain characters are output as a sequence with the first being a
125  * backslash. */
126 #define isBACKSLASHED_PUNCT(c)                                              \
127                     ((c) == '-' || (c) == ']' || (c) == '\\' || (c) == '^')
128
129
130 struct RExC_state_t {
131     U32         flags;                  /* RXf_* are we folding, multilining? */
132     U32         pm_flags;               /* PMf_* stuff from the calling PMOP */
133     char        *precomp;               /* uncompiled string. */
134     char        *precomp_end;           /* pointer to end of uncompiled string. */
135     REGEXP      *rx_sv;                 /* The SV that is the regexp. */
136     regexp      *rx;                    /* perl core regexp structure */
137     regexp_internal     *rxi;           /* internal data for regexp object
138                                            pprivate field */
139     char        *start;                 /* Start of input for compile */
140     char        *end;                   /* End of input for compile */
141     char        *parse;                 /* Input-scan pointer. */
142     char        *adjusted_start;        /* 'start', adjusted.  See code use */
143     STRLEN      precomp_adj;            /* an offset beyond precomp.  See code use */
144     SSize_t     whilem_seen;            /* number of WHILEM in this expr */
145     regnode     *emit_start;            /* Start of emitted-code area */
146     regnode     *emit_bound;            /* First regnode outside of the
147                                            allocated space */
148     regnode     *emit;                  /* Code-emit pointer; if = &emit_dummy,
149                                            implies compiling, so don't emit */
150     regnode_ssc emit_dummy;             /* placeholder for emit to point to;
151                                            large enough for the largest
152                                            non-EXACTish node, so can use it as
153                                            scratch in pass1 */
154     I32         naughty;                /* How bad is this pattern? */
155     I32         sawback;                /* Did we see \1, ...? */
156     U32         seen;
157     SSize_t     size;                   /* Code size. */
158     I32                npar;            /* Capture buffer count, (OPEN) plus
159                                            one. ("par" 0 is the whole
160                                            pattern)*/
161     I32         nestroot;               /* root parens we are in - used by
162                                            accept */
163     I32         extralen;
164     I32         seen_zerolen;
165     regnode     **open_parens;          /* pointers to open parens */
166     regnode     **close_parens;         /* pointers to close parens */
167     regnode     *opend;                 /* END node in program */
168     I32         utf8;           /* whether the pattern is utf8 or not */
169     I32         orig_utf8;      /* whether the pattern was originally in utf8 */
170                                 /* XXX use this for future optimisation of case
171                                  * where pattern must be upgraded to utf8. */
172     I32         uni_semantics;  /* If a d charset modifier should use unicode
173                                    rules, even if the pattern is not in
174                                    utf8 */
175     HV          *paren_names;           /* Paren names */
176
177     regnode     **recurse;              /* Recurse regops */
178     I32         recurse_count;          /* Number of recurse regops */
179     U8          *study_chunk_recursed;  /* bitmap of which subs we have moved
180                                            through */
181     U32         study_chunk_recursed_bytes;  /* bytes in bitmap */
182     I32         in_lookbehind;
183     I32         contains_locale;
184     I32         contains_i;
185     I32         override_recoding;
186 #ifdef EBCDIC
187     I32         recode_x_to_native;
188 #endif
189     I32         in_multi_char_class;
190     struct reg_code_block *code_blocks; /* positions of literal (?{})
191                                             within pattern */
192     int         num_code_blocks;        /* size of code_blocks[] */
193     int         code_index;             /* next code_blocks[] slot */
194     SSize_t     maxlen;                        /* mininum possible number of chars in string to match */
195     scan_frame *frame_head;
196     scan_frame *frame_last;
197     U32         frame_count;
198 #ifdef ADD_TO_REGEXEC
199     char        *starttry;              /* -Dr: where regtry was called. */
200 #define RExC_starttry   (pRExC_state->starttry)
201 #endif
202     SV          *runtime_code_qr;       /* qr with the runtime code blocks */
203 #ifdef DEBUGGING
204     const char  *lastparse;
205     I32         lastnum;
206     AV          *paren_name_list;       /* idx -> name */
207     U32         study_chunk_recursed_count;
208     SV          *mysv1;
209     SV          *mysv2;
210 #define RExC_lastparse  (pRExC_state->lastparse)
211 #define RExC_lastnum    (pRExC_state->lastnum)
212 #define RExC_paren_name_list    (pRExC_state->paren_name_list)
213 #define RExC_study_chunk_recursed_count    (pRExC_state->study_chunk_recursed_count)
214 #define RExC_mysv       (pRExC_state->mysv1)
215 #define RExC_mysv1      (pRExC_state->mysv1)
216 #define RExC_mysv2      (pRExC_state->mysv2)
217
218 #endif
219     bool        seen_unfolded_sharp_s;
220     bool        strict;
221 };
222
223 #define RExC_flags      (pRExC_state->flags)
224 #define RExC_pm_flags   (pRExC_state->pm_flags)
225 #define RExC_precomp    (pRExC_state->precomp)
226 #define RExC_precomp_adj (pRExC_state->precomp_adj)
227 #define RExC_adjusted_start  (pRExC_state->adjusted_start)
228 #define RExC_precomp_end (pRExC_state->precomp_end)
229 #define RExC_rx_sv      (pRExC_state->rx_sv)
230 #define RExC_rx         (pRExC_state->rx)
231 #define RExC_rxi        (pRExC_state->rxi)
232 #define RExC_start      (pRExC_state->start)
233 #define RExC_end        (pRExC_state->end)
234 #define RExC_parse      (pRExC_state->parse)
235 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
236
237 /* Set during the sizing pass when there is a LATIN SMALL LETTER SHARP S in any
238  * EXACTF node, hence was parsed under /di rules.  If later in the parse,
239  * something forces the pattern into using /ui rules, the sharp s should be
240  * folded into the sequence 'ss', which takes up more space than previously
241  * calculated.  This means that the sizing pass needs to be restarted.  (The
242  * node also becomes an EXACTFU_SS.)  For all other characters, an EXACTF node
243  * that gets converted to /ui (and EXACTFU) occupies the same amount of space,
244  * so there is no need to resize [perl #125990]. */
245 #define RExC_seen_unfolded_sharp_s (pRExC_state->seen_unfolded_sharp_s)
246
247 #ifdef RE_TRACK_PATTERN_OFFSETS
248 #define RExC_offsets    (pRExC_state->rxi->u.offsets) /* I am not like the
249                                                          others */
250 #endif
251 #define RExC_emit       (pRExC_state->emit)
252 #define RExC_emit_dummy (pRExC_state->emit_dummy)
253 #define RExC_emit_start (pRExC_state->emit_start)
254 #define RExC_emit_bound (pRExC_state->emit_bound)
255 #define RExC_sawback    (pRExC_state->sawback)
256 #define RExC_seen       (pRExC_state->seen)
257 #define RExC_size       (pRExC_state->size)
258 #define RExC_maxlen        (pRExC_state->maxlen)
259 #define RExC_npar       (pRExC_state->npar)
260 #define RExC_nestroot   (pRExC_state->nestroot)
261 #define RExC_extralen   (pRExC_state->extralen)
262 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
263 #define RExC_utf8       (pRExC_state->utf8)
264 #define RExC_uni_semantics      (pRExC_state->uni_semantics)
265 #define RExC_orig_utf8  (pRExC_state->orig_utf8)
266 #define RExC_open_parens        (pRExC_state->open_parens)
267 #define RExC_close_parens       (pRExC_state->close_parens)
268 #define RExC_opend      (pRExC_state->opend)
269 #define RExC_paren_names        (pRExC_state->paren_names)
270 #define RExC_recurse    (pRExC_state->recurse)
271 #define RExC_recurse_count      (pRExC_state->recurse_count)
272 #define RExC_study_chunk_recursed        (pRExC_state->study_chunk_recursed)
273 #define RExC_study_chunk_recursed_bytes  \
274                                    (pRExC_state->study_chunk_recursed_bytes)
275 #define RExC_in_lookbehind      (pRExC_state->in_lookbehind)
276 #define RExC_contains_locale    (pRExC_state->contains_locale)
277 #define RExC_contains_i (pRExC_state->contains_i)
278 #define RExC_override_recoding (pRExC_state->override_recoding)
279 #ifdef EBCDIC
280 #   define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
281 #endif
282 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
283 #define RExC_frame_head (pRExC_state->frame_head)
284 #define RExC_frame_last (pRExC_state->frame_last)
285 #define RExC_frame_count (pRExC_state->frame_count)
286 #define RExC_strict (pRExC_state->strict)
287
288 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
289  * a flag to disable back-off on the fixed/floating substrings - if it's
290  * a high complexity pattern we assume the benefit of avoiding a full match
291  * is worth the cost of checking for the substrings even if they rarely help.
292  */
293 #define RExC_naughty    (pRExC_state->naughty)
294 #define TOO_NAUGHTY (10)
295 #define MARK_NAUGHTY(add) \
296     if (RExC_naughty < TOO_NAUGHTY) \
297         RExC_naughty += (add)
298 #define MARK_NAUGHTY_EXP(exp, add) \
299     if (RExC_naughty < TOO_NAUGHTY) \
300         RExC_naughty += RExC_naughty / (exp) + (add)
301
302 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
303 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
304         ((*s) == '{' && regcurly(s)))
305
306 /*
307  * Flags to be passed up and down.
308  */
309 #define WORST           0       /* Worst case. */
310 #define HASWIDTH        0x01    /* Known to match non-null strings. */
311
312 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
313  * character.  (There needs to be a case: in the switch statement in regexec.c
314  * for any node marked SIMPLE.)  Note that this is not the same thing as
315  * REGNODE_SIMPLE */
316 #define SIMPLE          0x02
317 #define SPSTART         0x04    /* Starts with * or + */
318 #define POSTPONED       0x08    /* (?1),(?&name), (??{...}) or similar */
319 #define TRYAGAIN        0x10    /* Weeded out a declaration. */
320 #define RESTART_PASS1   0x20    /* Need to restart sizing pass */
321 #define NEED_UTF8       0x40    /* In conjunction with RESTART_PASS1, need to
322                                    calcuate sizes as UTF-8 */
323
324 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
325
326 /* whether trie related optimizations are enabled */
327 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
328 #define TRIE_STUDY_OPT
329 #define FULL_TRIE_STUDY
330 #define TRIE_STCLASS
331 #endif
332
333
334
335 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
336 #define PBITVAL(paren) (1 << ((paren) & 7))
337 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
338 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
339 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
340
341 #define REQUIRE_UTF8(flagp) STMT_START {                                   \
342                                      if (!UTF) {                           \
343                                          assert(PASS1);                    \
344                                          *flagp = RESTART_PASS1|NEED_UTF8; \
345                                          return NULL;                      \
346                                      }                                     \
347                              } STMT_END
348
349 /* Change from /d into /u rules, and restart the parse if we've already seen
350  * something whose size would increase as a result, by setting *flagp and
351  * returning 'restart_retval'.  RExC_uni_semantics is a flag that indicates
352  * we've change to /u during the parse.  */
353 #define REQUIRE_UNI_RULES(flagp, restart_retval)                            \
354     STMT_START {                                                            \
355             if (DEPENDS_SEMANTICS) {                                        \
356                 assert(PASS1);                                              \
357                 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);      \
358                 RExC_uni_semantics = 1;                                     \
359                 if (RExC_seen_unfolded_sharp_s) {                           \
360                     *flagp |= RESTART_PASS1;                                \
361                     return restart_retval;                                  \
362                 }                                                           \
363             }                                                               \
364     } STMT_END
365
366 /* This converts the named class defined in regcomp.h to its equivalent class
367  * number defined in handy.h. */
368 #define namedclass_to_classnum(class)  ((int) ((class) / 2))
369 #define classnum_to_namedclass(classnum)  ((classnum) * 2)
370
371 #define _invlist_union_complement_2nd(a, b, output) \
372                         _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
373 #define _invlist_intersection_complement_2nd(a, b, output) \
374                  _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
375
376 /* About scan_data_t.
377
378   During optimisation we recurse through the regexp program performing
379   various inplace (keyhole style) optimisations. In addition study_chunk
380   and scan_commit populate this data structure with information about
381   what strings MUST appear in the pattern. We look for the longest
382   string that must appear at a fixed location, and we look for the
383   longest string that may appear at a floating location. So for instance
384   in the pattern:
385
386     /FOO[xX]A.*B[xX]BAR/
387
388   Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
389   strings (because they follow a .* construct). study_chunk will identify
390   both FOO and BAR as being the longest fixed and floating strings respectively.
391
392   The strings can be composites, for instance
393
394      /(f)(o)(o)/
395
396   will result in a composite fixed substring 'foo'.
397
398   For each string some basic information is maintained:
399
400   - offset or min_offset
401     This is the position the string must appear at, or not before.
402     It also implicitly (when combined with minlenp) tells us how many
403     characters must match before the string we are searching for.
404     Likewise when combined with minlenp and the length of the string it
405     tells us how many characters must appear after the string we have
406     found.
407
408   - max_offset
409     Only used for floating strings. This is the rightmost point that
410     the string can appear at. If set to SSize_t_MAX it indicates that the
411     string can occur infinitely far to the right.
412
413   - minlenp
414     A pointer to the minimum number of characters of the pattern that the
415     string was found inside. This is important as in the case of positive
416     lookahead or positive lookbehind we can have multiple patterns
417     involved. Consider
418
419     /(?=FOO).*F/
420
421     The minimum length of the pattern overall is 3, the minimum length
422     of the lookahead part is 3, but the minimum length of the part that
423     will actually match is 1. So 'FOO's minimum length is 3, but the
424     minimum length for the F is 1. This is important as the minimum length
425     is used to determine offsets in front of and behind the string being
426     looked for.  Since strings can be composites this is the length of the
427     pattern at the time it was committed with a scan_commit. Note that
428     the length is calculated by study_chunk, so that the minimum lengths
429     are not known until the full pattern has been compiled, thus the
430     pointer to the value.
431
432   - lookbehind
433
434     In the case of lookbehind the string being searched for can be
435     offset past the start point of the final matching string.
436     If this value was just blithely removed from the min_offset it would
437     invalidate some of the calculations for how many chars must match
438     before or after (as they are derived from min_offset and minlen and
439     the length of the string being searched for).
440     When the final pattern is compiled and the data is moved from the
441     scan_data_t structure into the regexp structure the information
442     about lookbehind is factored in, with the information that would
443     have been lost precalculated in the end_shift field for the
444     associated string.
445
446   The fields pos_min and pos_delta are used to store the minimum offset
447   and the delta to the maximum offset at the current point in the pattern.
448
449 */
450
451 typedef struct scan_data_t {
452     /*I32 len_min;      unused */
453     /*I32 len_delta;    unused */
454     SSize_t pos_min;
455     SSize_t pos_delta;
456     SV *last_found;
457     SSize_t last_end;       /* min value, <0 unless valid. */
458     SSize_t last_start_min;
459     SSize_t last_start_max;
460     SV **longest;           /* Either &l_fixed, or &l_float. */
461     SV *longest_fixed;      /* longest fixed string found in pattern */
462     SSize_t offset_fixed;   /* offset where it starts */
463     SSize_t *minlen_fixed;  /* pointer to the minlen relevant to the string */
464     I32 lookbehind_fixed;   /* is the position of the string modfied by LB */
465     SV *longest_float;      /* longest floating string found in pattern */
466     SSize_t offset_float_min; /* earliest point in string it can appear */
467     SSize_t offset_float_max; /* latest point in string it can appear */
468     SSize_t *minlen_float;  /* pointer to the minlen relevant to the string */
469     SSize_t lookbehind_float; /* is the pos of the string modified by LB */
470     I32 flags;
471     I32 whilem_c;
472     SSize_t *last_closep;
473     regnode_ssc *start_class;
474 } scan_data_t;
475
476 /*
477  * Forward declarations for pregcomp()'s friends.
478  */
479
480 static const scan_data_t zero_scan_data =
481   { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
482
483 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
484 #define SF_BEFORE_SEOL          0x0001
485 #define SF_BEFORE_MEOL          0x0002
486 #define SF_FIX_BEFORE_EOL       (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
487 #define SF_FL_BEFORE_EOL        (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
488
489 #define SF_FIX_SHIFT_EOL        (+2)
490 #define SF_FL_SHIFT_EOL         (+4)
491
492 #define SF_FIX_BEFORE_SEOL      (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
493 #define SF_FIX_BEFORE_MEOL      (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
494
495 #define SF_FL_BEFORE_SEOL       (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
496 #define SF_FL_BEFORE_MEOL       (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
497 #define SF_IS_INF               0x0040
498 #define SF_HAS_PAR              0x0080
499 #define SF_IN_PAR               0x0100
500 #define SF_HAS_EVAL             0x0200
501 #define SCF_DO_SUBSTR           0x0400
502 #define SCF_DO_STCLASS_AND      0x0800
503 #define SCF_DO_STCLASS_OR       0x1000
504 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
505 #define SCF_WHILEM_VISITED_POS  0x2000
506
507 #define SCF_TRIE_RESTUDY        0x4000 /* Do restudy? */
508 #define SCF_SEEN_ACCEPT         0x8000
509 #define SCF_TRIE_DOING_RESTUDY 0x10000
510 #define SCF_IN_DEFINE          0x20000
511
512
513
514
515 #define UTF cBOOL(RExC_utf8)
516
517 /* The enums for all these are ordered so things work out correctly */
518 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
519 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags)                    \
520                                                      == REGEX_DEPENDS_CHARSET)
521 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
522 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags)                \
523                                                      >= REGEX_UNICODE_CHARSET)
524 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags)                      \
525                                             == REGEX_ASCII_RESTRICTED_CHARSET)
526 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags)             \
527                                             >= REGEX_ASCII_RESTRICTED_CHARSET)
528 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags)                 \
529                                         == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
530
531 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
532
533 /* For programs that want to be strictly Unicode compatible by dying if any
534  * attempt is made to match a non-Unicode code point against a Unicode
535  * property.  */
536 #define ALWAYS_WARN_SUPER  ckDEAD(packWARN(WARN_NON_UNICODE))
537
538 #define OOB_NAMEDCLASS          -1
539
540 /* There is no code point that is out-of-bounds, so this is problematic.  But
541  * its only current use is to initialize a variable that is always set before
542  * looked at. */
543 #define OOB_UNICODE             0xDEADBEEF
544
545 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
546 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
547
548
549 /* length of regex to show in messages that don't mark a position within */
550 #define RegexLengthToShowInErrorMessages 127
551
552 /*
553  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
554  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
555  * op/pragma/warn/regcomp.
556  */
557 #define MARKER1 "<-- HERE"    /* marker as it appears in the description */
558 #define MARKER2 " <-- HERE "  /* marker as it appears within the regex */
559
560 #define REPORT_LOCATION " in regex; marked by " MARKER1    \
561                         " in m/%"UTF8f MARKER2 "%"UTF8f"/"
562
563 /* The code in this file in places uses one level of recursion with parsing
564  * rebased to an alternate string constructed by us in memory.  This can take
565  * the form of something that is completely different from the input, or
566  * something that uses the input as part of the alternate.  In the first case,
567  * there should be no possibility of an error, as we are in complete control of
568  * the alternate string.  But in the second case we don't control the input
569  * portion, so there may be errors in that.  Here's an example:
570  *      /[abc\x{DF}def]/ui
571  * is handled specially because \x{df} folds to a sequence of more than one
572  * character, 'ss'.  What is done is to create and parse an alternate string,
573  * which looks like this:
574  *      /(?:\x{DF}|[abc\x{DF}def])/ui
575  * where it uses the input unchanged in the middle of something it constructs,
576  * which is a branch for the DF outside the character class, and clustering
577  * parens around the whole thing. (It knows enough to skip the DF inside the
578  * class while in this substitute parse.) 'abc' and 'def' may have errors that
579  * need to be reported.  The general situation looks like this:
580  *
581  *              sI                       tI               xI       eI
582  * Input:       ----------------------------------------------------
583  * Constructed:         ---------------------------------------------------
584  *                      sC               tC               xC       eC     EC
585  *
586  * The input string sI..eI is the input pattern.  The string sC..EC is the
587  * constructed substitute parse string.  The portions sC..tC and eC..EC are
588  * constructed by us.  The portion tC..eC is an exact duplicate of the input
589  * pattern tI..eI.  In the diagram, these are vertically aligned.  Suppose that
590  * while parsing, we find an error at xC.  We want to display a message showing
591  * the real input string.  Thus we need to find the point xI in it which
592  * corresponds to xC.  xC >= tC, since the portion of the string sC..tC has
593  * been constructed by us, and so shouldn't have errors.  We get:
594  *
595  *      xI = sI + (tI - sI) + (xC - tC)
596  *
597  * and, the offset into sI is:
598  *
599  *      (xI - sI) = (tI - sI) + (xC - tC)
600  *
601  * When the substitute is constructed, we save (tI -sI) as RExC_precomp_adj,
602  * and we save tC as RExC_adjusted_start.
603  *
604  * During normal processing of the input pattern, everything points to that,
605  * with RExC_precomp_adj set to 0, and RExC_adjusted_start set to sI.
606  */
607
608 #define tI_sI           RExC_precomp_adj
609 #define tC              RExC_adjusted_start
610 #define sC              RExC_precomp
611 #define xI_offset(xC)   ((IV) (tI_sI + (xC - tC)))
612 #define xI(xC)          (sC + xI_offset(xC))
613 #define eC              RExC_precomp_end
614
615 #define REPORT_LOCATION_ARGS(xC)                                            \
616     UTF8fARG(UTF,                                                           \
617              (xI(xC) > eC) /* Don't run off end */                          \
618               ? eC - sC   /* Length before the <--HERE */                   \
619               : xI_offset(xC),                                              \
620              sC),         /* The input pattern printed up to the <--HERE */ \
621     UTF8fARG(UTF,                                                           \
622              (xI(xC) > eC) ? 0 : eC - xI(xC), /* Length after <--HERE */    \
623              (xI(xC) > eC) ? eC : xI(xC))     /* pattern after <--HERE */
624
625 /* Used to point after bad bytes for an error message, but avoid skipping
626  * past a nul byte. */
627 #define SKIP_IF_CHAR(s) (!*(s) ? 0 : UTF ? UTF8SKIP(s) : 1)
628
629 /*
630  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
631  * arg. Show regex, up to a maximum length. If it's too long, chop and add
632  * "...".
633  */
634 #define _FAIL(code) STMT_START {                                        \
635     const char *ellipses = "";                                          \
636     IV len = RExC_precomp_end - RExC_precomp;                                   \
637                                                                         \
638     if (!SIZE_ONLY)                                                     \
639         SAVEFREESV(RExC_rx_sv);                                         \
640     if (len > RegexLengthToShowInErrorMessages) {                       \
641         /* chop 10 shorter than the max, to ensure meaning of "..." */  \
642         len = RegexLengthToShowInErrorMessages - 10;                    \
643         ellipses = "...";                                               \
644     }                                                                   \
645     code;                                                               \
646 } STMT_END
647
648 #define FAIL(msg) _FAIL(                            \
649     Perl_croak(aTHX_ "%s in regex m/%"UTF8f"%s/",           \
650             msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
651
652 #define FAIL2(msg,arg) _FAIL(                       \
653     Perl_croak(aTHX_ msg " in regex m/%"UTF8f"%s/",         \
654             arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
655
656 /*
657  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
658  */
659 #define Simple_vFAIL(m) STMT_START {                                    \
660     Perl_croak(aTHX_ "%s" REPORT_LOCATION,                              \
661             m, REPORT_LOCATION_ARGS(RExC_parse));                       \
662 } STMT_END
663
664 /*
665  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
666  */
667 #define vFAIL(m) STMT_START {                           \
668     if (!SIZE_ONLY)                                     \
669         SAVEFREESV(RExC_rx_sv);                         \
670     Simple_vFAIL(m);                                    \
671 } STMT_END
672
673 /*
674  * Like Simple_vFAIL(), but accepts two arguments.
675  */
676 #define Simple_vFAIL2(m,a1) STMT_START {                        \
677     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1,              \
678                       REPORT_LOCATION_ARGS(RExC_parse));        \
679 } STMT_END
680
681 /*
682  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
683  */
684 #define vFAIL2(m,a1) STMT_START {                       \
685     if (!SIZE_ONLY)                                     \
686         SAVEFREESV(RExC_rx_sv);                         \
687     Simple_vFAIL2(m, a1);                               \
688 } STMT_END
689
690
691 /*
692  * Like Simple_vFAIL(), but accepts three arguments.
693  */
694 #define Simple_vFAIL3(m, a1, a2) STMT_START {                   \
695     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2,          \
696             REPORT_LOCATION_ARGS(RExC_parse));                  \
697 } STMT_END
698
699 /*
700  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
701  */
702 #define vFAIL3(m,a1,a2) STMT_START {                    \
703     if (!SIZE_ONLY)                                     \
704         SAVEFREESV(RExC_rx_sv);                         \
705     Simple_vFAIL3(m, a1, a2);                           \
706 } STMT_END
707
708 /*
709  * Like Simple_vFAIL(), but accepts four arguments.
710  */
711 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START {               \
712     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3,      \
713             REPORT_LOCATION_ARGS(RExC_parse));                  \
714 } STMT_END
715
716 #define vFAIL4(m,a1,a2,a3) STMT_START {                 \
717     if (!SIZE_ONLY)                                     \
718         SAVEFREESV(RExC_rx_sv);                         \
719     Simple_vFAIL4(m, a1, a2, a3);                       \
720 } STMT_END
721
722 /* A specialized version of vFAIL2 that works with UTF8f */
723 #define vFAIL2utf8f(m, a1) STMT_START {             \
724     if (!SIZE_ONLY)                                 \
725         SAVEFREESV(RExC_rx_sv);                     \
726     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1,  \
727             REPORT_LOCATION_ARGS(RExC_parse));      \
728 } STMT_END
729
730 #define vFAIL3utf8f(m, a1, a2) STMT_START {             \
731     if (!SIZE_ONLY)                                     \
732         SAVEFREESV(RExC_rx_sv);                         \
733     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2,  \
734             REPORT_LOCATION_ARGS(RExC_parse));          \
735 } STMT_END
736
737 /* These have asserts in them because of [perl #122671] Many warnings in
738  * regcomp.c can occur twice.  If they get output in pass1 and later in that
739  * pass, the pattern has to be converted to UTF-8 and the pass restarted, they
740  * would get output again.  So they should be output in pass2, and these
741  * asserts make sure new warnings follow that paradigm. */
742
743 /* m is not necessarily a "literal string", in this macro */
744 #define reg_warn_non_literal_string(loc, m) STMT_START {                \
745     __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP),           \
746                                        "%s" REPORT_LOCATION,            \
747                                   m, REPORT_LOCATION_ARGS(loc));        \
748 } STMT_END
749
750 #define ckWARNreg(loc,m) STMT_START {                                   \
751     __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),        \
752                                           m REPORT_LOCATION,            \
753                                           REPORT_LOCATION_ARGS(loc));   \
754 } STMT_END
755
756 #define vWARN(loc, m) STMT_START {                                      \
757     __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP),           \
758                                        m REPORT_LOCATION,               \
759                                        REPORT_LOCATION_ARGS(loc));      \
760 } STMT_END
761
762 #define vWARN_dep(loc, m) STMT_START {                                  \
763     __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),       \
764                                        m REPORT_LOCATION,               \
765                                        REPORT_LOCATION_ARGS(loc));      \
766 } STMT_END
767
768 #define ckWARNdep(loc,m) STMT_START {                                   \
769     __ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),  \
770                                             m REPORT_LOCATION,          \
771                                             REPORT_LOCATION_ARGS(loc)); \
772 } STMT_END
773
774 #define ckWARNregdep(loc,m) STMT_START {                                    \
775     __ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED,      \
776                                                       WARN_REGEXP),         \
777                                              m REPORT_LOCATION,             \
778                                              REPORT_LOCATION_ARGS(loc));    \
779 } STMT_END
780
781 #define ckWARN2reg_d(loc,m, a1) STMT_START {                                \
782     __ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP),          \
783                                             m REPORT_LOCATION,              \
784                                             a1, REPORT_LOCATION_ARGS(loc)); \
785 } STMT_END
786
787 #define ckWARN2reg(loc, m, a1) STMT_START {                                 \
788     __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),            \
789                                           m REPORT_LOCATION,                \
790                                           a1, REPORT_LOCATION_ARGS(loc));   \
791 } STMT_END
792
793 #define vWARN3(loc, m, a1, a2) STMT_START {                                 \
794     __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP),               \
795                                        m REPORT_LOCATION,                   \
796                                        a1, a2, REPORT_LOCATION_ARGS(loc));  \
797 } STMT_END
798
799 #define ckWARN3reg(loc, m, a1, a2) STMT_START {                             \
800     __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),            \
801                                           m REPORT_LOCATION,                \
802                                           a1, a2,                           \
803                                           REPORT_LOCATION_ARGS(loc));       \
804 } STMT_END
805
806 #define vWARN4(loc, m, a1, a2, a3) STMT_START {                         \
807     __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP),           \
808                                        m REPORT_LOCATION,               \
809                                        a1, a2, a3,                      \
810                                        REPORT_LOCATION_ARGS(loc));      \
811 } STMT_END
812
813 #define ckWARN4reg(loc, m, a1, a2, a3) STMT_START {                     \
814     __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),        \
815                                           m REPORT_LOCATION,            \
816                                           a1, a2, a3,                   \
817                                           REPORT_LOCATION_ARGS(loc));   \
818 } STMT_END
819
820 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START {                     \
821     __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP),           \
822                                        m REPORT_LOCATION,               \
823                                        a1, a2, a3, a4,                  \
824                                        REPORT_LOCATION_ARGS(loc));      \
825 } STMT_END
826
827 /* Macros for recording node offsets.   20001227 mjd@plover.com
828  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
829  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
830  * Element 0 holds the number n.
831  * Position is 1 indexed.
832  */
833 #ifndef RE_TRACK_PATTERN_OFFSETS
834 #define Set_Node_Offset_To_R(node,byte)
835 #define Set_Node_Offset(node,byte)
836 #define Set_Cur_Node_Offset
837 #define Set_Node_Length_To_R(node,len)
838 #define Set_Node_Length(node,len)
839 #define Set_Node_Cur_Length(node,start)
840 #define Node_Offset(n)
841 #define Node_Length(n)
842 #define Set_Node_Offset_Length(node,offset,len)
843 #define ProgLen(ri) ri->u.proglen
844 #define SetProgLen(ri,x) ri->u.proglen = x
845 #else
846 #define ProgLen(ri) ri->u.offsets[0]
847 #define SetProgLen(ri,x) ri->u.offsets[0] = x
848 #define Set_Node_Offset_To_R(node,byte) STMT_START {                    \
849     if (! SIZE_ONLY) {                                                  \
850         MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n",         \
851                     __LINE__, (int)(node), (int)(byte)));               \
852         if((node) < 0) {                                                \
853             Perl_croak(aTHX_ "value of node is %d in Offset macro",     \
854                                          (int)(node));                  \
855         } else {                                                        \
856             RExC_offsets[2*(node)-1] = (byte);                          \
857         }                                                               \
858     }                                                                   \
859 } STMT_END
860
861 #define Set_Node_Offset(node,byte) \
862     Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
863 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
864
865 #define Set_Node_Length_To_R(node,len) STMT_START {                     \
866     if (! SIZE_ONLY) {                                                  \
867         MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n",           \
868                 __LINE__, (int)(node), (int)(len)));                    \
869         if((node) < 0) {                                                \
870             Perl_croak(aTHX_ "value of node is %d in Length macro",     \
871                                          (int)(node));                  \
872         } else {                                                        \
873             RExC_offsets[2*(node)] = (len);                             \
874         }                                                               \
875     }                                                                   \
876 } STMT_END
877
878 #define Set_Node_Length(node,len) \
879     Set_Node_Length_To_R((node)-RExC_emit_start, len)
880 #define Set_Node_Cur_Length(node, start)                \
881     Set_Node_Length(node, RExC_parse - start)
882
883 /* Get offsets and lengths */
884 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
885 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
886
887 #define Set_Node_Offset_Length(node,offset,len) STMT_START {    \
888     Set_Node_Offset_To_R((node)-RExC_emit_start, (offset));     \
889     Set_Node_Length_To_R((node)-RExC_emit_start, (len));        \
890 } STMT_END
891 #endif
892
893 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
894 #define EXPERIMENTAL_INPLACESCAN
895 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
896
897 #define DEBUG_RExC_seen() \
898         DEBUG_OPTIMISE_MORE_r({                                             \
899             PerlIO_printf(Perl_debug_log,"RExC_seen: ");                    \
900                                                                             \
901             if (RExC_seen & REG_ZERO_LEN_SEEN)                              \
902                 PerlIO_printf(Perl_debug_log,"REG_ZERO_LEN_SEEN ");         \
903                                                                             \
904             if (RExC_seen & REG_LOOKBEHIND_SEEN)                            \
905                 PerlIO_printf(Perl_debug_log,"REG_LOOKBEHIND_SEEN ");       \
906                                                                             \
907             if (RExC_seen & REG_GPOS_SEEN)                                  \
908                 PerlIO_printf(Perl_debug_log,"REG_GPOS_SEEN ");             \
909                                                                             \
910             if (RExC_seen & REG_RECURSE_SEEN)                               \
911                 PerlIO_printf(Perl_debug_log,"REG_RECURSE_SEEN ");          \
912                                                                             \
913             if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)                         \
914                 PerlIO_printf(Perl_debug_log,"REG_TOP_LEVEL_BRANCHES_SEEN ");    \
915                                                                             \
916             if (RExC_seen & REG_VERBARG_SEEN)                               \
917                 PerlIO_printf(Perl_debug_log,"REG_VERBARG_SEEN ");          \
918                                                                             \
919             if (RExC_seen & REG_CUTGROUP_SEEN)                              \
920                 PerlIO_printf(Perl_debug_log,"REG_CUTGROUP_SEEN ");         \
921                                                                             \
922             if (RExC_seen & REG_RUN_ON_COMMENT_SEEN)                        \
923                 PerlIO_printf(Perl_debug_log,"REG_RUN_ON_COMMENT_SEEN ");   \
924                                                                             \
925             if (RExC_seen & REG_UNFOLDED_MULTI_SEEN)                        \
926                 PerlIO_printf(Perl_debug_log,"REG_UNFOLDED_MULTI_SEEN ");   \
927                                                                             \
928             if (RExC_seen & REG_GOSTART_SEEN)                               \
929                 PerlIO_printf(Perl_debug_log,"REG_GOSTART_SEEN ");          \
930                                                                             \
931             if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)                               \
932                 PerlIO_printf(Perl_debug_log,"REG_UNBOUNDED_QUANTIFIER_SEEN ");          \
933                                                                             \
934             PerlIO_printf(Perl_debug_log,"\n");                             \
935         });
936
937 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
938   if ((flags) & flag) PerlIO_printf(Perl_debug_log, "%s ", #flag)
939
940 #define DEBUG_SHOW_STUDY_FLAGS(flags,open_str,close_str)                    \
941     if ( ( flags ) ) {                                                      \
942         PerlIO_printf(Perl_debug_log, "%s", open_str);                      \
943         DEBUG_SHOW_STUDY_FLAG(flags,SF_FL_BEFORE_SEOL);                     \
944         DEBUG_SHOW_STUDY_FLAG(flags,SF_FL_BEFORE_MEOL);                     \
945         DEBUG_SHOW_STUDY_FLAG(flags,SF_IS_INF);                             \
946         DEBUG_SHOW_STUDY_FLAG(flags,SF_HAS_PAR);                            \
947         DEBUG_SHOW_STUDY_FLAG(flags,SF_IN_PAR);                             \
948         DEBUG_SHOW_STUDY_FLAG(flags,SF_HAS_EVAL);                           \
949         DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_SUBSTR);                         \
950         DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_STCLASS_AND);                    \
951         DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_STCLASS_OR);                     \
952         DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_STCLASS);                        \
953         DEBUG_SHOW_STUDY_FLAG(flags,SCF_WHILEM_VISITED_POS);                \
954         DEBUG_SHOW_STUDY_FLAG(flags,SCF_TRIE_RESTUDY);                      \
955         DEBUG_SHOW_STUDY_FLAG(flags,SCF_SEEN_ACCEPT);                       \
956         DEBUG_SHOW_STUDY_FLAG(flags,SCF_TRIE_DOING_RESTUDY);                \
957         DEBUG_SHOW_STUDY_FLAG(flags,SCF_IN_DEFINE);                         \
958         PerlIO_printf(Perl_debug_log, "%s", close_str);                     \
959     }
960
961
962 #define DEBUG_STUDYDATA(str,data,depth)                              \
963 DEBUG_OPTIMISE_MORE_r(if(data){                                      \
964     PerlIO_printf(Perl_debug_log,                                    \
965         "%*s" str "Pos:%"IVdf"/%"IVdf                                \
966         " Flags: 0x%"UVXf,                                           \
967         (int)(depth)*2, "",                                          \
968         (IV)((data)->pos_min),                                       \
969         (IV)((data)->pos_delta),                                     \
970         (UV)((data)->flags)                                          \
971     );                                                               \
972     DEBUG_SHOW_STUDY_FLAGS((data)->flags," [ ","]");                 \
973     PerlIO_printf(Perl_debug_log,                                    \
974         " Whilem_c: %"IVdf" Lcp: %"IVdf" %s",                        \
975         (IV)((data)->whilem_c),                                      \
976         (IV)((data)->last_closep ? *((data)->last_closep) : -1),     \
977         is_inf ? "INF " : ""                                         \
978     );                                                               \
979     if ((data)->last_found)                                          \
980         PerlIO_printf(Perl_debug_log,                                \
981             "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
982             " %sFloat: '%s' @ %"IVdf"/%"IVdf"",                      \
983             SvPVX_const((data)->last_found),                         \
984             (IV)((data)->last_end),                                  \
985             (IV)((data)->last_start_min),                            \
986             (IV)((data)->last_start_max),                            \
987             ((data)->longest &&                                      \
988              (data)->longest==&((data)->longest_fixed)) ? "*" : "",  \
989             SvPVX_const((data)->longest_fixed),                      \
990             (IV)((data)->offset_fixed),                              \
991             ((data)->longest &&                                      \
992              (data)->longest==&((data)->longest_float)) ? "*" : "",  \
993             SvPVX_const((data)->longest_float),                      \
994             (IV)((data)->offset_float_min),                          \
995             (IV)((data)->offset_float_max)                           \
996         );                                                           \
997     PerlIO_printf(Perl_debug_log,"\n");                              \
998 });
999
1000 /* =========================================================
1001  * BEGIN edit_distance stuff.
1002  *
1003  * This calculates how many single character changes of any type are needed to
1004  * transform a string into another one.  It is taken from version 3.1 of
1005  *
1006  * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1007  */
1008
1009 /* Our unsorted dictionary linked list.   */
1010 /* Note we use UVs, not chars. */
1011
1012 struct dictionary{
1013   UV key;
1014   UV value;
1015   struct dictionary* next;
1016 };
1017 typedef struct dictionary item;
1018
1019
1020 PERL_STATIC_INLINE item*
1021 push(UV key,item* curr)
1022 {
1023     item* head;
1024     Newxz(head, 1, item);
1025     head->key = key;
1026     head->value = 0;
1027     head->next = curr;
1028     return head;
1029 }
1030
1031
1032 PERL_STATIC_INLINE item*
1033 find(item* head, UV key)
1034 {
1035     item* iterator = head;
1036     while (iterator){
1037         if (iterator->key == key){
1038             return iterator;
1039         }
1040         iterator = iterator->next;
1041     }
1042
1043     return NULL;
1044 }
1045
1046 PERL_STATIC_INLINE item*
1047 uniquePush(item* head,UV key)
1048 {
1049     item* iterator = head;
1050
1051     while (iterator){
1052         if (iterator->key == key) {
1053             return head;
1054         }
1055         iterator = iterator->next;
1056     }
1057
1058     return push(key,head);
1059 }
1060
1061 PERL_STATIC_INLINE void
1062 dict_free(item* head)
1063 {
1064     item* iterator = head;
1065
1066     while (iterator) {
1067         item* temp = iterator;
1068         iterator = iterator->next;
1069         Safefree(temp);
1070     }
1071
1072     head = NULL;
1073 }
1074
1075 /* End of Dictionary Stuff */
1076
1077 /* All calculations/work are done here */
1078 STATIC int
1079 S_edit_distance(const UV* src,
1080                 const UV* tgt,
1081                 const STRLEN x,             /* length of src[] */
1082                 const STRLEN y,             /* length of tgt[] */
1083                 const SSize_t maxDistance
1084 )
1085 {
1086     item *head = NULL;
1087     UV swapCount,swapScore,targetCharCount,i,j;
1088     UV *scores;
1089     UV score_ceil = x + y;
1090
1091     PERL_ARGS_ASSERT_EDIT_DISTANCE;
1092
1093     /* intialize matrix start values */
1094     Newxz(scores, ( (x + 2) * (y + 2)), UV);
1095     scores[0] = score_ceil;
1096     scores[1 * (y + 2) + 0] = score_ceil;
1097     scores[0 * (y + 2) + 1] = score_ceil;
1098     scores[1 * (y + 2) + 1] = 0;
1099     head = uniquePush(uniquePush(head,src[0]),tgt[0]);
1100
1101     /* work loops    */
1102     /* i = src index */
1103     /* j = tgt index */
1104     for (i=1;i<=x;i++) {
1105         if (i < x)
1106             head = uniquePush(head,src[i]);
1107         scores[(i+1) * (y + 2) + 1] = i;
1108         scores[(i+1) * (y + 2) + 0] = score_ceil;
1109         swapCount = 0;
1110
1111         for (j=1;j<=y;j++) {
1112             if (i == 1) {
1113                 if(j < y)
1114                 head = uniquePush(head,tgt[j]);
1115                 scores[1 * (y + 2) + (j + 1)] = j;
1116                 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1117             }
1118
1119             targetCharCount = find(head,tgt[j-1])->value;
1120             swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1121
1122             if (src[i-1] != tgt[j-1]){
1123                 scores[(i+1) * (y + 2) + (j + 1)] = MIN(swapScore,(MIN(scores[i * (y + 2) + j], MIN(scores[(i+1) * (y + 2) + j], scores[i * (y + 2) + (j + 1)])) + 1));
1124             }
1125             else {
1126                 swapCount = j;
1127                 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1128             }
1129         }
1130
1131         find(head,src[i-1])->value = i;
1132     }
1133
1134     {
1135         IV score = scores[(x+1) * (y + 2) + (y + 1)];
1136         dict_free(head);
1137         Safefree(scores);
1138         return (maxDistance != 0 && maxDistance < score)?(-1):score;
1139     }
1140 }
1141
1142 /* END of edit_distance() stuff
1143  * ========================================================= */
1144
1145 /* is c a control character for which we have a mnemonic? */
1146 #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
1147
1148 STATIC const char *
1149 S_cntrl_to_mnemonic(const U8 c)
1150 {
1151     /* Returns the mnemonic string that represents character 'c', if one
1152      * exists; NULL otherwise.  The only ones that exist for the purposes of
1153      * this routine are a few control characters */
1154
1155     switch (c) {
1156         case '\a':       return "\\a";
1157         case '\b':       return "\\b";
1158         case ESC_NATIVE: return "\\e";
1159         case '\f':       return "\\f";
1160         case '\n':       return "\\n";
1161         case '\r':       return "\\r";
1162         case '\t':       return "\\t";
1163     }
1164
1165     return NULL;
1166 }
1167
1168 /* Mark that we cannot extend a found fixed substring at this point.
1169    Update the longest found anchored substring and the longest found
1170    floating substrings if needed. */
1171
1172 STATIC void
1173 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1174                     SSize_t *minlenp, int is_inf)
1175 {
1176     const STRLEN l = CHR_SVLEN(data->last_found);
1177     const STRLEN old_l = CHR_SVLEN(*data->longest);
1178     GET_RE_DEBUG_FLAGS_DECL;
1179
1180     PERL_ARGS_ASSERT_SCAN_COMMIT;
1181
1182     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1183         SvSetMagicSV(*data->longest, data->last_found);
1184         if (*data->longest == data->longest_fixed) {
1185             data->offset_fixed = l ? data->last_start_min : data->pos_min;
1186             if (data->flags & SF_BEFORE_EOL)
1187                 data->flags
1188                     |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
1189             else
1190                 data->flags &= ~SF_FIX_BEFORE_EOL;
1191             data->minlen_fixed=minlenp;
1192             data->lookbehind_fixed=0;
1193         }
1194         else { /* *data->longest == data->longest_float */
1195             data->offset_float_min = l ? data->last_start_min : data->pos_min;
1196             data->offset_float_max = (l
1197                           ? data->last_start_max
1198                           : (data->pos_delta > SSize_t_MAX - data->pos_min
1199                                          ? SSize_t_MAX
1200                                          : data->pos_min + data->pos_delta));
1201             if (is_inf
1202                  || (STRLEN)data->offset_float_max > (STRLEN)SSize_t_MAX)
1203                 data->offset_float_max = SSize_t_MAX;
1204             if (data->flags & SF_BEFORE_EOL)
1205                 data->flags
1206                     |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
1207             else
1208                 data->flags &= ~SF_FL_BEFORE_EOL;
1209             data->minlen_float=minlenp;
1210             data->lookbehind_float=0;
1211         }
1212     }
1213     SvCUR_set(data->last_found, 0);
1214     {
1215         SV * const sv = data->last_found;
1216         if (SvUTF8(sv) && SvMAGICAL(sv)) {
1217             MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1218             if (mg)
1219                 mg->mg_len = 0;
1220         }
1221     }
1222     data->last_end = -1;
1223     data->flags &= ~SF_BEFORE_EOL;
1224     DEBUG_STUDYDATA("commit: ",data,0);
1225 }
1226
1227 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1228  * list that describes which code points it matches */
1229
1230 STATIC void
1231 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1232 {
1233     /* Set the SSC 'ssc' to match an empty string or any code point */
1234
1235     PERL_ARGS_ASSERT_SSC_ANYTHING;
1236
1237     assert(is_ANYOF_SYNTHETIC(ssc));
1238
1239     ssc->invlist = sv_2mortal(_new_invlist(2)); /* mortalize so won't leak */
1240     _append_range_to_invlist(ssc->invlist, 0, UV_MAX);
1241     ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING;  /* Plus matches empty */
1242 }
1243
1244 STATIC int
1245 S_ssc_is_anything(const regnode_ssc *ssc)
1246 {
1247     /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1248      * point; FALSE otherwise.  Thus, this is used to see if using 'ssc' buys
1249      * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1250      * in any way, so there's no point in using it */
1251
1252     UV start, end;
1253     bool ret;
1254
1255     PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1256
1257     assert(is_ANYOF_SYNTHETIC(ssc));
1258
1259     if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1260         return FALSE;
1261     }
1262
1263     /* See if the list consists solely of the range 0 - Infinity */
1264     invlist_iterinit(ssc->invlist);
1265     ret = invlist_iternext(ssc->invlist, &start, &end)
1266           && start == 0
1267           && end == UV_MAX;
1268
1269     invlist_iterfinish(ssc->invlist);
1270
1271     if (ret) {
1272         return TRUE;
1273     }
1274
1275     /* If e.g., both \w and \W are set, matches everything */
1276     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1277         int i;
1278         for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1279             if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1280                 return TRUE;
1281             }
1282         }
1283     }
1284
1285     return FALSE;
1286 }
1287
1288 STATIC void
1289 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1290 {
1291     /* Initializes the SSC 'ssc'.  This includes setting it to match an empty
1292      * string, any code point, or any posix class under locale */
1293
1294     PERL_ARGS_ASSERT_SSC_INIT;
1295
1296     Zero(ssc, 1, regnode_ssc);
1297     set_ANYOF_SYNTHETIC(ssc);
1298     ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1299     ssc_anything(ssc);
1300
1301     /* If any portion of the regex is to operate under locale rules that aren't
1302      * fully known at compile time, initialization includes it.  The reason
1303      * this isn't done for all regexes is that the optimizer was written under
1304      * the assumption that locale was all-or-nothing.  Given the complexity and
1305      * lack of documentation in the optimizer, and that there are inadequate
1306      * test cases for locale, many parts of it may not work properly, it is
1307      * safest to avoid locale unless necessary. */
1308     if (RExC_contains_locale) {
1309         ANYOF_POSIXL_SETALL(ssc);
1310     }
1311     else {
1312         ANYOF_POSIXL_ZERO(ssc);
1313     }
1314 }
1315
1316 STATIC int
1317 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1318                         const regnode_ssc *ssc)
1319 {
1320     /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1321      * to the list of code points matched, and locale posix classes; hence does
1322      * not check its flags) */
1323
1324     UV start, end;
1325     bool ret;
1326
1327     PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1328
1329     assert(is_ANYOF_SYNTHETIC(ssc));
1330
1331     invlist_iterinit(ssc->invlist);
1332     ret = invlist_iternext(ssc->invlist, &start, &end)
1333           && start == 0
1334           && end == UV_MAX;
1335
1336     invlist_iterfinish(ssc->invlist);
1337
1338     if (! ret) {
1339         return FALSE;
1340     }
1341
1342     if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1343         return FALSE;
1344     }
1345
1346     return TRUE;
1347 }
1348
1349 STATIC SV*
1350 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1351                                const regnode_charclass* const node)
1352 {
1353     /* Returns a mortal inversion list defining which code points are matched
1354      * by 'node', which is of type ANYOF.  Handles complementing the result if
1355      * appropriate.  If some code points aren't knowable at this time, the
1356      * returned list must, and will, contain every code point that is a
1357      * possibility. */
1358
1359     SV* invlist = sv_2mortal(_new_invlist(0));
1360     SV* only_utf8_locale_invlist = NULL;
1361     unsigned int i;
1362     const U32 n = ARG(node);
1363     bool new_node_has_latin1 = FALSE;
1364
1365     PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1366
1367     /* Look at the data structure created by S_set_ANYOF_arg() */
1368     if (n != ANYOF_ONLY_HAS_BITMAP) {
1369         SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1370         AV * const av = MUTABLE_AV(SvRV(rv));
1371         SV **const ary = AvARRAY(av);
1372         assert(RExC_rxi->data->what[n] == 's');
1373
1374         if (ary[1] && ary[1] != &PL_sv_undef) { /* Has compile-time swash */
1375             invlist = sv_2mortal(invlist_clone(_get_swash_invlist(ary[1])));
1376         }
1377         else if (ary[0] && ary[0] != &PL_sv_undef) {
1378
1379             /* Here, no compile-time swash, and there are things that won't be
1380              * known until runtime -- we have to assume it could be anything */
1381             return _add_range_to_invlist(invlist, 0, UV_MAX);
1382         }
1383         else if (ary[3] && ary[3] != &PL_sv_undef) {
1384
1385             /* Here no compile-time swash, and no run-time only data.  Use the
1386              * node's inversion list */
1387             invlist = sv_2mortal(invlist_clone(ary[3]));
1388         }
1389
1390         /* Get the code points valid only under UTF-8 locales */
1391         if ((ANYOF_FLAGS(node) & ANYOFL_FOLD)
1392             && ary[2] && ary[2] != &PL_sv_undef)
1393         {
1394             only_utf8_locale_invlist = ary[2];
1395         }
1396     }
1397
1398     /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1399      * code points, and an inversion list for the others, but if there are code
1400      * points that should match only conditionally on the target string being
1401      * UTF-8, those are placed in the inversion list, and not the bitmap.
1402      * Since there are circumstances under which they could match, they are
1403      * included in the SSC.  But if the ANYOF node is to be inverted, we have
1404      * to exclude them here, so that when we invert below, the end result
1405      * actually does include them.  (Think about "\xe0" =~ /[^\xc0]/di;).  We
1406      * have to do this here before we add the unconditionally matched code
1407      * points */
1408     if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1409         _invlist_intersection_complement_2nd(invlist,
1410                                              PL_UpperLatin1,
1411                                              &invlist);
1412     }
1413
1414     /* Add in the points from the bit map */
1415     for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1416         if (ANYOF_BITMAP_TEST(node, i)) {
1417             invlist = add_cp_to_invlist(invlist, i);
1418             new_node_has_latin1 = TRUE;
1419         }
1420     }
1421
1422     /* If this can match all upper Latin1 code points, have to add them
1423      * as well.  But don't add them if inverting, as when that gets done below,
1424      * it would exclude all these characters, including the ones it shouldn't
1425      * that were added just above */
1426     if (! (ANYOF_FLAGS(node) & ANYOF_INVERT) && OP(node) == ANYOFD
1427         && (ANYOF_FLAGS(node) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1428     {
1429         _invlist_union(invlist, PL_UpperLatin1, &invlist);
1430     }
1431
1432     /* Similarly for these */
1433     if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1434         _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1435     }
1436
1437     if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1438         _invlist_invert(invlist);
1439     }
1440     else if (new_node_has_latin1 && ANYOF_FLAGS(node) & ANYOFL_FOLD) {
1441
1442         /* Under /li, any 0-255 could fold to any other 0-255, depending on the
1443          * locale.  We can skip this if there are no 0-255 at all. */
1444         _invlist_union(invlist, PL_Latin1, &invlist);
1445     }
1446
1447     /* Similarly add the UTF-8 locale possible matches.  These have to be
1448      * deferred until after the non-UTF-8 locale ones are taken care of just
1449      * above, or it leads to wrong results under ANYOF_INVERT */
1450     if (only_utf8_locale_invlist) {
1451         _invlist_union_maybe_complement_2nd(invlist,
1452                                             only_utf8_locale_invlist,
1453                                             ANYOF_FLAGS(node) & ANYOF_INVERT,
1454                                             &invlist);
1455     }
1456
1457     return invlist;
1458 }
1459
1460 /* These two functions currently do the exact same thing */
1461 #define ssc_init_zero           ssc_init
1462
1463 #define ssc_add_cp(ssc, cp)   ssc_add_range((ssc), (cp), (cp))
1464 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1465
1466 /* 'AND' a given class with another one.  Can create false positives.  'ssc'
1467  * should not be inverted.  'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1468  * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1469
1470 STATIC void
1471 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1472                 const regnode_charclass *and_with)
1473 {
1474     /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1475      * another SSC or a regular ANYOF class.  Can create false positives. */
1476
1477     SV* anded_cp_list;
1478     U8  anded_flags;
1479
1480     PERL_ARGS_ASSERT_SSC_AND;
1481
1482     assert(is_ANYOF_SYNTHETIC(ssc));
1483
1484     /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1485      * the code point inversion list and just the relevant flags */
1486     if (is_ANYOF_SYNTHETIC(and_with)) {
1487         anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1488         anded_flags = ANYOF_FLAGS(and_with);
1489
1490         /* XXX This is a kludge around what appears to be deficiencies in the
1491          * optimizer.  If we make S_ssc_anything() add in the WARN_SUPER flag,
1492          * there are paths through the optimizer where it doesn't get weeded
1493          * out when it should.  And if we don't make some extra provision for
1494          * it like the code just below, it doesn't get added when it should.
1495          * This solution is to add it only when AND'ing, which is here, and
1496          * only when what is being AND'ed is the pristine, original node
1497          * matching anything.  Thus it is like adding it to ssc_anything() but
1498          * only when the result is to be AND'ed.  Probably the same solution
1499          * could be adopted for the same problem we have with /l matching,
1500          * which is solved differently in S_ssc_init(), and that would lead to
1501          * fewer false positives than that solution has.  But if this solution
1502          * creates bugs, the consequences are only that a warning isn't raised
1503          * that should be; while the consequences for having /l bugs is
1504          * incorrect matches */
1505         if (ssc_is_anything((regnode_ssc *)and_with)) {
1506             anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1507         }
1508     }
1509     else {
1510         anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1511         if (OP(and_with) == ANYOFD) {
1512             anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
1513         }
1514         else {
1515             anded_flags = ANYOF_FLAGS(and_with)
1516             &( ANYOF_COMMON_FLAGS
1517               |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1518               |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1519             if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(and_with))) {
1520                 anded_flags &=
1521                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1522             }
1523         }
1524     }
1525
1526     ANYOF_FLAGS(ssc) &= anded_flags;
1527
1528     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1529      * C2 is the list of code points in 'and-with'; P2, its posix classes.
1530      * 'and_with' may be inverted.  When not inverted, we have the situation of
1531      * computing:
1532      *  (C1 | P1) & (C2 | P2)
1533      *                     =  (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1534      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1535      *                    <=  ((C1 & C2) |       P2)) | ( P1       | (P1 & P2))
1536      *                    <=  ((C1 & C2) | P1 | P2)
1537      * Alternatively, the last few steps could be:
1538      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1539      *                    <=  ((C1 & C2) |  C1      ) | (      C2  | (P1 & P2))
1540      *                    <=  (C1 | C2 | (P1 & P2))
1541      * We favor the second approach if either P1 or P2 is non-empty.  This is
1542      * because these components are a barrier to doing optimizations, as what
1543      * they match cannot be known until the moment of matching as they are
1544      * dependent on the current locale, 'AND"ing them likely will reduce or
1545      * eliminate them.
1546      * But we can do better if we know that C1,P1 are in their initial state (a
1547      * frequent occurrence), each matching everything:
1548      *  (<everything>) & (C2 | P2) =  C2 | P2
1549      * Similarly, if C2,P2 are in their initial state (again a frequent
1550      * occurrence), the result is a no-op
1551      *  (C1 | P1) & (<everything>) =  C1 | P1
1552      *
1553      * Inverted, we have
1554      *  (C1 | P1) & ~(C2 | P2)  =  (C1 | P1) & (~C2 & ~P2)
1555      *                          =  (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1556      *                         <=  (C1 & ~C2) | (P1 & ~P2)
1557      * */
1558
1559     if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
1560         && ! is_ANYOF_SYNTHETIC(and_with))
1561     {
1562         unsigned int i;
1563
1564         ssc_intersection(ssc,
1565                          anded_cp_list,
1566                          FALSE /* Has already been inverted */
1567                          );
1568
1569         /* If either P1 or P2 is empty, the intersection will be also; can skip
1570          * the loop */
1571         if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
1572             ANYOF_POSIXL_ZERO(ssc);
1573         }
1574         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1575
1576             /* Note that the Posix class component P from 'and_with' actually
1577              * looks like:
1578              *      P = Pa | Pb | ... | Pn
1579              * where each component is one posix class, such as in [\w\s].
1580              * Thus
1581              *      ~P = ~(Pa | Pb | ... | Pn)
1582              *         = ~Pa & ~Pb & ... & ~Pn
1583              *        <= ~Pa | ~Pb | ... | ~Pn
1584              * The last is something we can easily calculate, but unfortunately
1585              * is likely to have many false positives.  We could do better
1586              * in some (but certainly not all) instances if two classes in
1587              * P have known relationships.  For example
1588              *      :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1589              * So
1590              *      :lower: & :print: = :lower:
1591              * And similarly for classes that must be disjoint.  For example,
1592              * since \s and \w can have no elements in common based on rules in
1593              * the POSIX standard,
1594              *      \w & ^\S = nothing
1595              * Unfortunately, some vendor locales do not meet the Posix
1596              * standard, in particular almost everything by Microsoft.
1597              * The loop below just changes e.g., \w into \W and vice versa */
1598
1599             regnode_charclass_posixl temp;
1600             int add = 1;    /* To calculate the index of the complement */
1601
1602             ANYOF_POSIXL_ZERO(&temp);
1603             for (i = 0; i < ANYOF_MAX; i++) {
1604                 assert(i % 2 != 0
1605                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1606                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1607
1608                 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1609                     ANYOF_POSIXL_SET(&temp, i + add);
1610                 }
1611                 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1612             }
1613             ANYOF_POSIXL_AND(&temp, ssc);
1614
1615         } /* else ssc already has no posixes */
1616     } /* else: Not inverted.  This routine is a no-op if 'and_with' is an SSC
1617          in its initial state */
1618     else if (! is_ANYOF_SYNTHETIC(and_with)
1619              || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1620     {
1621         /* But if 'ssc' is in its initial state, the result is just 'and_with';
1622          * copy it over 'ssc' */
1623         if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1624             if (is_ANYOF_SYNTHETIC(and_with)) {
1625                 StructCopy(and_with, ssc, regnode_ssc);
1626             }
1627             else {
1628                 ssc->invlist = anded_cp_list;
1629                 ANYOF_POSIXL_ZERO(ssc);
1630                 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1631                     ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1632                 }
1633             }
1634         }
1635         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1636                  || (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
1637         {
1638             /* One or the other of P1, P2 is non-empty. */
1639             if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1640                 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1641             }
1642             ssc_union(ssc, anded_cp_list, FALSE);
1643         }
1644         else { /* P1 = P2 = empty */
1645             ssc_intersection(ssc, anded_cp_list, FALSE);
1646         }
1647     }
1648 }
1649
1650 STATIC void
1651 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1652                const regnode_charclass *or_with)
1653 {
1654     /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1655      * another SSC or a regular ANYOF class.  Can create false positives if
1656      * 'or_with' is to be inverted. */
1657
1658     SV* ored_cp_list;
1659     U8 ored_flags;
1660
1661     PERL_ARGS_ASSERT_SSC_OR;
1662
1663     assert(is_ANYOF_SYNTHETIC(ssc));
1664
1665     /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1666      * the code point inversion list and just the relevant flags */
1667     if (is_ANYOF_SYNTHETIC(or_with)) {
1668         ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1669         ored_flags = ANYOF_FLAGS(or_with);
1670     }
1671     else {
1672         ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1673         ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
1674         if (OP(or_with) != ANYOFD) {
1675             ored_flags
1676             |= ANYOF_FLAGS(or_with)
1677              & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1678                 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1679             if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(or_with))) {
1680                 ored_flags |=
1681                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1682             }
1683         }
1684     }
1685
1686     ANYOF_FLAGS(ssc) |= ored_flags;
1687
1688     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1689      * C2 is the list of code points in 'or-with'; P2, its posix classes.
1690      * 'or_with' may be inverted.  When not inverted, we have the simple
1691      * situation of computing:
1692      *  (C1 | P1) | (C2 | P2)  =  (C1 | C2) | (P1 | P2)
1693      * If P1|P2 yields a situation with both a class and its complement are
1694      * set, like having both \w and \W, this matches all code points, and we
1695      * can delete these from the P component of the ssc going forward.  XXX We
1696      * might be able to delete all the P components, but I (khw) am not certain
1697      * about this, and it is better to be safe.
1698      *
1699      * Inverted, we have
1700      *  (C1 | P1) | ~(C2 | P2)  =  (C1 | P1) | (~C2 & ~P2)
1701      *                         <=  (C1 | P1) | ~C2
1702      *                         <=  (C1 | ~C2) | P1
1703      * (which results in actually simpler code than the non-inverted case)
1704      * */
1705
1706     if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
1707         && ! is_ANYOF_SYNTHETIC(or_with))
1708     {
1709         /* We ignore P2, leaving P1 going forward */
1710     }   /* else  Not inverted */
1711     else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
1712         ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1713         if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1714             unsigned int i;
1715             for (i = 0; i < ANYOF_MAX; i += 2) {
1716                 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1717                 {
1718                     ssc_match_all_cp(ssc);
1719                     ANYOF_POSIXL_CLEAR(ssc, i);
1720                     ANYOF_POSIXL_CLEAR(ssc, i+1);
1721                 }
1722             }
1723         }
1724     }
1725
1726     ssc_union(ssc,
1727               ored_cp_list,
1728               FALSE /* Already has been inverted */
1729               );
1730 }
1731
1732 PERL_STATIC_INLINE void
1733 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1734 {
1735     PERL_ARGS_ASSERT_SSC_UNION;
1736
1737     assert(is_ANYOF_SYNTHETIC(ssc));
1738
1739     _invlist_union_maybe_complement_2nd(ssc->invlist,
1740                                         invlist,
1741                                         invert2nd,
1742                                         &ssc->invlist);
1743 }
1744
1745 PERL_STATIC_INLINE void
1746 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1747                          SV* const invlist,
1748                          const bool invert2nd)
1749 {
1750     PERL_ARGS_ASSERT_SSC_INTERSECTION;
1751
1752     assert(is_ANYOF_SYNTHETIC(ssc));
1753
1754     _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1755                                                invlist,
1756                                                invert2nd,
1757                                                &ssc->invlist);
1758 }
1759
1760 PERL_STATIC_INLINE void
1761 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
1762 {
1763     PERL_ARGS_ASSERT_SSC_ADD_RANGE;
1764
1765     assert(is_ANYOF_SYNTHETIC(ssc));
1766
1767     ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
1768 }
1769
1770 PERL_STATIC_INLINE void
1771 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
1772 {
1773     /* AND just the single code point 'cp' into the SSC 'ssc' */
1774
1775     SV* cp_list = _new_invlist(2);
1776
1777     PERL_ARGS_ASSERT_SSC_CP_AND;
1778
1779     assert(is_ANYOF_SYNTHETIC(ssc));
1780
1781     cp_list = add_cp_to_invlist(cp_list, cp);
1782     ssc_intersection(ssc, cp_list,
1783                      FALSE /* Not inverted */
1784                      );
1785     SvREFCNT_dec_NN(cp_list);
1786 }
1787
1788 PERL_STATIC_INLINE void
1789 S_ssc_clear_locale(regnode_ssc *ssc)
1790 {
1791     /* Set the SSC 'ssc' to not match any locale things */
1792     PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
1793
1794     assert(is_ANYOF_SYNTHETIC(ssc));
1795
1796     ANYOF_POSIXL_ZERO(ssc);
1797     ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
1798 }
1799
1800 #define NON_OTHER_COUNT   NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
1801
1802 STATIC bool
1803 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
1804 {
1805     /* The synthetic start class is used to hopefully quickly winnow down
1806      * places where a pattern could start a match in the target string.  If it
1807      * doesn't really narrow things down that much, there isn't much point to
1808      * having the overhead of using it.  This function uses some very crude
1809      * heuristics to decide if to use the ssc or not.
1810      *
1811      * It returns TRUE if 'ssc' rules out more than half what it considers to
1812      * be the "likely" possible matches, but of course it doesn't know what the
1813      * actual things being matched are going to be; these are only guesses
1814      *
1815      * For /l matches, it assumes that the only likely matches are going to be
1816      *      in the 0-255 range, uniformly distributed, so half of that is 127
1817      * For /a and /d matches, it assumes that the likely matches will be just
1818      *      the ASCII range, so half of that is 63
1819      * For /u and there isn't anything matching above the Latin1 range, it
1820      *      assumes that that is the only range likely to be matched, and uses
1821      *      half that as the cut-off: 127.  If anything matches above Latin1,
1822      *      it assumes that all of Unicode could match (uniformly), except for
1823      *      non-Unicode code points and things in the General Category "Other"
1824      *      (unassigned, private use, surrogates, controls and formats).  This
1825      *      is a much large number. */
1826
1827     U32 count = 0;      /* Running total of number of code points matched by
1828                            'ssc' */
1829     UV start, end;      /* Start and end points of current range in inversion
1830                            list */
1831     const U32 max_code_points = (LOC)
1832                                 ?  256
1833                                 : ((   ! UNI_SEMANTICS
1834                                      || invlist_highest(ssc->invlist) < 256)
1835                                   ? 128
1836                                   : NON_OTHER_COUNT);
1837     const U32 max_match = max_code_points / 2;
1838
1839     PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
1840
1841     invlist_iterinit(ssc->invlist);
1842     while (invlist_iternext(ssc->invlist, &start, &end)) {
1843         if (start >= max_code_points) {
1844             break;
1845         }
1846         end = MIN(end, max_code_points - 1);
1847         count += end - start + 1;
1848         if (count >= max_match) {
1849             invlist_iterfinish(ssc->invlist);
1850             return FALSE;
1851         }
1852     }
1853
1854     return TRUE;
1855 }
1856
1857
1858 STATIC void
1859 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
1860 {
1861     /* The inversion list in the SSC is marked mortal; now we need a more
1862      * permanent copy, which is stored the same way that is done in a regular
1863      * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
1864      * map */
1865
1866     SV* invlist = invlist_clone(ssc->invlist);
1867
1868     PERL_ARGS_ASSERT_SSC_FINALIZE;
1869
1870     assert(is_ANYOF_SYNTHETIC(ssc));
1871
1872     /* The code in this file assumes that all but these flags aren't relevant
1873      * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
1874      * by the time we reach here */
1875     assert(! (ANYOF_FLAGS(ssc)
1876         & ~( ANYOF_COMMON_FLAGS
1877             |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1878             |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
1879
1880     populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
1881
1882     set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist,
1883                                 NULL, NULL, NULL, FALSE);
1884
1885     /* Make sure is clone-safe */
1886     ssc->invlist = NULL;
1887
1888     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1889         ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
1890     }
1891
1892     if (RExC_contains_locale) {
1893         OP(ssc) = ANYOFL;
1894     }
1895
1896     assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
1897 }
1898
1899 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
1900 #define TRIE_LIST_CUR(state)  ( TRIE_LIST_ITEM( state, 0 ).forid )
1901 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
1902 #define TRIE_LIST_USED(idx)  ( trie->states[state].trans.list         \
1903                                ? (TRIE_LIST_CUR( idx ) - 1)           \
1904                                : 0 )
1905
1906
1907 #ifdef DEBUGGING
1908 /*
1909    dump_trie(trie,widecharmap,revcharmap)
1910    dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
1911    dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
1912
1913    These routines dump out a trie in a somewhat readable format.
1914    The _interim_ variants are used for debugging the interim
1915    tables that are used to generate the final compressed
1916    representation which is what dump_trie expects.
1917
1918    Part of the reason for their existence is to provide a form
1919    of documentation as to how the different representations function.
1920
1921 */
1922
1923 /*
1924   Dumps the final compressed table form of the trie to Perl_debug_log.
1925   Used for debugging make_trie().
1926 */
1927
1928 STATIC void
1929 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
1930             AV *revcharmap, U32 depth)
1931 {
1932     U32 state;
1933     SV *sv=sv_newmortal();
1934     int colwidth= widecharmap ? 6 : 4;
1935     U16 word;
1936     GET_RE_DEBUG_FLAGS_DECL;
1937
1938     PERL_ARGS_ASSERT_DUMP_TRIE;
1939
1940     PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
1941         (int)depth * 2 + 2,"",
1942         "Match","Base","Ofs" );
1943
1944     for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
1945         SV ** const tmp = av_fetch( revcharmap, state, 0);
1946         if ( tmp ) {
1947             PerlIO_printf( Perl_debug_log, "%*s",
1948                 colwidth,
1949                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
1950                             PL_colors[0], PL_colors[1],
1951                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1952                             PERL_PV_ESCAPE_FIRSTCHAR
1953                 )
1954             );
1955         }
1956     }
1957     PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
1958         (int)depth * 2 + 2,"");
1959
1960     for( state = 0 ; state < trie->uniquecharcount ; state++ )
1961         PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
1962     PerlIO_printf( Perl_debug_log, "\n");
1963
1964     for( state = 1 ; state < trie->statecount ; state++ ) {
1965         const U32 base = trie->states[ state ].trans.base;
1966
1967         PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|",
1968                                        (int)depth * 2 + 2,"", (UV)state);
1969
1970         if ( trie->states[ state ].wordnum ) {
1971             PerlIO_printf( Perl_debug_log, " W%4X",
1972                                            trie->states[ state ].wordnum );
1973         } else {
1974             PerlIO_printf( Perl_debug_log, "%6s", "" );
1975         }
1976
1977         PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
1978
1979         if ( base ) {
1980             U32 ofs = 0;
1981
1982             while( ( base + ofs  < trie->uniquecharcount ) ||
1983                    ( base + ofs - trie->uniquecharcount < trie->lasttrans
1984                      && trie->trans[ base + ofs - trie->uniquecharcount ].check
1985                                                                     != state))
1986                     ofs++;
1987
1988             PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
1989
1990             for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1991                 if ( ( base + ofs >= trie->uniquecharcount )
1992                         && ( base + ofs - trie->uniquecharcount
1993                                                         < trie->lasttrans )
1994                         && trie->trans[ base + ofs
1995                                     - trie->uniquecharcount ].check == state )
1996                 {
1997                    PerlIO_printf( Perl_debug_log, "%*"UVXf,
1998                     colwidth,
1999                     (UV)trie->trans[ base + ofs
2000                                              - trie->uniquecharcount ].next );
2001                 } else {
2002                     PerlIO_printf( Perl_debug_log, "%*s",colwidth,"   ." );
2003                 }
2004             }
2005
2006             PerlIO_printf( Perl_debug_log, "]");
2007
2008         }
2009         PerlIO_printf( Perl_debug_log, "\n" );
2010     }
2011     PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=",
2012                                 (int)depth*2, "");
2013     for (word=1; word <= trie->wordcount; word++) {
2014         PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
2015             (int)word, (int)(trie->wordinfo[word].prev),
2016             (int)(trie->wordinfo[word].len));
2017     }
2018     PerlIO_printf(Perl_debug_log, "\n" );
2019 }
2020 /*
2021   Dumps a fully constructed but uncompressed trie in list form.
2022   List tries normally only are used for construction when the number of
2023   possible chars (trie->uniquecharcount) is very high.
2024   Used for debugging make_trie().
2025 */
2026 STATIC void
2027 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2028                          HV *widecharmap, AV *revcharmap, U32 next_alloc,
2029                          U32 depth)
2030 {
2031     U32 state;
2032     SV *sv=sv_newmortal();
2033     int colwidth= widecharmap ? 6 : 4;
2034     GET_RE_DEBUG_FLAGS_DECL;
2035
2036     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2037
2038     /* print out the table precompression.  */
2039     PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
2040         (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
2041         "------:-----+-----------------\n" );
2042
2043     for( state=1 ; state < next_alloc ; state ++ ) {
2044         U16 charid;
2045
2046         PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
2047             (int)depth * 2 + 2,"", (UV)state  );
2048         if ( ! trie->states[ state ].wordnum ) {
2049             PerlIO_printf( Perl_debug_log, "%5s| ","");
2050         } else {
2051             PerlIO_printf( Perl_debug_log, "W%4x| ",
2052                 trie->states[ state ].wordnum
2053             );
2054         }
2055         for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2056             SV ** const tmp = av_fetch( revcharmap,
2057                                         TRIE_LIST_ITEM(state,charid).forid, 0);
2058             if ( tmp ) {
2059                 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
2060                     colwidth,
2061                     pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2062                               colwidth,
2063                               PL_colors[0], PL_colors[1],
2064                               (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2065                               | PERL_PV_ESCAPE_FIRSTCHAR
2066                     ) ,
2067                     TRIE_LIST_ITEM(state,charid).forid,
2068                     (UV)TRIE_LIST_ITEM(state,charid).newstate
2069                 );
2070                 if (!(charid % 10))
2071                     PerlIO_printf(Perl_debug_log, "\n%*s| ",
2072                         (int)((depth * 2) + 14), "");
2073             }
2074         }
2075         PerlIO_printf( Perl_debug_log, "\n");
2076     }
2077 }
2078
2079 /*
2080   Dumps a fully constructed but uncompressed trie in table form.
2081   This is the normal DFA style state transition table, with a few
2082   twists to facilitate compression later.
2083   Used for debugging make_trie().
2084 */
2085 STATIC void
2086 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2087                           HV *widecharmap, AV *revcharmap, U32 next_alloc,
2088                           U32 depth)
2089 {
2090     U32 state;
2091     U16 charid;
2092     SV *sv=sv_newmortal();
2093     int colwidth= widecharmap ? 6 : 4;
2094     GET_RE_DEBUG_FLAGS_DECL;
2095
2096     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2097
2098     /*
2099        print out the table precompression so that we can do a visual check
2100        that they are identical.
2101      */
2102
2103     PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
2104
2105     for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2106         SV ** const tmp = av_fetch( revcharmap, charid, 0);
2107         if ( tmp ) {
2108             PerlIO_printf( Perl_debug_log, "%*s",
2109                 colwidth,
2110                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2111                             PL_colors[0], PL_colors[1],
2112                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2113                             PERL_PV_ESCAPE_FIRSTCHAR
2114                 )
2115             );
2116         }
2117     }
2118
2119     PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
2120
2121     for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2122         PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
2123     }
2124
2125     PerlIO_printf( Perl_debug_log, "\n" );
2126
2127     for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2128
2129         PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
2130             (int)depth * 2 + 2,"",
2131             (UV)TRIE_NODENUM( state ) );
2132
2133         for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2134             UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2135             if (v)
2136                 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
2137             else
2138                 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
2139         }
2140         if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2141             PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n",
2142                                             (UV)trie->trans[ state ].check );
2143         } else {
2144             PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n",
2145                                             (UV)trie->trans[ state ].check,
2146             trie->states[ TRIE_NODENUM( state ) ].wordnum );
2147         }
2148     }
2149 }
2150
2151 #endif
2152
2153
2154 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2155   startbranch: the first branch in the whole branch sequence
2156   first      : start branch of sequence of branch-exact nodes.
2157                May be the same as startbranch
2158   last       : Thing following the last branch.
2159                May be the same as tail.
2160   tail       : item following the branch sequence
2161   count      : words in the sequence
2162   flags      : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2163   depth      : indent depth
2164
2165 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2166
2167 A trie is an N'ary tree where the branches are determined by digital
2168 decomposition of the key. IE, at the root node you look up the 1st character and
2169 follow that branch repeat until you find the end of the branches. Nodes can be
2170 marked as "accepting" meaning they represent a complete word. Eg:
2171
2172   /he|she|his|hers/
2173
2174 would convert into the following structure. Numbers represent states, letters
2175 following numbers represent valid transitions on the letter from that state, if
2176 the number is in square brackets it represents an accepting state, otherwise it
2177 will be in parenthesis.
2178
2179       +-h->+-e->[3]-+-r->(8)-+-s->[9]
2180       |    |
2181       |   (2)
2182       |    |
2183      (1)   +-i->(6)-+-s->[7]
2184       |
2185       +-s->(3)-+-h->(4)-+-e->[5]
2186
2187       Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2188
2189 This shows that when matching against the string 'hers' we will begin at state 1
2190 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2191 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2192 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2193 single traverse. We store a mapping from accepting to state to which word was
2194 matched, and then when we have multiple possibilities we try to complete the
2195 rest of the regex in the order in which they occurred in the alternation.
2196
2197 The only prior NFA like behaviour that would be changed by the TRIE support is
2198 the silent ignoring of duplicate alternations which are of the form:
2199
2200  / (DUPE|DUPE) X? (?{ ... }) Y /x
2201
2202 Thus EVAL blocks following a trie may be called a different number of times with
2203 and without the optimisation. With the optimisations dupes will be silently
2204 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2205 the following demonstrates:
2206
2207  'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2208
2209 which prints out 'word' three times, but
2210
2211  'words'=~/(word|word|word)(?{ print $1 })S/
2212
2213 which doesnt print it out at all. This is due to other optimisations kicking in.
2214
2215 Example of what happens on a structural level:
2216
2217 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2218
2219    1: CURLYM[1] {1,32767}(18)
2220    5:   BRANCH(8)
2221    6:     EXACT <ac>(16)
2222    8:   BRANCH(11)
2223    9:     EXACT <ad>(16)
2224   11:   BRANCH(14)
2225   12:     EXACT <ab>(16)
2226   16:   SUCCEED(0)
2227   17:   NOTHING(18)
2228   18: END(0)
2229
2230 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2231 and should turn into:
2232
2233    1: CURLYM[1] {1,32767}(18)
2234    5:   TRIE(16)
2235         [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2236           <ac>
2237           <ad>
2238           <ab>
2239   16:   SUCCEED(0)
2240   17:   NOTHING(18)
2241   18: END(0)
2242
2243 Cases where tail != last would be like /(?foo|bar)baz/:
2244
2245    1: BRANCH(4)
2246    2:   EXACT <foo>(8)
2247    4: BRANCH(7)
2248    5:   EXACT <bar>(8)
2249    7: TAIL(8)
2250    8: EXACT <baz>(10)
2251   10: END(0)
2252
2253 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2254 and would end up looking like:
2255
2256     1: TRIE(8)
2257       [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2258         <foo>
2259         <bar>
2260    7: TAIL(8)
2261    8: EXACT <baz>(10)
2262   10: END(0)
2263
2264     d = uvchr_to_utf8_flags(d, uv, 0);
2265
2266 is the recommended Unicode-aware way of saying
2267
2268     *(d++) = uv;
2269 */
2270
2271 #define TRIE_STORE_REVCHAR(val)                                            \
2272     STMT_START {                                                           \
2273         if (UTF) {                                                         \
2274             SV *zlopp = newSV(UTF8_MAXBYTES);                              \
2275             unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp);      \
2276             unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2277             SvCUR_set(zlopp, kapow - flrbbbbb);                            \
2278             SvPOK_on(zlopp);                                               \
2279             SvUTF8_on(zlopp);                                              \
2280             av_push(revcharmap, zlopp);                                    \
2281         } else {                                                           \
2282             char ooooff = (char)val;                                           \
2283             av_push(revcharmap, newSVpvn(&ooooff, 1));                     \
2284         }                                                                  \
2285         } STMT_END
2286
2287 /* This gets the next character from the input, folding it if not already
2288  * folded. */
2289 #define TRIE_READ_CHAR STMT_START {                                           \
2290     wordlen++;                                                                \
2291     if ( UTF ) {                                                              \
2292         /* if it is UTF then it is either already folded, or does not need    \
2293          * folding */                                                         \
2294         uvc = valid_utf8_to_uvchr( (const U8*) uc, &len);                     \
2295     }                                                                         \
2296     else if (folder == PL_fold_latin1) {                                      \
2297         /* This folder implies Unicode rules, which in the range expressible  \
2298          *  by not UTF is the lower case, with the two exceptions, one of     \
2299          *  which should have been taken care of before calling this */       \
2300         assert(*uc != LATIN_SMALL_LETTER_SHARP_S);                            \
2301         uvc = toLOWER_L1(*uc);                                                \
2302         if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU;         \
2303         len = 1;                                                              \
2304     } else {                                                                  \
2305         /* raw data, will be folded later if needed */                        \
2306         uvc = (U32)*uc;                                                       \
2307         len = 1;                                                              \
2308     }                                                                         \
2309 } STMT_END
2310
2311
2312
2313 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START {               \
2314     if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) {    \
2315         U32 ging = TRIE_LIST_LEN( state ) *= 2;                 \
2316         Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2317     }                                                           \
2318     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid;     \
2319     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns;   \
2320     TRIE_LIST_CUR( state )++;                                   \
2321 } STMT_END
2322
2323 #define TRIE_LIST_NEW(state) STMT_START {                       \
2324     Newxz( trie->states[ state ].trans.list,               \
2325         4, reg_trie_trans_le );                                 \
2326      TRIE_LIST_CUR( state ) = 1;                                \
2327      TRIE_LIST_LEN( state ) = 4;                                \
2328 } STMT_END
2329
2330 #define TRIE_HANDLE_WORD(state) STMT_START {                    \
2331     U16 dupe= trie->states[ state ].wordnum;                    \
2332     regnode * const noper_next = regnext( noper );              \
2333                                                                 \
2334     DEBUG_r({                                                   \
2335         /* store the word for dumping */                        \
2336         SV* tmp;                                                \
2337         if (OP(noper) != NOTHING)                               \
2338             tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF);    \
2339         else                                                    \
2340             tmp = newSVpvn_utf8( "", 0, UTF );                  \
2341         av_push( trie_words, tmp );                             \
2342     });                                                         \
2343                                                                 \
2344     curword++;                                                  \
2345     trie->wordinfo[curword].prev   = 0;                         \
2346     trie->wordinfo[curword].len    = wordlen;                   \
2347     trie->wordinfo[curword].accept = state;                     \
2348                                                                 \
2349     if ( noper_next < tail ) {                                  \
2350         if (!trie->jump)                                        \
2351             trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2352                                                  sizeof(U16) ); \
2353         trie->jump[curword] = (U16)(noper_next - convert);      \
2354         if (!jumper)                                            \
2355             jumper = noper_next;                                \
2356         if (!nextbranch)                                        \
2357             nextbranch= regnext(cur);                           \
2358     }                                                           \
2359                                                                 \
2360     if ( dupe ) {                                               \
2361         /* It's a dupe. Pre-insert into the wordinfo[].prev   */\
2362         /* chain, so that when the bits of chain are later    */\
2363         /* linked together, the dups appear in the chain      */\
2364         trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2365         trie->wordinfo[dupe].prev = curword;                    \
2366     } else {                                                    \
2367         /* we haven't inserted this word yet.                */ \
2368         trie->states[ state ].wordnum = curword;                \
2369     }                                                           \
2370 } STMT_END
2371
2372
2373 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special)          \
2374      ( ( base + charid >=  ucharcount                                   \
2375          && base + charid < ubound                                      \
2376          && state == trie->trans[ base - ucharcount + charid ].check    \
2377          && trie->trans[ base - ucharcount + charid ].next )            \
2378            ? trie->trans[ base - ucharcount + charid ].next             \
2379            : ( state==1 ? special : 0 )                                 \
2380       )
2381
2382 #define MADE_TRIE       1
2383 #define MADE_JUMP_TRIE  2
2384 #define MADE_EXACT_TRIE 4
2385
2386 STATIC I32
2387 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2388                   regnode *first, regnode *last, regnode *tail,
2389                   U32 word_count, U32 flags, U32 depth)
2390 {
2391     /* first pass, loop through and scan words */
2392     reg_trie_data *trie;
2393     HV *widecharmap = NULL;
2394     AV *revcharmap = newAV();
2395     regnode *cur;
2396     STRLEN len = 0;
2397     UV uvc = 0;
2398     U16 curword = 0;
2399     U32 next_alloc = 0;
2400     regnode *jumper = NULL;
2401     regnode *nextbranch = NULL;
2402     regnode *convert = NULL;
2403     U32 *prev_states; /* temp array mapping each state to previous one */
2404     /* we just use folder as a flag in utf8 */
2405     const U8 * folder = NULL;
2406
2407 #ifdef DEBUGGING
2408     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuuu"));
2409     AV *trie_words = NULL;
2410     /* along with revcharmap, this only used during construction but both are
2411      * useful during debugging so we store them in the struct when debugging.
2412      */
2413 #else
2414     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2415     STRLEN trie_charcount=0;
2416 #endif
2417     SV *re_trie_maxbuff;
2418     GET_RE_DEBUG_FLAGS_DECL;
2419
2420     PERL_ARGS_ASSERT_MAKE_TRIE;
2421 #ifndef DEBUGGING
2422     PERL_UNUSED_ARG(depth);
2423 #endif
2424
2425     switch (flags) {
2426         case EXACT: case EXACTL: break;
2427         case EXACTFA:
2428         case EXACTFU_SS:
2429         case EXACTFU:
2430         case EXACTFLU8: folder = PL_fold_latin1; break;
2431         case EXACTF:  folder = PL_fold; break;
2432         default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2433     }
2434
2435     trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2436     trie->refcount = 1;
2437     trie->startstate = 1;
2438     trie->wordcount = word_count;
2439     RExC_rxi->data->data[ data_slot ] = (void*)trie;
2440     trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2441     if (flags == EXACT || flags == EXACTL)
2442         trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2443     trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2444                        trie->wordcount+1, sizeof(reg_trie_wordinfo));
2445
2446     DEBUG_r({
2447         trie_words = newAV();
2448     });
2449
2450     re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2451     assert(re_trie_maxbuff);
2452     if (!SvIOK(re_trie_maxbuff)) {
2453         sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2454     }
2455     DEBUG_TRIE_COMPILE_r({
2456         PerlIO_printf( Perl_debug_log,
2457           "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2458           (int)depth * 2 + 2, "",
2459           REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
2460           REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2461     });
2462
2463    /* Find the node we are going to overwrite */
2464     if ( first == startbranch && OP( last ) != BRANCH ) {
2465         /* whole branch chain */
2466         convert = first;
2467     } else {
2468         /* branch sub-chain */
2469         convert = NEXTOPER( first );
2470     }
2471
2472     /*  -- First loop and Setup --
2473
2474        We first traverse the branches and scan each word to determine if it
2475        contains widechars, and how many unique chars there are, this is
2476        important as we have to build a table with at least as many columns as we
2477        have unique chars.
2478
2479        We use an array of integers to represent the character codes 0..255
2480        (trie->charmap) and we use a an HV* to store Unicode characters. We use
2481        the native representation of the character value as the key and IV's for
2482        the coded index.
2483
2484        *TODO* If we keep track of how many times each character is used we can
2485        remap the columns so that the table compression later on is more
2486        efficient in terms of memory by ensuring the most common value is in the
2487        middle and the least common are on the outside.  IMO this would be better
2488        than a most to least common mapping as theres a decent chance the most
2489        common letter will share a node with the least common, meaning the node
2490        will not be compressible. With a middle is most common approach the worst
2491        case is when we have the least common nodes twice.
2492
2493      */
2494
2495     for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2496         regnode *noper = NEXTOPER( cur );
2497         const U8 *uc = (U8*)STRING( noper );
2498         const U8 *e  = uc + STR_LEN( noper );
2499         int foldlen = 0;
2500         U32 wordlen      = 0;         /* required init */
2501         STRLEN minchars = 0;
2502         STRLEN maxchars = 0;
2503         bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2504                                                bitmap?*/
2505
2506         if (OP(noper) == NOTHING) {
2507             regnode *noper_next= regnext(noper);
2508             if (noper_next != tail && OP(noper_next) == flags) {
2509                 noper = noper_next;
2510                 uc= (U8*)STRING(noper);
2511                 e= uc + STR_LEN(noper);
2512                 trie->minlen= STR_LEN(noper);
2513             } else {
2514                 trie->minlen= 0;
2515                 continue;
2516             }
2517         }
2518
2519         if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2520             TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2521                                           regardless of encoding */
2522             if (OP( noper ) == EXACTFU_SS) {
2523                 /* false positives are ok, so just set this */
2524                 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2525             }
2526         }
2527         for ( ; uc < e ; uc += len ) {  /* Look at each char in the current
2528                                            branch */
2529             TRIE_CHARCOUNT(trie)++;
2530             TRIE_READ_CHAR;
2531
2532             /* TRIE_READ_CHAR returns the current character, or its fold if /i
2533              * is in effect.  Under /i, this character can match itself, or
2534              * anything that folds to it.  If not under /i, it can match just
2535              * itself.  Most folds are 1-1, for example k, K, and KELVIN SIGN
2536              * all fold to k, and all are single characters.   But some folds
2537              * expand to more than one character, so for example LATIN SMALL
2538              * LIGATURE FFI folds to the three character sequence 'ffi'.  If
2539              * the string beginning at 'uc' is 'ffi', it could be matched by
2540              * three characters, or just by the one ligature character. (It
2541              * could also be matched by two characters: LATIN SMALL LIGATURE FF
2542              * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2543              * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2544              * match.)  The trie needs to know the minimum and maximum number
2545              * of characters that could match so that it can use size alone to
2546              * quickly reject many match attempts.  The max is simple: it is
2547              * the number of folded characters in this branch (since a fold is
2548              * never shorter than what folds to it. */
2549
2550             maxchars++;
2551
2552             /* And the min is equal to the max if not under /i (indicated by
2553              * 'folder' being NULL), or there are no multi-character folds.  If
2554              * there is a multi-character fold, the min is incremented just
2555              * once, for the character that folds to the sequence.  Each
2556              * character in the sequence needs to be added to the list below of
2557              * characters in the trie, but we count only the first towards the
2558              * min number of characters needed.  This is done through the
2559              * variable 'foldlen', which is returned by the macros that look
2560              * for these sequences as the number of bytes the sequence
2561              * occupies.  Each time through the loop, we decrement 'foldlen' by
2562              * how many bytes the current char occupies.  Only when it reaches
2563              * 0 do we increment 'minchars' or look for another multi-character
2564              * sequence. */
2565             if (folder == NULL) {
2566                 minchars++;
2567             }
2568             else if (foldlen > 0) {
2569                 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2570             }
2571             else {
2572                 minchars++;
2573
2574                 /* See if *uc is the beginning of a multi-character fold.  If
2575                  * so, we decrement the length remaining to look at, to account
2576                  * for the current character this iteration.  (We can use 'uc'
2577                  * instead of the fold returned by TRIE_READ_CHAR because for
2578                  * non-UTF, the latin1_safe macro is smart enough to account
2579                  * for all the unfolded characters, and because for UTF, the
2580                  * string will already have been folded earlier in the
2581                  * compilation process */
2582                 if (UTF) {
2583                     if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2584                         foldlen -= UTF8SKIP(uc);
2585                     }
2586                 }
2587                 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2588                     foldlen--;
2589                 }
2590             }
2591
2592             /* The current character (and any potential folds) should be added
2593              * to the possible matching characters for this position in this
2594              * branch */
2595             if ( uvc < 256 ) {
2596                 if ( folder ) {
2597                     U8 folded= folder[ (U8) uvc ];
2598                     if ( !trie->charmap[ folded ] ) {
2599                         trie->charmap[ folded ]=( ++trie->uniquecharcount );
2600                         TRIE_STORE_REVCHAR( folded );
2601                     }
2602                 }
2603                 if ( !trie->charmap[ uvc ] ) {
2604                     trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2605                     TRIE_STORE_REVCHAR( uvc );
2606                 }
2607                 if ( set_bit ) {
2608                     /* store the codepoint in the bitmap, and its folded
2609                      * equivalent. */
2610                     TRIE_BITMAP_SET(trie, uvc);
2611
2612                     /* store the folded codepoint */
2613                     if ( folder ) TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);
2614
2615                     if ( !UTF ) {
2616                         /* store first byte of utf8 representation of
2617                            variant codepoints */
2618                         if (! UVCHR_IS_INVARIANT(uvc)) {
2619                             TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
2620                         }
2621                     }
2622                     set_bit = 0; /* We've done our bit :-) */
2623                 }
2624             } else {
2625
2626                 /* XXX We could come up with the list of code points that fold
2627                  * to this using PL_utf8_foldclosures, except not for
2628                  * multi-char folds, as there may be multiple combinations
2629                  * there that could work, which needs to wait until runtime to
2630                  * resolve (The comment about LIGATURE FFI above is such an
2631                  * example */
2632
2633                 SV** svpp;
2634                 if ( !widecharmap )
2635                     widecharmap = newHV();
2636
2637                 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2638
2639                 if ( !svpp )
2640                     Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
2641
2642                 if ( !SvTRUE( *svpp ) ) {
2643                     sv_setiv( *svpp, ++trie->uniquecharcount );
2644                     TRIE_STORE_REVCHAR(uvc);
2645                 }
2646             }
2647         } /* end loop through characters in this branch of the trie */
2648
2649         /* We take the min and max for this branch and combine to find the min
2650          * and max for all branches processed so far */
2651         if( cur == first ) {
2652             trie->minlen = minchars;
2653             trie->maxlen = maxchars;
2654         } else if (minchars < trie->minlen) {
2655             trie->minlen = minchars;
2656         } else if (maxchars > trie->maxlen) {
2657             trie->maxlen = maxchars;
2658         }
2659     } /* end first pass */
2660     DEBUG_TRIE_COMPILE_r(
2661         PerlIO_printf( Perl_debug_log,
2662                 "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2663                 (int)depth * 2 + 2,"",
2664                 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2665                 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2666                 (int)trie->minlen, (int)trie->maxlen )
2667     );
2668
2669     /*
2670         We now know what we are dealing with in terms of unique chars and
2671         string sizes so we can calculate how much memory a naive
2672         representation using a flat table  will take. If it's over a reasonable
2673         limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2674         conservative but potentially much slower representation using an array
2675         of lists.
2676
2677         At the end we convert both representations into the same compressed
2678         form that will be used in regexec.c for matching with. The latter
2679         is a form that cannot be used to construct with but has memory
2680         properties similar to the list form and access properties similar
2681         to the table form making it both suitable for fast searches and
2682         small enough that its feasable to store for the duration of a program.
2683
2684         See the comment in the code where the compressed table is produced
2685         inplace from the flat tabe representation for an explanation of how
2686         the compression works.
2687
2688     */
2689
2690
2691     Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2692     prev_states[1] = 0;
2693
2694     if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2695                                                     > SvIV(re_trie_maxbuff) )
2696     {
2697         /*
2698             Second Pass -- Array Of Lists Representation
2699
2700             Each state will be represented by a list of charid:state records
2701             (reg_trie_trans_le) the first such element holds the CUR and LEN
2702             points of the allocated array. (See defines above).
2703
2704             We build the initial structure using the lists, and then convert
2705             it into the compressed table form which allows faster lookups
2706             (but cant be modified once converted).
2707         */
2708
2709         STRLEN transcount = 1;
2710
2711         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
2712             "%*sCompiling trie using list compiler\n",
2713             (int)depth * 2 + 2, ""));
2714
2715         trie->states = (reg_trie_state *)
2716             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2717                                   sizeof(reg_trie_state) );
2718         TRIE_LIST_NEW(1);
2719         next_alloc = 2;
2720
2721         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2722
2723             regnode *noper   = NEXTOPER( cur );
2724             U8 *uc           = (U8*)STRING( noper );
2725             const U8 *e      = uc + STR_LEN( noper );
2726             U32 state        = 1;         /* required init */
2727             U16 charid       = 0;         /* sanity init */
2728             U32 wordlen      = 0;         /* required init */
2729
2730             if (OP(noper) == NOTHING) {
2731                 regnode *noper_next= regnext(noper);
2732                 if (noper_next != tail && OP(noper_next) == flags) {
2733                     noper = noper_next;
2734                     uc= (U8*)STRING(noper);
2735                     e= uc + STR_LEN(noper);
2736                 }
2737             }
2738
2739             if (OP(noper) != NOTHING) {
2740                 for ( ; uc < e ; uc += len ) {
2741
2742                     TRIE_READ_CHAR;
2743
2744                     if ( uvc < 256 ) {
2745                         charid = trie->charmap[ uvc ];
2746                     } else {
2747                         SV** const svpp = hv_fetch( widecharmap,
2748                                                     (char*)&uvc,
2749                                                     sizeof( UV ),
2750                                                     0);
2751                         if ( !svpp ) {
2752                             charid = 0;
2753                         } else {
2754                             charid=(U16)SvIV( *svpp );
2755                         }
2756                     }
2757                     /* charid is now 0 if we dont know the char read, or
2758                      * nonzero if we do */
2759                     if ( charid ) {
2760
2761                         U16 check;
2762                         U32 newstate = 0;
2763
2764                         charid--;
2765                         if ( !trie->states[ state ].trans.list ) {
2766                             TRIE_LIST_NEW( state );
2767                         }
2768                         for ( check = 1;
2769                               check <= TRIE_LIST_USED( state );
2770                               check++ )
2771                         {
2772                             if ( TRIE_LIST_ITEM( state, check ).forid
2773                                                                     == charid )
2774                             {
2775                                 newstate = TRIE_LIST_ITEM( state, check ).newstate;
2776                                 break;
2777                             }
2778                         }
2779                         if ( ! newstate ) {
2780                             newstate = next_alloc++;
2781                             prev_states[newstate] = state;
2782                             TRIE_LIST_PUSH( state, charid, newstate );
2783                             transcount++;
2784                         }
2785                         state = newstate;
2786                     } else {
2787                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2788                     }
2789                 }
2790             }
2791             TRIE_HANDLE_WORD(state);
2792
2793         } /* end second pass */
2794
2795         /* next alloc is the NEXT state to be allocated */
2796         trie->statecount = next_alloc;
2797         trie->states = (reg_trie_state *)
2798             PerlMemShared_realloc( trie->states,
2799                                    next_alloc
2800                                    * sizeof(reg_trie_state) );
2801
2802         /* and now dump it out before we compress it */
2803         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
2804                                                          revcharmap, next_alloc,
2805                                                          depth+1)
2806         );
2807
2808         trie->trans = (reg_trie_trans *)
2809             PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
2810         {
2811             U32 state;
2812             U32 tp = 0;
2813             U32 zp = 0;
2814
2815
2816             for( state=1 ; state < next_alloc ; state ++ ) {
2817                 U32 base=0;
2818
2819                 /*
2820                 DEBUG_TRIE_COMPILE_MORE_r(
2821                     PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
2822                 );
2823                 */
2824
2825                 if (trie->states[state].trans.list) {
2826                     U16 minid=TRIE_LIST_ITEM( state, 1).forid;
2827                     U16 maxid=minid;
2828                     U16 idx;
2829
2830                     for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
2831                         const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
2832                         if ( forid < minid ) {
2833                             minid=forid;
2834                         } else if ( forid > maxid ) {
2835                             maxid=forid;
2836                         }
2837                     }
2838                     if ( transcount < tp + maxid - minid + 1) {
2839                         transcount *= 2;
2840                         trie->trans = (reg_trie_trans *)
2841                             PerlMemShared_realloc( trie->trans,
2842                                                      transcount
2843                                                      * sizeof(reg_trie_trans) );
2844                         Zero( trie->trans + (transcount / 2),
2845                               transcount / 2,
2846                               reg_trie_trans );
2847                     }
2848                     base = trie->uniquecharcount + tp - minid;
2849                     if ( maxid == minid ) {
2850                         U32 set = 0;
2851                         for ( ; zp < tp ; zp++ ) {
2852                             if ( ! trie->trans[ zp ].next ) {
2853                                 base = trie->uniquecharcount + zp - minid;
2854                                 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
2855                                                                    1).newstate;
2856                                 trie->trans[ zp ].check = state;
2857                                 set = 1;
2858                                 break;
2859                             }
2860                         }
2861                         if ( !set ) {
2862                             trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
2863                                                                    1).newstate;
2864                             trie->trans[ tp ].check = state;
2865                             tp++;
2866                             zp = tp;
2867                         }
2868                     } else {
2869                         for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
2870                             const U32 tid = base
2871                                            - trie->uniquecharcount
2872                                            + TRIE_LIST_ITEM( state, idx ).forid;
2873                             trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
2874                                                                 idx ).newstate;
2875                             trie->trans[ tid ].check = state;
2876                         }
2877                         tp += ( maxid - minid + 1 );
2878                     }
2879                     Safefree(trie->states[ state ].trans.list);
2880                 }
2881                 /*
2882                 DEBUG_TRIE_COMPILE_MORE_r(
2883                     PerlIO_printf( Perl_debug_log, " base: %d\n",base);
2884                 );
2885                 */
2886                 trie->states[ state ].trans.base=base;
2887             }
2888             trie->lasttrans = tp + 1;
2889         }
2890     } else {
2891         /*
2892            Second Pass -- Flat Table Representation.
2893
2894            we dont use the 0 slot of either trans[] or states[] so we add 1 to
2895            each.  We know that we will need Charcount+1 trans at most to store
2896            the data (one row per char at worst case) So we preallocate both
2897            structures assuming worst case.
2898
2899            We then construct the trie using only the .next slots of the entry
2900            structs.
2901
2902            We use the .check field of the first entry of the node temporarily
2903            to make compression both faster and easier by keeping track of how
2904            many non zero fields are in the node.
2905
2906            Since trans are numbered from 1 any 0 pointer in the table is a FAIL
2907            transition.
2908
2909            There are two terms at use here: state as a TRIE_NODEIDX() which is
2910            a number representing the first entry of the node, and state as a
2911            TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
2912            and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
2913            if there are 2 entrys per node. eg:
2914
2915              A B       A B
2916           1. 2 4    1. 3 7
2917           2. 0 3    3. 0 5
2918           3. 0 0    5. 0 0
2919           4. 0 0    7. 0 0
2920
2921            The table is internally in the right hand, idx form. However as we
2922            also have to deal with the states array which is indexed by nodenum
2923            we have to use TRIE_NODENUM() to convert.
2924
2925         */
2926         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
2927             "%*sCompiling trie using table compiler\n",
2928             (int)depth * 2 + 2, ""));
2929
2930         trie->trans = (reg_trie_trans *)
2931             PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
2932                                   * trie->uniquecharcount + 1,
2933                                   sizeof(reg_trie_trans) );
2934         trie->states = (reg_trie_state *)
2935             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2936                                   sizeof(reg_trie_state) );
2937         next_alloc = trie->uniquecharcount + 1;
2938
2939
2940         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2941
2942             regnode *noper   = NEXTOPER( cur );
2943             const U8 *uc     = (U8*)STRING( noper );
2944             const U8 *e      = uc + STR_LEN( noper );
2945
2946             U32 state        = 1;         /* required init */
2947
2948             U16 charid       = 0;         /* sanity init */
2949             U32 accept_state = 0;         /* sanity init */
2950
2951             U32 wordlen      = 0;         /* required init */
2952
2953             if (OP(noper) == NOTHING) {
2954                 regnode *noper_next= regnext(noper);
2955                 if (noper_next != tail && OP(noper_next) == flags) {
2956                     noper = noper_next;
2957                     uc= (U8*)STRING(noper);
2958                     e= uc + STR_LEN(noper);
2959                 }
2960             }
2961
2962             if ( OP(noper) != NOTHING ) {
2963                 for ( ; uc < e ; uc += len ) {
2964
2965                     TRIE_READ_CHAR;
2966
2967                     if ( uvc < 256 ) {
2968                         charid = trie->charmap[ uvc ];
2969                     } else {
2970                         SV* const * const svpp = hv_fetch( widecharmap,
2971                                                            (char*)&uvc,
2972                                                            sizeof( UV ),
2973                                                            0);
2974                         charid = svpp ? (U16)SvIV(*svpp) : 0;
2975                     }
2976                     if ( charid ) {
2977                         charid--;
2978                         if ( !trie->trans[ state + charid ].next ) {
2979                             trie->trans[ state + charid ].next = next_alloc;
2980                             trie->trans[ state ].check++;
2981                             prev_states[TRIE_NODENUM(next_alloc)]
2982                                     = TRIE_NODENUM(state);
2983                             next_alloc += trie->uniquecharcount;
2984                         }
2985                         state = trie->trans[ state + charid ].next;
2986                     } else {
2987                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2988                     }
2989                     /* charid is now 0 if we dont know the char read, or
2990                      * nonzero if we do */
2991                 }
2992             }
2993             accept_state = TRIE_NODENUM( state );
2994             TRIE_HANDLE_WORD(accept_state);
2995
2996         } /* end second pass */
2997
2998         /* and now dump it out before we compress it */
2999         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3000                                                           revcharmap,
3001                                                           next_alloc, depth+1));
3002
3003         {
3004         /*
3005            * Inplace compress the table.*
3006
3007            For sparse data sets the table constructed by the trie algorithm will
3008            be mostly 0/FAIL transitions or to put it another way mostly empty.
3009            (Note that leaf nodes will not contain any transitions.)
3010
3011            This algorithm compresses the tables by eliminating most such
3012            transitions, at the cost of a modest bit of extra work during lookup:
3013
3014            - Each states[] entry contains a .base field which indicates the
3015            index in the state[] array wheres its transition data is stored.
3016
3017            - If .base is 0 there are no valid transitions from that node.
3018
3019            - If .base is nonzero then charid is added to it to find an entry in
3020            the trans array.
3021
3022            -If trans[states[state].base+charid].check!=state then the
3023            transition is taken to be a 0/Fail transition. Thus if there are fail
3024            transitions at the front of the node then the .base offset will point
3025            somewhere inside the previous nodes data (or maybe even into a node
3026            even earlier), but the .check field determines if the transition is
3027            valid.
3028
3029            XXX - wrong maybe?
3030            The following process inplace converts the table to the compressed
3031            table: We first do not compress the root node 1,and mark all its
3032            .check pointers as 1 and set its .base pointer as 1 as well. This
3033            allows us to do a DFA construction from the compressed table later,
3034            and ensures that any .base pointers we calculate later are greater
3035            than 0.
3036
3037            - We set 'pos' to indicate the first entry of the second node.
3038
3039            - We then iterate over the columns of the node, finding the first and
3040            last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3041            and set the .check pointers accordingly, and advance pos
3042            appropriately and repreat for the next node. Note that when we copy
3043            the next pointers we have to convert them from the original
3044            NODEIDX form to NODENUM form as the former is not valid post
3045            compression.
3046
3047            - If a node has no transitions used we mark its base as 0 and do not
3048            advance the pos pointer.
3049
3050            - If a node only has one transition we use a second pointer into the
3051            structure to fill in allocated fail transitions from other states.
3052            This pointer is independent of the main pointer and scans forward
3053            looking for null transitions that are allocated to a state. When it
3054            finds one it writes the single transition into the "hole".  If the
3055            pointer doesnt find one the single transition is appended as normal.
3056
3057            - Once compressed we can Renew/realloc the structures to release the
3058            excess space.
3059
3060            See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3061            specifically Fig 3.47 and the associated pseudocode.
3062
3063            demq
3064         */
3065         const U32 laststate = TRIE_NODENUM( next_alloc );
3066         U32 state, charid;
3067         U32 pos = 0, zp=0;
3068         trie->statecount = laststate;
3069
3070         for ( state = 1 ; state < laststate ; state++ ) {
3071             U8 flag = 0;
3072             const U32 stateidx = TRIE_NODEIDX( state );
3073             const U32 o_used = trie->trans[ stateidx ].check;
3074             U32 used = trie->trans[ stateidx ].check;
3075             trie->trans[ stateidx ].check = 0;
3076
3077             for ( charid = 0;
3078                   used && charid < trie->uniquecharcount;
3079                   charid++ )
3080             {
3081                 if ( flag || trie->trans[ stateidx + charid ].next ) {
3082                     if ( trie->trans[ stateidx + charid ].next ) {
3083                         if (o_used == 1) {
3084                             for ( ; zp < pos ; zp++ ) {
3085                                 if ( ! trie->trans[ zp ].next ) {
3086                                     break;
3087                                 }
3088                             }
3089                             trie->states[ state ].trans.base
3090                                                     = zp
3091                                                       + trie->uniquecharcount
3092                                                       - charid ;
3093                             trie->trans[ zp ].next
3094                                 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3095                                                              + charid ].next );
3096                             trie->trans[ zp ].check = state;
3097                             if ( ++zp > pos ) pos = zp;
3098                             break;
3099                         }
3100                         used--;
3101                     }
3102                     if ( !flag ) {
3103                         flag = 1;
3104                         trie->states[ state ].trans.base
3105                                        = pos + trie->uniquecharcount - charid ;
3106                     }
3107                     trie->trans[ pos ].next
3108                         = SAFE_TRIE_NODENUM(
3109                                        trie->trans[ stateidx + charid ].next );
3110                     trie->trans[ pos ].check = state;
3111                     pos++;
3112                 }
3113             }
3114         }
3115         trie->lasttrans = pos + 1;
3116         trie->states = (reg_trie_state *)
3117             PerlMemShared_realloc( trie->states, laststate
3118                                    * sizeof(reg_trie_state) );
3119         DEBUG_TRIE_COMPILE_MORE_r(
3120             PerlIO_printf( Perl_debug_log,
3121                 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
3122                 (int)depth * 2 + 2,"",
3123                 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3124                        + 1 ),
3125                 (IV)next_alloc,
3126                 (IV)pos,
3127                 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3128             );
3129
3130         } /* end table compress */
3131     }
3132     DEBUG_TRIE_COMPILE_MORE_r(
3133             PerlIO_printf(Perl_debug_log,
3134                 "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
3135                 (int)depth * 2 + 2, "",
3136                 (UV)trie->statecount,
3137                 (UV)trie->lasttrans)
3138     );
3139     /* resize the trans array to remove unused space */
3140     trie->trans = (reg_trie_trans *)
3141         PerlMemShared_realloc( trie->trans, trie->lasttrans
3142                                * sizeof(reg_trie_trans) );
3143
3144     {   /* Modify the program and insert the new TRIE node */
3145         U8 nodetype =(U8)(flags & 0xFF);
3146         char *str=NULL;
3147
3148 #ifdef DEBUGGING
3149         regnode *optimize = NULL;
3150 #ifdef RE_TRACK_PATTERN_OFFSETS
3151
3152         U32 mjd_offset = 0;
3153         U32 mjd_nodelen = 0;
3154 #endif /* RE_TRACK_PATTERN_OFFSETS */
3155 #endif /* DEBUGGING */
3156         /*
3157            This means we convert either the first branch or the first Exact,
3158            depending on whether the thing following (in 'last') is a branch
3159            or not and whther first is the startbranch (ie is it a sub part of
3160            the alternation or is it the whole thing.)
3161            Assuming its a sub part we convert the EXACT otherwise we convert
3162            the whole branch sequence, including the first.
3163          */
3164         /* Find the node we are going to overwrite */
3165         if ( first != startbranch || OP( last ) == BRANCH ) {
3166             /* branch sub-chain */
3167             NEXT_OFF( first ) = (U16)(last - first);
3168 #ifdef RE_TRACK_PATTERN_OFFSETS
3169             DEBUG_r({
3170                 mjd_offset= Node_Offset((convert));
3171                 mjd_nodelen= Node_Length((convert));
3172             });
3173 #endif
3174             /* whole branch chain */
3175         }
3176 #ifdef RE_TRACK_PATTERN_OFFSETS
3177         else {
3178             DEBUG_r({
3179                 const  regnode *nop = NEXTOPER( convert );
3180                 mjd_offset= Node_Offset((nop));
3181                 mjd_nodelen= Node_Length((nop));
3182             });
3183         }
3184         DEBUG_OPTIMISE_r(
3185             PerlIO_printf(Perl_debug_log,
3186                 "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
3187                 (int)depth * 2 + 2, "",
3188                 (UV)mjd_offset, (UV)mjd_nodelen)
3189         );
3190 #endif
3191         /* But first we check to see if there is a common prefix we can
3192            split out as an EXACT and put in front of the TRIE node.  */
3193         trie->startstate= 1;
3194         if ( trie->bitmap && !widecharmap && !trie->jump  ) {
3195             U32 state;
3196             for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3197                 U32 ofs = 0;
3198                 I32 idx = -1;
3199                 U32 count = 0;
3200                 const U32 base = trie->states[ state ].trans.base;
3201
3202                 if ( trie->states[state].wordnum )
3203                         count = 1;
3204
3205                 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3206                     if ( ( base + ofs >= trie->uniquecharcount ) &&
3207                          ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3208                          trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3209                     {
3210                         if ( ++count > 1 ) {
3211                             SV **tmp = av_fetch( revcharmap, ofs, 0);
3212                             const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
3213                             if ( state == 1 ) break;
3214                             if ( count == 2 ) {
3215                                 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3216                                 DEBUG_OPTIMISE_r(
3217                                     PerlIO_printf(Perl_debug_log,
3218                                         "%*sNew Start State=%"UVuf" Class: [",
3219                                         (int)depth * 2 + 2, "",
3220                                         (UV)state));
3221                                 if (idx >= 0) {
3222                                     SV ** const tmp = av_fetch( revcharmap, idx, 0);
3223                                     const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3224
3225                                     TRIE_BITMAP_SET(trie,*ch);
3226                                     if ( folder )
3227                                         TRIE_BITMAP_SET(trie, folder[ *ch ]);
3228                                     DEBUG_OPTIMISE_r(
3229                                         PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
3230                                     );
3231                                 }
3232                             }
3233                             TRIE_BITMAP_SET(trie,*ch);
3234                             if ( folder )
3235                                 TRIE_BITMAP_SET(trie,folder[ *ch ]);
3236                             DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
3237                         }
3238                         idx = ofs;
3239                     }
3240                 }
3241                 if ( count == 1 ) {
3242                     SV **tmp = av_fetch( revcharmap, idx, 0);
3243                     STRLEN len;
3244                     char *ch = SvPV( *tmp, len );
3245                     DEBUG_OPTIMISE_r({
3246                         SV *sv=sv_newmortal();
3247                         PerlIO_printf( Perl_debug_log,
3248                             "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
3249                             (int)depth * 2 + 2, "",
3250                             (UV)state, (UV)idx,
3251                             pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3252                                 PL_colors[0], PL_colors[1],
3253                                 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3254                                 PERL_PV_ESCAPE_FIRSTCHAR
3255                             )
3256                         );
3257                     });
3258                     if ( state==1 ) {
3259                         OP( convert ) = nodetype;
3260                         str=STRING(convert);
3261                         STR_LEN(convert)=0;
3262                     }
3263                     STR_LEN(convert) += len;
3264                     while (len--)
3265                         *str++ = *ch++;
3266                 } else {
3267 #ifdef DEBUGGING
3268                     if (state>1)
3269                         DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
3270 #endif
3271                     break;
3272                 }
3273             }
3274             trie->prefixlen = (state-1);
3275             if (str) {
3276                 regnode *n = convert+NODE_SZ_STR(convert);
3277                 NEXT_OFF(convert) = NODE_SZ_STR(convert);
3278                 trie->startstate = state;
3279                 trie->minlen -= (state - 1);
3280                 trie->maxlen -= (state - 1);
3281 #ifdef DEBUGGING
3282                /* At least the UNICOS C compiler choked on this
3283                 * being argument to DEBUG_r(), so let's just have
3284                 * it right here. */
3285                if (
3286 #ifdef PERL_EXT_RE_BUILD
3287                    1
3288 #else
3289                    DEBUG_r_TEST
3290 #endif
3291                    ) {
3292                    regnode *fix = convert;
3293                    U32 word = trie->wordcount;
3294                    mjd_nodelen++;
3295                    Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3296                    while( ++fix < n ) {
3297                        Set_Node_Offset_Length(fix, 0, 0);
3298                    }
3299                    while (word--) {
3300                        SV ** const tmp = av_fetch( trie_words, word, 0 );
3301                        if (tmp) {
3302                            if ( STR_LEN(convert) <= SvCUR(*tmp) )
3303                                sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3304                            else
3305                                sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3306                        }
3307                    }
3308                }
3309 #endif
3310                 if (trie->maxlen) {
3311                     convert = n;
3312                 } else {
3313                     NEXT_OFF(convert) = (U16)(tail - convert);
3314                     DEBUG_r(optimize= n);
3315                 }
3316             }
3317         }
3318         if (!jumper)
3319             jumper = last;
3320         if ( trie->maxlen ) {
3321             NEXT_OFF( convert ) = (U16)(tail - convert);
3322             ARG_SET( convert, data_slot );
3323             /* Store the offset to the first unabsorbed branch in
3324                jump[0], which is otherwise unused by the jump logic.
3325                We use this when dumping a trie and during optimisation. */
3326             if (trie->jump)
3327                 trie->jump[0] = (U16)(nextbranch - convert);
3328
3329             /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3330              *   and there is a bitmap
3331              *   and the first "jump target" node we found leaves enough room
3332              * then convert the TRIE node into a TRIEC node, with the bitmap
3333              * embedded inline in the opcode - this is hypothetically faster.
3334              */
3335             if ( !trie->states[trie->startstate].wordnum
3336                  && trie->bitmap
3337                  && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3338             {
3339                 OP( convert ) = TRIEC;
3340                 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3341                 PerlMemShared_free(trie->bitmap);
3342                 trie->bitmap= NULL;
3343             } else
3344                 OP( convert ) = TRIE;
3345
3346             /* store the type in the flags */
3347             convert->flags = nodetype;
3348             DEBUG_r({
3349             optimize = convert
3350                       + NODE_STEP_REGNODE
3351                       + regarglen[ OP( convert ) ];
3352             });
3353             /* XXX We really should free up the resource in trie now,
3354                    as we won't use them - (which resources?) dmq */
3355         }
3356         /* needed for dumping*/
3357         DEBUG_r(if (optimize) {
3358             regnode *opt = convert;
3359
3360             while ( ++opt < optimize) {
3361                 Set_Node_Offset_Length(opt,0,0);
3362             }
3363             /*
3364                 Try to clean up some of the debris left after the
3365                 optimisation.
3366              */
3367             while( optimize < jumper ) {
3368                 mjd_nodelen += Node_Length((optimize));
3369                 OP( optimize ) = OPTIMIZED;
3370                 Set_Node_Offset_Length(optimize,0,0);
3371                 optimize++;
3372             }
3373             Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
3374         });
3375     } /* end node insert */
3376
3377     /*  Finish populating the prev field of the wordinfo array.  Walk back
3378      *  from each accept state until we find another accept state, and if
3379      *  so, point the first word's .prev field at the second word. If the
3380      *  second already has a .prev field set, stop now. This will be the
3381      *  case either if we've already processed that word's accept state,
3382      *  or that state had multiple words, and the overspill words were
3383      *  already linked up earlier.
3384      */
3385     {
3386         U16 word;
3387         U32 state;
3388         U16 prev;
3389
3390         for (word=1; word <= trie->wordcount; word++) {
3391             prev = 0;
3392             if (trie->wordinfo[word].prev)
3393                 continue;
3394             state = trie->wordinfo[word].accept;
3395             while (state) {
3396                 state = prev_states[state];
3397                 if (!state)
3398                     break;
3399                 prev = trie->states[state].wordnum;
3400                 if (prev)
3401                     break;
3402             }
3403             trie->wordinfo[word].prev = prev;
3404         }
3405         Safefree(prev_states);
3406     }
3407
3408
3409     /* and now dump out the compressed format */
3410     DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3411
3412     RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3413 #ifdef DEBUGGING
3414     RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3415     RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3416 #else
3417     SvREFCNT_dec_NN(revcharmap);
3418 #endif
3419     return trie->jump
3420            ? MADE_JUMP_TRIE
3421            : trie->startstate>1
3422              ? MADE_EXACT_TRIE
3423              : MADE_TRIE;
3424 }
3425
3426 STATIC regnode *
3427 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3428 {
3429 /* The Trie is constructed and compressed now so we can build a fail array if
3430  * it's needed
3431
3432    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3433    3.32 in the
3434    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3435    Ullman 1985/88
3436    ISBN 0-201-10088-6
3437
3438    We find the fail state for each state in the trie, this state is the longest
3439    proper suffix of the current state's 'word' that is also a proper prefix of
3440    another word in our trie. State 1 represents the word '' and is thus the
3441    default fail state. This allows the DFA not to have to restart after its
3442    tried and failed a word at a given point, it simply continues as though it
3443    had been matching the other word in the first place.
3444    Consider
3445       'abcdgu'=~/abcdefg|cdgu/
3446    When we get to 'd' we are still matching the first word, we would encounter
3447    'g' which would fail, which would bring us to the state representing 'd' in
3448    the second word where we would try 'g' and succeed, proceeding to match
3449    'cdgu'.
3450  */
3451  /* add a fail transition */
3452     const U32 trie_offset = ARG(source);
3453     reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3454     U32 *q;
3455     const U32 ucharcount = trie->uniquecharcount;
3456     const U32 numstates = trie->statecount;
3457     const U32 ubound = trie->lasttrans + ucharcount;
3458     U32 q_read = 0;
3459     U32 q_write = 0;
3460     U32 charid;
3461     U32 base = trie->states[ 1 ].trans.base;
3462     U32 *fail;
3463     reg_ac_data *aho;
3464     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3465     regnode *stclass;
3466     GET_RE_DEBUG_FLAGS_DECL;
3467
3468     PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3469     PERL_UNUSED_CONTEXT;
3470 #ifndef DEBUGGING
3471     PERL_UNUSED_ARG(depth);
3472 #endif
3473
3474     if ( OP(source) == TRIE ) {
3475         struct regnode_1 *op = (struct regnode_1 *)
3476             PerlMemShared_calloc(1, sizeof(struct regnode_1));
3477         StructCopy(source,op,struct regnode_1);
3478         stclass = (regnode *)op;
3479     } else {
3480         struct regnode_charclass *op = (struct regnode_charclass *)
3481             PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3482         StructCopy(source,op,struct regnode_charclass);
3483         stclass = (regnode *)op;
3484     }
3485     OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3486
3487     ARG_SET( stclass, data_slot );
3488     aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3489     RExC_rxi->data->data[ data_slot ] = (void*)aho;
3490     aho->trie=trie_offset;
3491     aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3492     Copy( trie->states, aho->states, numstates, reg_trie_state );
3493     Newxz( q, numstates, U32);
3494     aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3495     aho->refcount = 1;
3496     fail = aho->fail;
3497     /* initialize fail[0..1] to be 1 so that we always have
3498        a valid final fail state */
3499     fail[ 0 ] = fail[ 1 ] = 1;
3500
3501     for ( charid = 0; charid < ucharcount ; charid++ ) {
3502         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3503         if ( newstate ) {
3504             q[ q_write ] = newstate;
3505             /* set to point at the root */
3506             fail[ q[ q_write++ ] ]=1;
3507         }
3508     }
3509     while ( q_read < q_write) {
3510         const U32 cur = q[ q_read++ % numstates ];
3511         base = trie->states[ cur ].trans.base;
3512
3513         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3514             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3515             if (ch_state) {
3516                 U32 fail_state = cur;
3517                 U32 fail_base;
3518                 do {
3519                     fail_state = fail[ fail_state ];
3520                     fail_base = aho->states[ fail_state ].trans.base;
3521                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3522
3523                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3524                 fail[ ch_state ] = fail_state;
3525                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3526                 {
3527                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
3528                 }
3529                 q[ q_write++ % numstates] = ch_state;
3530             }
3531         }
3532     }
3533     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3534        when we fail in state 1, this allows us to use the
3535        charclass scan to find a valid start char. This is based on the principle
3536        that theres a good chance the string being searched contains lots of stuff
3537        that cant be a start char.
3538      */
3539     fail[ 0 ] = fail[ 1 ] = 0;
3540     DEBUG_TRIE_COMPILE_r({
3541         PerlIO_printf(Perl_debug_log,
3542                       "%*sStclass Failtable (%"UVuf" states): 0",
3543                       (int)(depth * 2), "", (UV)numstates
3544         );
3545         for( q_read=1; q_read<numstates; q_read++ ) {
3546             PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
3547         }
3548         PerlIO_printf(Perl_debug_log, "\n");
3549     });
3550     Safefree(q);
3551     /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3552     return stclass;
3553 }
3554
3555
3556 #define DEBUG_PEEP(str,scan,depth) \
3557     DEBUG_OPTIMISE_r({if (scan){ \
3558        regnode *Next = regnext(scan); \
3559        regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state); \
3560        PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)", \
3561            (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),\
3562            Next ? (REG_NODE_NUM(Next)) : 0 ); \
3563        DEBUG_SHOW_STUDY_FLAGS(flags," [ ","]");\
3564        PerlIO_printf(Perl_debug_log, "\n"); \
3565    }});
3566
3567 /* The below joins as many adjacent EXACTish nodes as possible into a single
3568  * one.  The regop may be changed if the node(s) contain certain sequences that
3569  * require special handling.  The joining is only done if:
3570  * 1) there is room in the current conglomerated node to entirely contain the
3571  *    next one.
3572  * 2) they are the exact same node type
3573  *
3574  * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3575  * these get optimized out
3576  *
3577  * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3578  * as possible, even if that means splitting an existing node so that its first
3579  * part is moved to the preceeding node.  This would maximise the efficiency of
3580  * memEQ during matching.  Elsewhere in this file, khw proposes splitting
3581  * EXACTFish nodes into portions that don't change under folding vs those that
3582  * do.  Those portions that don't change may be the only things in the pattern that
3583  * could be used to find fixed and floating strings.
3584  *
3585  * If a node is to match under /i (folded), the number of characters it matches
3586  * can be different than its character length if it contains a multi-character
3587  * fold.  *min_subtract is set to the total delta number of characters of the
3588  * input nodes.
3589  *
3590  * And *unfolded_multi_char is set to indicate whether or not the node contains
3591  * an unfolded multi-char fold.  This happens when whether the fold is valid or
3592  * not won't be known until runtime; namely for EXACTF nodes that contain LATIN
3593  * SMALL LETTER SHARP S, as only if the target string being matched against
3594  * turns out to be UTF-8 is that fold valid; and also for EXACTFL nodes whose
3595  * folding rules depend on the locale in force at runtime.  (Multi-char folds
3596  * whose components are all above the Latin1 range are not run-time locale
3597  * dependent, and have already been folded by the time this function is
3598  * called.)
3599  *
3600  * This is as good a place as any to discuss the design of handling these
3601  * multi-character fold sequences.  It's been wrong in Perl for a very long
3602  * time.  There are three code points in Unicode whose multi-character folds
3603  * were long ago discovered to mess things up.  The previous designs for
3604  * dealing with these involved assigning a special node for them.  This
3605  * approach doesn't always work, as evidenced by this example:
3606  *      "\xDFs" =~ /s\xDF/ui    # Used to fail before these patches
3607  * Both sides fold to "sss", but if the pattern is parsed to create a node that
3608  * would match just the \xDF, it won't be able to handle the case where a
3609  * successful match would have to cross the node's boundary.  The new approach
3610  * that hopefully generally solves the problem generates an EXACTFU_SS node
3611  * that is "sss" in this case.
3612  *
3613  * It turns out that there are problems with all multi-character folds, and not
3614  * just these three.  Now the code is general, for all such cases.  The
3615  * approach taken is:
3616  * 1)   This routine examines each EXACTFish node that could contain multi-
3617  *      character folded sequences.  Since a single character can fold into
3618  *      such a sequence, the minimum match length for this node is less than
3619  *      the number of characters in the node.  This routine returns in
3620  *      *min_subtract how many characters to subtract from the the actual
3621  *      length of the string to get a real minimum match length; it is 0 if
3622  *      there are no multi-char foldeds.  This delta is used by the caller to
3623  *      adjust the min length of the match, and the delta between min and max,
3624  *      so that the optimizer doesn't reject these possibilities based on size
3625  *      constraints.
3626  * 2)   For the sequence involving the Sharp s (\xDF), the node type EXACTFU_SS
3627  *      is used for an EXACTFU node that contains at least one "ss" sequence in
3628  *      it.  For non-UTF-8 patterns and strings, this is the only case where
3629  *      there is a possible fold length change.  That means that a regular
3630  *      EXACTFU node without UTF-8 involvement doesn't have to concern itself
3631  *      with length changes, and so can be processed faster.  regexec.c takes
3632  *      advantage of this.  Generally, an EXACTFish node that is in UTF-8 is
3633  *      pre-folded by regcomp.c (except EXACTFL, some of whose folds aren't
3634  *      known until runtime).  This saves effort in regex matching.  However,
3635  *      the pre-folding isn't done for non-UTF8 patterns because the fold of
3636  *      the MICRO SIGN requires UTF-8, and we don't want to slow things down by
3637  *      forcing the pattern into UTF8 unless necessary.  Also what EXACTF (and,
3638  *      again, EXACTFL) nodes fold to isn't known until runtime.  The fold
3639  *      possibilities for the non-UTF8 patterns are quite simple, except for
3640  *      the sharp s.  All the ones that don't involve a UTF-8 target string are
3641  *      members of a fold-pair, and arrays are set up for all of them so that
3642  *      the other member of the pair can be found quickly.  Code elsewhere in
3643  *      this file makes sure that in EXACTFU nodes, the sharp s gets folded to
3644  *      'ss', even if the pattern isn't UTF-8.  This avoids the issues
3645  *      described in the next item.
3646  * 3)   A problem remains for unfolded multi-char folds. (These occur when the
3647  *      validity of the fold won't be known until runtime, and so must remain
3648  *      unfolded for now.  This happens for the sharp s in EXACTF and EXACTFA
3649  *      nodes when the pattern isn't in UTF-8.  (Note, BTW, that there cannot
3650  *      be an EXACTF node with a UTF-8 pattern.)  They also occur for various
3651  *      folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3652  *      The reason this is a problem is that the optimizer part of regexec.c
3653  *      (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3654  *      that a character in the pattern corresponds to at most a single
3655  *      character in the target string.  (And I do mean character, and not byte
3656  *      here, unlike other parts of the documentation that have never been
3657  *      updated to account for multibyte Unicode.)  sharp s in EXACTF and
3658  *      EXACTFL nodes can match the two character string 'ss'; in EXACTFA nodes
3659  *      it can match "\x{17F}\x{17F}".  These, along with other ones in EXACTFL
3660  *      nodes, violate the assumption, and they are the only instances where it
3661  *      is violated.  I'm reluctant to try to change the assumption, as the
3662  *      code involved is impenetrable to me (khw), so instead the code here
3663  *      punts.  This routine examines EXACTFL nodes, and (when the pattern
3664  *      isn't UTF-8) EXACTF and EXACTFA for such unfolded folds, and returns a
3665  *      boolean indicating whether or not the node contains such a fold.  When
3666  *      it is true, the caller sets a flag that later causes the optimizer in
3667  *      this file to not set values for the floating and fixed string lengths,
3668  *      and thus avoids the optimizer code in regexec.c that makes the invalid
3669  *      assumption.  Thus, there is no optimization based on string lengths for
3670  *      EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3671  *      EXACTF and EXACTFA nodes that contain the sharp s.  (The reason the
3672  *      assumption is wrong only in these cases is that all other non-UTF-8
3673  *      folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3674  *      their expanded versions.  (Again, we can't prefold sharp s to 'ss' in
3675  *      EXACTF nodes because we don't know at compile time if it actually
3676  *      matches 'ss' or not.  For EXACTF nodes it will match iff the target
3677  *      string is in UTF-8.  This is in contrast to EXACTFU nodes, where it
3678  *      always matches; and EXACTFA where it never does.  In an EXACTFA node in
3679  *      a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3680  *      problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3681  *      string would require the pattern to be forced into UTF-8, the overhead
3682  *      of which we want to avoid.  Similarly the unfolded multi-char folds in
3683  *      EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3684  *      locale.)
3685  *
3686  *      Similarly, the code that generates tries doesn't currently handle
3687  *      not-already-folded multi-char folds, and it looks like a pain to change
3688  *      that.  Therefore, trie generation of EXACTFA nodes with the sharp s
3689  *      doesn't work.  Instead, such an EXACTFA is turned into a new regnode,
3690  *      EXACTFA_NO_TRIE, which the trie code knows not to handle.  Most people
3691  *      using /iaa matching will be doing so almost entirely with ASCII
3692  *      strings, so this should rarely be encountered in practice */
3693
3694 #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
3695     if (PL_regkind[OP(scan)] == EXACT) \
3696         join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags),NULL,depth+1)
3697
3698 STATIC U32
3699 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
3700                    UV *min_subtract, bool *unfolded_multi_char,
3701                    U32 flags,regnode *val, U32 depth)
3702 {
3703     /* Merge several consecutive EXACTish nodes into one. */
3704     regnode *n = regnext(scan);
3705     U32 stringok = 1;
3706     regnode *next = scan + NODE_SZ_STR(scan);
3707     U32 merged = 0;
3708     U32 stopnow = 0;
3709 #ifdef DEBUGGING
3710     regnode *stop = scan;
3711     GET_RE_DEBUG_FLAGS_DECL;
3712 #else
3713     PERL_UNUSED_ARG(depth);
3714 #endif
3715
3716     PERL_ARGS_ASSERT_JOIN_EXACT;
3717 #ifndef EXPERIMENTAL_INPLACESCAN
3718     PERL_UNUSED_ARG(flags);
3719     PERL_UNUSED_ARG(val);
3720 #endif
3721     DEBUG_PEEP("join",scan,depth);
3722
3723     /* Look through the subsequent nodes in the chain.  Skip NOTHING, merge
3724      * EXACT ones that are mergeable to the current one. */
3725     while (n
3726            && (PL_regkind[OP(n)] == NOTHING
3727                || (stringok && OP(n) == OP(scan)))
3728            && NEXT_OFF(n)
3729            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
3730     {
3731
3732         if (OP(n) == TAIL || n > next)
3733             stringok = 0;
3734         if (PL_regkind[OP(n)] == NOTHING) {
3735             DEBUG_PEEP("skip:",n,depth);
3736             NEXT_OFF(scan) += NEXT_OFF(n);
3737             next = n + NODE_STEP_REGNODE;
3738 #ifdef DEBUGGING
3739             if (stringok)
3740                 stop = n;
3741 #endif
3742             n = regnext(n);
3743         }
3744         else if (stringok) {
3745             const unsigned int oldl = STR_LEN(scan);
3746             regnode * const nnext = regnext(n);
3747
3748             /* XXX I (khw) kind of doubt that this works on platforms (should
3749              * Perl ever run on one) where U8_MAX is above 255 because of lots
3750              * of other assumptions */
3751             /* Don't join if the sum can't fit into a single node */
3752             if (oldl + STR_LEN(n) > U8_MAX)
3753                 break;
3754
3755             DEBUG_PEEP("merg",n,depth);
3756             merged++;
3757
3758             NEXT_OFF(scan) += NEXT_OFF(n);
3759             STR_LEN(scan) += STR_LEN(n);
3760             next = n + NODE_SZ_STR(n);
3761             /* Now we can overwrite *n : */
3762             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
3763 #ifdef DEBUGGING
3764             stop = next - 1;
3765 #endif
3766             n = nnext;
3767             if (stopnow) break;
3768         }
3769
3770 #ifdef EXPERIMENTAL_INPLACESCAN
3771         if (flags && !NEXT_OFF(n)) {
3772             DEBUG_PEEP("atch", val, depth);
3773             if (reg_off_by_arg[OP(n)]) {
3774                 ARG_SET(n, val - n);
3775             }
3776             else {
3777                 NEXT_OFF(n) = val - n;
3778             }
3779             stopnow = 1;
3780         }
3781 #endif
3782     }
3783
3784     *min_subtract = 0;
3785     *unfolded_multi_char = FALSE;
3786
3787     /* Here, all the adjacent mergeable EXACTish nodes have been merged.  We
3788      * can now analyze for sequences of problematic code points.  (Prior to
3789      * this final joining, sequences could have been split over boundaries, and
3790      * hence missed).  The sequences only happen in folding, hence for any
3791      * non-EXACT EXACTish node */
3792     if (OP(scan) != EXACT && OP(scan) != EXACTL) {
3793         U8* s0 = (U8*) STRING(scan);
3794         U8* s = s0;
3795         U8* s_end = s0 + STR_LEN(scan);
3796
3797         int total_count_delta = 0;  /* Total delta number of characters that
3798                                        multi-char folds expand to */
3799
3800         /* One pass is made over the node's string looking for all the
3801          * possibilities.  To avoid some tests in the loop, there are two main
3802          * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
3803          * non-UTF-8 */
3804         if (UTF) {
3805             U8* folded = NULL;
3806
3807             if (OP(scan) == EXACTFL) {
3808                 U8 *d;
3809
3810                 /* An EXACTFL node would already have been changed to another
3811                  * node type unless there is at least one character in it that
3812                  * is problematic; likely a character whose fold definition
3813                  * won't be known until runtime, and so has yet to be folded.
3814                  * For all but the UTF-8 locale, folds are 1-1 in length, but
3815                  * to handle the UTF-8 case, we need to create a temporary
3816                  * folded copy using UTF-8 locale rules in order to analyze it.
3817                  * This is because our macros that look to see if a sequence is
3818                  * a multi-char fold assume everything is folded (otherwise the
3819                  * tests in those macros would be too complicated and slow).
3820                  * Note that here, the non-problematic folds will have already
3821                  * been done, so we can just copy such characters.  We actually
3822                  * don't completely fold the EXACTFL string.  We skip the
3823                  * unfolded multi-char folds, as that would just create work
3824                  * below to figure out the size they already are */
3825
3826                 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
3827                 d = folded;
3828                 while (s < s_end) {
3829                     STRLEN s_len = UTF8SKIP(s);
3830                     if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
3831                         Copy(s, d, s_len, U8);
3832                         d += s_len;
3833                     }
3834                     else if (is_FOLDS_TO_MULTI_utf8(s)) {
3835                         *unfolded_multi_char = TRUE;
3836                         Copy(s, d, s_len, U8);
3837                         d += s_len;
3838                     }
3839                     else if (isASCII(*s)) {
3840                         *(d++) = toFOLD(*s);
3841                     }
3842                     else {
3843                         STRLEN len;
3844                         _to_utf8_fold_flags(s, d, &len, FOLD_FLAGS_FULL);
3845                         d += len;
3846                     }
3847                     s += s_len;
3848                 }
3849
3850                 /* Point the remainder of the routine to look at our temporary
3851                  * folded copy */
3852                 s = folded;
3853                 s_end = d;
3854             } /* End of creating folded copy of EXACTFL string */
3855
3856             /* Examine the string for a multi-character fold sequence.  UTF-8
3857              * patterns have all characters pre-folded by the time this code is
3858              * executed */
3859             while (s < s_end - 1) /* Can stop 1 before the end, as minimum
3860                                      length sequence we are looking for is 2 */
3861             {
3862                 int count = 0;  /* How many characters in a multi-char fold */
3863                 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
3864                 if (! len) {    /* Not a multi-char fold: get next char */
3865                     s += UTF8SKIP(s);
3866                     continue;
3867                 }
3868
3869                 /* Nodes with 'ss' require special handling, except for
3870                  * EXACTFA-ish for which there is no multi-char fold to this */
3871                 if (len == 2 && *s == 's' && *(s+1) == 's'
3872                     && OP(scan) != EXACTFA
3873                     && OP(scan) != EXACTFA_NO_TRIE)
3874                 {
3875                     count = 2;
3876                     if (OP(scan) != EXACTFL) {
3877                         OP(scan) = EXACTFU_SS;
3878                     }
3879                     s += 2;
3880                 }
3881                 else { /* Here is a generic multi-char fold. */
3882                     U8* multi_end  = s + len;
3883
3884                     /* Count how many characters are in it.  In the case of
3885                      * /aa, no folds which contain ASCII code points are
3886                      * allowed, so check for those, and skip if found. */
3887                     if (OP(scan) != EXACTFA && OP(scan) != EXACTFA_NO_TRIE) {
3888                         count = utf8_length(s, multi_end);
3889                         s = multi_end;
3890                     }
3891                     else {
3892                         while (s < multi_end) {
3893                             if (isASCII(*s)) {
3894                                 s++;
3895                                 goto next_iteration;
3896                             }
3897                             else {
3898                                 s += UTF8SKIP(s);
3899                             }
3900                             count++;
3901                         }
3902                     }
3903                 }
3904
3905                 /* The delta is how long the sequence is minus 1 (1 is how long
3906                  * the character that folds to the sequence is) */
3907                 total_count_delta += count - 1;
3908               next_iteration: ;
3909             }
3910
3911             /* We created a temporary folded copy of the string in EXACTFL
3912              * nodes.  Therefore we need to be sure it doesn't go below zero,
3913              * as the real string could be shorter */
3914             if (OP(scan) == EXACTFL) {
3915                 int total_chars = utf8_length((U8*) STRING(scan),
3916                                            (U8*) STRING(scan) + STR_LEN(scan));
3917                 if (total_count_delta > total_chars) {
3918                     total_count_delta = total_chars;
3919                 }
3920             }
3921
3922             *min_subtract += total_count_delta;
3923             Safefree(folded);
3924         }
3925         else if (OP(scan) == EXACTFA) {
3926
3927             /* Non-UTF-8 pattern, EXACTFA node.  There can't be a multi-char
3928              * fold to the ASCII range (and there are no existing ones in the
3929              * upper latin1 range).  But, as outlined in the comments preceding
3930              * this function, we need to flag any occurrences of the sharp s.
3931              * This character forbids trie formation (because of added
3932              * complexity) */
3933 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
3934    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
3935                                       || UNICODE_DOT_DOT_VERSION > 0)
3936             while (s < s_end) {
3937                 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
3938                     OP(scan) = EXACTFA_NO_TRIE;
3939                     *unfolded_multi_char = TRUE;
3940                     break;
3941                 }
3942                 s++;
3943             }
3944         }
3945         else {
3946
3947             /* Non-UTF-8 pattern, not EXACTFA node.  Look for the multi-char
3948              * folds that are all Latin1.  As explained in the comments
3949              * preceding this function, we look also for the sharp s in EXACTF
3950              * and EXACTFL nodes; it can be in the final position.  Otherwise
3951              * we can stop looking 1 byte earlier because have to find at least
3952              * two characters for a multi-fold */
3953             const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
3954                               ? s_end
3955                               : s_end -1;
3956
3957             while (s < upper) {
3958                 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
3959                 if (! len) {    /* Not a multi-char fold. */
3960                     if (*s == LATIN_SMALL_LETTER_SHARP_S
3961                         && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
3962                     {
3963                         *unfolded_multi_char = TRUE;
3964                     }
3965                     s++;
3966                     continue;
3967                 }
3968
3969                 if (len == 2
3970                     && isALPHA_FOLD_EQ(*s, 's')
3971                     && isALPHA_FOLD_EQ(*(s+1), 's'))
3972                 {
3973