This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
regcomp.c: Add code to compute edit distance (Damerau–Levenshtein)
[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     U32         strict;
199 #ifdef ADD_TO_REGEXEC
200     char        *starttry;              /* -Dr: where regtry was called. */
201 #define RExC_starttry   (pRExC_state->starttry)
202 #endif
203     SV          *runtime_code_qr;       /* qr with the runtime code blocks */
204 #ifdef DEBUGGING
205     const char  *lastparse;
206     I32         lastnum;
207     AV          *paren_name_list;       /* idx -> name */
208     U32         study_chunk_recursed_count;
209     SV          *mysv1;
210     SV          *mysv2;
211 #define RExC_lastparse  (pRExC_state->lastparse)
212 #define RExC_lastnum    (pRExC_state->lastnum)
213 #define RExC_paren_name_list    (pRExC_state->paren_name_list)
214 #define RExC_study_chunk_recursed_count    (pRExC_state->study_chunk_recursed_count)
215 #define RExC_mysv       (pRExC_state->mysv1)
216 #define RExC_mysv1      (pRExC_state->mysv1)
217 #define RExC_mysv2      (pRExC_state->mysv2)
218
219 #endif
220     bool        seen_unfolded_sharp_s;
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 */
1424     if (OP(node) == ANYOFD
1425         && (ANYOF_FLAGS(node) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1426     {
1427         _invlist_union(invlist, PL_UpperLatin1, &invlist);
1428     }
1429
1430     /* Similarly for these */
1431     if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1432         _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1433     }
1434
1435     if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1436         _invlist_invert(invlist);
1437     }
1438     else if (new_node_has_latin1 && ANYOF_FLAGS(node) & ANYOFL_FOLD) {
1439
1440         /* Under /li, any 0-255 could fold to any other 0-255, depending on the
1441          * locale.  We can skip this if there are no 0-255 at all. */
1442         _invlist_union(invlist, PL_Latin1, &invlist);
1443     }
1444
1445     /* Similarly add the UTF-8 locale possible matches.  These have to be
1446      * deferred until after the non-UTF-8 locale ones are taken care of just
1447      * above, or it leads to wrong results under ANYOF_INVERT */
1448     if (only_utf8_locale_invlist) {
1449         _invlist_union_maybe_complement_2nd(invlist,
1450                                             only_utf8_locale_invlist,
1451                                             ANYOF_FLAGS(node) & ANYOF_INVERT,
1452                                             &invlist);
1453     }
1454
1455     return invlist;
1456 }
1457
1458 /* These two functions currently do the exact same thing */
1459 #define ssc_init_zero           ssc_init
1460
1461 #define ssc_add_cp(ssc, cp)   ssc_add_range((ssc), (cp), (cp))
1462 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1463
1464 /* 'AND' a given class with another one.  Can create false positives.  'ssc'
1465  * should not be inverted.  'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1466  * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1467
1468 STATIC void
1469 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1470                 const regnode_charclass *and_with)
1471 {
1472     /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1473      * another SSC or a regular ANYOF class.  Can create false positives. */
1474
1475     SV* anded_cp_list;
1476     U8  anded_flags;
1477
1478     PERL_ARGS_ASSERT_SSC_AND;
1479
1480     assert(is_ANYOF_SYNTHETIC(ssc));
1481
1482     /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1483      * the code point inversion list and just the relevant flags */
1484     if (is_ANYOF_SYNTHETIC(and_with)) {
1485         anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1486         anded_flags = ANYOF_FLAGS(and_with);
1487
1488         /* XXX This is a kludge around what appears to be deficiencies in the
1489          * optimizer.  If we make S_ssc_anything() add in the WARN_SUPER flag,
1490          * there are paths through the optimizer where it doesn't get weeded
1491          * out when it should.  And if we don't make some extra provision for
1492          * it like the code just below, it doesn't get added when it should.
1493          * This solution is to add it only when AND'ing, which is here, and
1494          * only when what is being AND'ed is the pristine, original node
1495          * matching anything.  Thus it is like adding it to ssc_anything() but
1496          * only when the result is to be AND'ed.  Probably the same solution
1497          * could be adopted for the same problem we have with /l matching,
1498          * which is solved differently in S_ssc_init(), and that would lead to
1499          * fewer false positives than that solution has.  But if this solution
1500          * creates bugs, the consequences are only that a warning isn't raised
1501          * that should be; while the consequences for having /l bugs is
1502          * incorrect matches */
1503         if (ssc_is_anything((regnode_ssc *)and_with)) {
1504             anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1505         }
1506     }
1507     else {
1508         anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1509         if (OP(and_with) == ANYOFD) {
1510             anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
1511         }
1512         else {
1513             anded_flags = ANYOF_FLAGS(and_with)
1514             &( ANYOF_COMMON_FLAGS
1515               |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1516               |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1517             if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(and_with))) {
1518                 anded_flags &=
1519                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1520             }
1521         }
1522     }
1523
1524     ANYOF_FLAGS(ssc) &= anded_flags;
1525
1526     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1527      * C2 is the list of code points in 'and-with'; P2, its posix classes.
1528      * 'and_with' may be inverted.  When not inverted, we have the situation of
1529      * computing:
1530      *  (C1 | P1) & (C2 | P2)
1531      *                     =  (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1532      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1533      *                    <=  ((C1 & C2) |       P2)) | ( P1       | (P1 & P2))
1534      *                    <=  ((C1 & C2) | P1 | P2)
1535      * Alternatively, the last few steps could be:
1536      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1537      *                    <=  ((C1 & C2) |  C1      ) | (      C2  | (P1 & P2))
1538      *                    <=  (C1 | C2 | (P1 & P2))
1539      * We favor the second approach if either P1 or P2 is non-empty.  This is
1540      * because these components are a barrier to doing optimizations, as what
1541      * they match cannot be known until the moment of matching as they are
1542      * dependent on the current locale, 'AND"ing them likely will reduce or
1543      * eliminate them.
1544      * But we can do better if we know that C1,P1 are in their initial state (a
1545      * frequent occurrence), each matching everything:
1546      *  (<everything>) & (C2 | P2) =  C2 | P2
1547      * Similarly, if C2,P2 are in their initial state (again a frequent
1548      * occurrence), the result is a no-op
1549      *  (C1 | P1) & (<everything>) =  C1 | P1
1550      *
1551      * Inverted, we have
1552      *  (C1 | P1) & ~(C2 | P2)  =  (C1 | P1) & (~C2 & ~P2)
1553      *                          =  (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1554      *                         <=  (C1 & ~C2) | (P1 & ~P2)
1555      * */
1556
1557     if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
1558         && ! is_ANYOF_SYNTHETIC(and_with))
1559     {
1560         unsigned int i;
1561
1562         ssc_intersection(ssc,
1563                          anded_cp_list,
1564                          FALSE /* Has already been inverted */
1565                          );
1566
1567         /* If either P1 or P2 is empty, the intersection will be also; can skip
1568          * the loop */
1569         if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
1570             ANYOF_POSIXL_ZERO(ssc);
1571         }
1572         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1573
1574             /* Note that the Posix class component P from 'and_with' actually
1575              * looks like:
1576              *      P = Pa | Pb | ... | Pn
1577              * where each component is one posix class, such as in [\w\s].
1578              * Thus
1579              *      ~P = ~(Pa | Pb | ... | Pn)
1580              *         = ~Pa & ~Pb & ... & ~Pn
1581              *        <= ~Pa | ~Pb | ... | ~Pn
1582              * The last is something we can easily calculate, but unfortunately
1583              * is likely to have many false positives.  We could do better
1584              * in some (but certainly not all) instances if two classes in
1585              * P have known relationships.  For example
1586              *      :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1587              * So
1588              *      :lower: & :print: = :lower:
1589              * And similarly for classes that must be disjoint.  For example,
1590              * since \s and \w can have no elements in common based on rules in
1591              * the POSIX standard,
1592              *      \w & ^\S = nothing
1593              * Unfortunately, some vendor locales do not meet the Posix
1594              * standard, in particular almost everything by Microsoft.
1595              * The loop below just changes e.g., \w into \W and vice versa */
1596
1597             regnode_charclass_posixl temp;
1598             int add = 1;    /* To calculate the index of the complement */
1599
1600             ANYOF_POSIXL_ZERO(&temp);
1601             for (i = 0; i < ANYOF_MAX; i++) {
1602                 assert(i % 2 != 0
1603                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1604                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1605
1606                 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1607                     ANYOF_POSIXL_SET(&temp, i + add);
1608                 }
1609                 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1610             }
1611             ANYOF_POSIXL_AND(&temp, ssc);
1612
1613         } /* else ssc already has no posixes */
1614     } /* else: Not inverted.  This routine is a no-op if 'and_with' is an SSC
1615          in its initial state */
1616     else if (! is_ANYOF_SYNTHETIC(and_with)
1617              || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1618     {
1619         /* But if 'ssc' is in its initial state, the result is just 'and_with';
1620          * copy it over 'ssc' */
1621         if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1622             if (is_ANYOF_SYNTHETIC(and_with)) {
1623                 StructCopy(and_with, ssc, regnode_ssc);
1624             }
1625             else {
1626                 ssc->invlist = anded_cp_list;
1627                 ANYOF_POSIXL_ZERO(ssc);
1628                 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1629                     ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1630                 }
1631             }
1632         }
1633         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1634                  || (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
1635         {
1636             /* One or the other of P1, P2 is non-empty. */
1637             if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1638                 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1639             }
1640             ssc_union(ssc, anded_cp_list, FALSE);
1641         }
1642         else { /* P1 = P2 = empty */
1643             ssc_intersection(ssc, anded_cp_list, FALSE);
1644         }
1645     }
1646 }
1647
1648 STATIC void
1649 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1650                const regnode_charclass *or_with)
1651 {
1652     /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1653      * another SSC or a regular ANYOF class.  Can create false positives if
1654      * 'or_with' is to be inverted. */
1655
1656     SV* ored_cp_list;
1657     U8 ored_flags;
1658
1659     PERL_ARGS_ASSERT_SSC_OR;
1660
1661     assert(is_ANYOF_SYNTHETIC(ssc));
1662
1663     /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1664      * the code point inversion list and just the relevant flags */
1665     if (is_ANYOF_SYNTHETIC(or_with)) {
1666         ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1667         ored_flags = ANYOF_FLAGS(or_with);
1668     }
1669     else {
1670         ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1671         ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
1672         if (OP(or_with) != ANYOFD) {
1673             ored_flags
1674             |= ANYOF_FLAGS(or_with)
1675              & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1676                 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1677             if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(or_with))) {
1678                 ored_flags |=
1679                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1680             }
1681         }
1682     }
1683
1684     ANYOF_FLAGS(ssc) |= ored_flags;
1685
1686     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1687      * C2 is the list of code points in 'or-with'; P2, its posix classes.
1688      * 'or_with' may be inverted.  When not inverted, we have the simple
1689      * situation of computing:
1690      *  (C1 | P1) | (C2 | P2)  =  (C1 | C2) | (P1 | P2)
1691      * If P1|P2 yields a situation with both a class and its complement are
1692      * set, like having both \w and \W, this matches all code points, and we
1693      * can delete these from the P component of the ssc going forward.  XXX We
1694      * might be able to delete all the P components, but I (khw) am not certain
1695      * about this, and it is better to be safe.
1696      *
1697      * Inverted, we have
1698      *  (C1 | P1) | ~(C2 | P2)  =  (C1 | P1) | (~C2 & ~P2)
1699      *                         <=  (C1 | P1) | ~C2
1700      *                         <=  (C1 | ~C2) | P1
1701      * (which results in actually simpler code than the non-inverted case)
1702      * */
1703
1704     if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
1705         && ! is_ANYOF_SYNTHETIC(or_with))
1706     {
1707         /* We ignore P2, leaving P1 going forward */
1708     }   /* else  Not inverted */
1709     else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
1710         ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1711         if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1712             unsigned int i;
1713             for (i = 0; i < ANYOF_MAX; i += 2) {
1714                 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1715                 {
1716                     ssc_match_all_cp(ssc);
1717                     ANYOF_POSIXL_CLEAR(ssc, i);
1718                     ANYOF_POSIXL_CLEAR(ssc, i+1);
1719                 }
1720             }
1721         }
1722     }
1723
1724     ssc_union(ssc,
1725               ored_cp_list,
1726               FALSE /* Already has been inverted */
1727               );
1728 }
1729
1730 PERL_STATIC_INLINE void
1731 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1732 {
1733     PERL_ARGS_ASSERT_SSC_UNION;
1734
1735     assert(is_ANYOF_SYNTHETIC(ssc));
1736
1737     _invlist_union_maybe_complement_2nd(ssc->invlist,
1738                                         invlist,
1739                                         invert2nd,
1740                                         &ssc->invlist);
1741 }
1742
1743 PERL_STATIC_INLINE void
1744 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1745                          SV* const invlist,
1746                          const bool invert2nd)
1747 {
1748     PERL_ARGS_ASSERT_SSC_INTERSECTION;
1749
1750     assert(is_ANYOF_SYNTHETIC(ssc));
1751
1752     _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1753                                                invlist,
1754                                                invert2nd,
1755                                                &ssc->invlist);
1756 }
1757
1758 PERL_STATIC_INLINE void
1759 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
1760 {
1761     PERL_ARGS_ASSERT_SSC_ADD_RANGE;
1762
1763     assert(is_ANYOF_SYNTHETIC(ssc));
1764
1765     ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
1766 }
1767
1768 PERL_STATIC_INLINE void
1769 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
1770 {
1771     /* AND just the single code point 'cp' into the SSC 'ssc' */
1772
1773     SV* cp_list = _new_invlist(2);
1774
1775     PERL_ARGS_ASSERT_SSC_CP_AND;
1776
1777     assert(is_ANYOF_SYNTHETIC(ssc));
1778
1779     cp_list = add_cp_to_invlist(cp_list, cp);
1780     ssc_intersection(ssc, cp_list,
1781                      FALSE /* Not inverted */
1782                      );
1783     SvREFCNT_dec_NN(cp_list);
1784 }
1785
1786 PERL_STATIC_INLINE void
1787 S_ssc_clear_locale(regnode_ssc *ssc)
1788 {
1789     /* Set the SSC 'ssc' to not match any locale things */
1790     PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
1791
1792     assert(is_ANYOF_SYNTHETIC(ssc));
1793
1794     ANYOF_POSIXL_ZERO(ssc);
1795     ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
1796 }
1797
1798 #define NON_OTHER_COUNT   NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
1799
1800 STATIC bool
1801 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
1802 {
1803     /* The synthetic start class is used to hopefully quickly winnow down
1804      * places where a pattern could start a match in the target string.  If it
1805      * doesn't really narrow things down that much, there isn't much point to
1806      * having the overhead of using it.  This function uses some very crude
1807      * heuristics to decide if to use the ssc or not.
1808      *
1809      * It returns TRUE if 'ssc' rules out more than half what it considers to
1810      * be the "likely" possible matches, but of course it doesn't know what the
1811      * actual things being matched are going to be; these are only guesses
1812      *
1813      * For /l matches, it assumes that the only likely matches are going to be
1814      *      in the 0-255 range, uniformly distributed, so half of that is 127
1815      * For /a and /d matches, it assumes that the likely matches will be just
1816      *      the ASCII range, so half of that is 63
1817      * For /u and there isn't anything matching above the Latin1 range, it
1818      *      assumes that that is the only range likely to be matched, and uses
1819      *      half that as the cut-off: 127.  If anything matches above Latin1,
1820      *      it assumes that all of Unicode could match (uniformly), except for
1821      *      non-Unicode code points and things in the General Category "Other"
1822      *      (unassigned, private use, surrogates, controls and formats).  This
1823      *      is a much large number. */
1824
1825     const U32 max_match = (LOC)
1826                           ? 127
1827                           : (! UNI_SEMANTICS)
1828                             ? 63
1829                             : (invlist_highest(ssc->invlist) < 256)
1830                               ? 127
1831                               : ((NON_OTHER_COUNT + 1) / 2) - 1;
1832     U32 count = 0;      /* Running total of number of code points matched by
1833                            'ssc' */
1834     UV start, end;      /* Start and end points of current range in inversion
1835                            list */
1836
1837     PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
1838
1839     invlist_iterinit(ssc->invlist);
1840     while (invlist_iternext(ssc->invlist, &start, &end)) {
1841
1842         /* /u is the only thing that we expect to match above 255; so if not /u
1843          * and even if there are matches above 255, ignore them.  This catches
1844          * things like \d under /d which does match the digits above 255, but
1845          * since the pattern is /d, it is not likely to be expecting them */
1846         if (! UNI_SEMANTICS) {
1847             if (start > 255) {
1848                 break;
1849             }
1850             end = MIN(end, 255);
1851         }
1852         count += end - start + 1;
1853         if (count > max_match) {
1854             invlist_iterfinish(ssc->invlist);
1855             return FALSE;
1856         }
1857     }
1858
1859     return TRUE;
1860 }
1861
1862
1863 STATIC void
1864 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
1865 {
1866     /* The inversion list in the SSC is marked mortal; now we need a more
1867      * permanent copy, which is stored the same way that is done in a regular
1868      * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
1869      * map */
1870
1871     SV* invlist = invlist_clone(ssc->invlist);
1872
1873     PERL_ARGS_ASSERT_SSC_FINALIZE;
1874
1875     assert(is_ANYOF_SYNTHETIC(ssc));
1876
1877     /* The code in this file assumes that all but these flags aren't relevant
1878      * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
1879      * by the time we reach here */
1880     assert(! (ANYOF_FLAGS(ssc)
1881         & ~( ANYOF_COMMON_FLAGS
1882             |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1883             |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
1884
1885     populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
1886
1887     set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist,
1888                                 NULL, NULL, NULL, FALSE);
1889
1890     /* Make sure is clone-safe */
1891     ssc->invlist = NULL;
1892
1893     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1894         ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
1895     }
1896
1897     if (RExC_contains_locale) {
1898         OP(ssc) = ANYOFL;
1899     }
1900
1901     assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
1902 }
1903
1904 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
1905 #define TRIE_LIST_CUR(state)  ( TRIE_LIST_ITEM( state, 0 ).forid )
1906 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
1907 #define TRIE_LIST_USED(idx)  ( trie->states[state].trans.list         \
1908                                ? (TRIE_LIST_CUR( idx ) - 1)           \
1909                                : 0 )
1910
1911
1912 #ifdef DEBUGGING
1913 /*
1914    dump_trie(trie,widecharmap,revcharmap)
1915    dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
1916    dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
1917
1918    These routines dump out a trie in a somewhat readable format.
1919    The _interim_ variants are used for debugging the interim
1920    tables that are used to generate the final compressed
1921    representation which is what dump_trie expects.
1922
1923    Part of the reason for their existence is to provide a form
1924    of documentation as to how the different representations function.
1925
1926 */
1927
1928 /*
1929   Dumps the final compressed table form of the trie to Perl_debug_log.
1930   Used for debugging make_trie().
1931 */
1932
1933 STATIC void
1934 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
1935             AV *revcharmap, U32 depth)
1936 {
1937     U32 state;
1938     SV *sv=sv_newmortal();
1939     int colwidth= widecharmap ? 6 : 4;
1940     U16 word;
1941     GET_RE_DEBUG_FLAGS_DECL;
1942
1943     PERL_ARGS_ASSERT_DUMP_TRIE;
1944
1945     PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
1946         (int)depth * 2 + 2,"",
1947         "Match","Base","Ofs" );
1948
1949     for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
1950         SV ** const tmp = av_fetch( revcharmap, state, 0);
1951         if ( tmp ) {
1952             PerlIO_printf( Perl_debug_log, "%*s",
1953                 colwidth,
1954                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
1955                             PL_colors[0], PL_colors[1],
1956                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1957                             PERL_PV_ESCAPE_FIRSTCHAR
1958                 )
1959             );
1960         }
1961     }
1962     PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
1963         (int)depth * 2 + 2,"");
1964
1965     for( state = 0 ; state < trie->uniquecharcount ; state++ )
1966         PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
1967     PerlIO_printf( Perl_debug_log, "\n");
1968
1969     for( state = 1 ; state < trie->statecount ; state++ ) {
1970         const U32 base = trie->states[ state ].trans.base;
1971
1972         PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|",
1973                                        (int)depth * 2 + 2,"", (UV)state);
1974
1975         if ( trie->states[ state ].wordnum ) {
1976             PerlIO_printf( Perl_debug_log, " W%4X",
1977                                            trie->states[ state ].wordnum );
1978         } else {
1979             PerlIO_printf( Perl_debug_log, "%6s", "" );
1980         }
1981
1982         PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
1983
1984         if ( base ) {
1985             U32 ofs = 0;
1986
1987             while( ( base + ofs  < trie->uniquecharcount ) ||
1988                    ( base + ofs - trie->uniquecharcount < trie->lasttrans
1989                      && trie->trans[ base + ofs - trie->uniquecharcount ].check
1990                                                                     != state))
1991                     ofs++;
1992
1993             PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
1994
1995             for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1996                 if ( ( base + ofs >= trie->uniquecharcount )
1997                         && ( base + ofs - trie->uniquecharcount
1998                                                         < trie->lasttrans )
1999                         && trie->trans[ base + ofs
2000                                     - trie->uniquecharcount ].check == state )
2001                 {
2002                    PerlIO_printf( Perl_debug_log, "%*"UVXf,
2003                     colwidth,
2004                     (UV)trie->trans[ base + ofs
2005                                              - trie->uniquecharcount ].next );
2006                 } else {
2007                     PerlIO_printf( Perl_debug_log, "%*s",colwidth,"   ." );
2008                 }
2009             }
2010
2011             PerlIO_printf( Perl_debug_log, "]");
2012
2013         }
2014         PerlIO_printf( Perl_debug_log, "\n" );
2015     }
2016     PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=",
2017                                 (int)depth*2, "");
2018     for (word=1; word <= trie->wordcount; word++) {
2019         PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
2020             (int)word, (int)(trie->wordinfo[word].prev),
2021             (int)(trie->wordinfo[word].len));
2022     }
2023     PerlIO_printf(Perl_debug_log, "\n" );
2024 }
2025 /*
2026   Dumps a fully constructed but uncompressed trie in list form.
2027   List tries normally only are used for construction when the number of
2028   possible chars (trie->uniquecharcount) is very high.
2029   Used for debugging make_trie().
2030 */
2031 STATIC void
2032 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2033                          HV *widecharmap, AV *revcharmap, U32 next_alloc,
2034                          U32 depth)
2035 {
2036     U32 state;
2037     SV *sv=sv_newmortal();
2038     int colwidth= widecharmap ? 6 : 4;
2039     GET_RE_DEBUG_FLAGS_DECL;
2040
2041     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2042
2043     /* print out the table precompression.  */
2044     PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
2045         (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
2046         "------:-----+-----------------\n" );
2047
2048     for( state=1 ; state < next_alloc ; state ++ ) {
2049         U16 charid;
2050
2051         PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
2052             (int)depth * 2 + 2,"", (UV)state  );
2053         if ( ! trie->states[ state ].wordnum ) {
2054             PerlIO_printf( Perl_debug_log, "%5s| ","");
2055         } else {
2056             PerlIO_printf( Perl_debug_log, "W%4x| ",
2057                 trie->states[ state ].wordnum
2058             );
2059         }
2060         for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2061             SV ** const tmp = av_fetch( revcharmap,
2062                                         TRIE_LIST_ITEM(state,charid).forid, 0);
2063             if ( tmp ) {
2064                 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
2065                     colwidth,
2066                     pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2067                               colwidth,
2068                               PL_colors[0], PL_colors[1],
2069                               (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2070                               | PERL_PV_ESCAPE_FIRSTCHAR
2071                     ) ,
2072                     TRIE_LIST_ITEM(state,charid).forid,
2073                     (UV)TRIE_LIST_ITEM(state,charid).newstate
2074                 );
2075                 if (!(charid % 10))
2076                     PerlIO_printf(Perl_debug_log, "\n%*s| ",
2077                         (int)((depth * 2) + 14), "");
2078             }
2079         }
2080         PerlIO_printf( Perl_debug_log, "\n");
2081     }
2082 }
2083
2084 /*
2085   Dumps a fully constructed but uncompressed trie in table form.
2086   This is the normal DFA style state transition table, with a few
2087   twists to facilitate compression later.
2088   Used for debugging make_trie().
2089 */
2090 STATIC void
2091 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2092                           HV *widecharmap, AV *revcharmap, U32 next_alloc,
2093                           U32 depth)
2094 {
2095     U32 state;
2096     U16 charid;
2097     SV *sv=sv_newmortal();
2098     int colwidth= widecharmap ? 6 : 4;
2099     GET_RE_DEBUG_FLAGS_DECL;
2100
2101     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2102
2103     /*
2104        print out the table precompression so that we can do a visual check
2105        that they are identical.
2106      */
2107
2108     PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
2109
2110     for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2111         SV ** const tmp = av_fetch( revcharmap, charid, 0);
2112         if ( tmp ) {
2113             PerlIO_printf( Perl_debug_log, "%*s",
2114                 colwidth,
2115                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2116                             PL_colors[0], PL_colors[1],
2117                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2118                             PERL_PV_ESCAPE_FIRSTCHAR
2119                 )
2120             );
2121         }
2122     }
2123
2124     PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
2125
2126     for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2127         PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
2128     }
2129
2130     PerlIO_printf( Perl_debug_log, "\n" );
2131
2132     for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2133
2134         PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
2135             (int)depth * 2 + 2,"",
2136             (UV)TRIE_NODENUM( state ) );
2137
2138         for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2139             UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2140             if (v)
2141                 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
2142             else
2143                 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
2144         }
2145         if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2146             PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n",
2147                                             (UV)trie->trans[ state ].check );
2148         } else {
2149             PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n",
2150                                             (UV)trie->trans[ state ].check,
2151             trie->states[ TRIE_NODENUM( state ) ].wordnum );
2152         }
2153     }
2154 }
2155
2156 #endif
2157
2158
2159 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2160   startbranch: the first branch in the whole branch sequence
2161   first      : start branch of sequence of branch-exact nodes.
2162                May be the same as startbranch
2163   last       : Thing following the last branch.
2164                May be the same as tail.
2165   tail       : item following the branch sequence
2166   count      : words in the sequence
2167   flags      : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2168   depth      : indent depth
2169
2170 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2171
2172 A trie is an N'ary tree where the branches are determined by digital
2173 decomposition of the key. IE, at the root node you look up the 1st character and
2174 follow that branch repeat until you find the end of the branches. Nodes can be
2175 marked as "accepting" meaning they represent a complete word. Eg:
2176
2177   /he|she|his|hers/
2178
2179 would convert into the following structure. Numbers represent states, letters
2180 following numbers represent valid transitions on the letter from that state, if
2181 the number is in square brackets it represents an accepting state, otherwise it
2182 will be in parenthesis.
2183
2184       +-h->+-e->[3]-+-r->(8)-+-s->[9]
2185       |    |
2186       |   (2)
2187       |    |
2188      (1)   +-i->(6)-+-s->[7]
2189       |
2190       +-s->(3)-+-h->(4)-+-e->[5]
2191
2192       Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2193
2194 This shows that when matching against the string 'hers' we will begin at state 1
2195 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2196 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2197 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2198 single traverse. We store a mapping from accepting to state to which word was
2199 matched, and then when we have multiple possibilities we try to complete the
2200 rest of the regex in the order in which they occurred in the alternation.
2201
2202 The only prior NFA like behaviour that would be changed by the TRIE support is
2203 the silent ignoring of duplicate alternations which are of the form:
2204
2205  / (DUPE|DUPE) X? (?{ ... }) Y /x
2206
2207 Thus EVAL blocks following a trie may be called a different number of times with
2208 and without the optimisation. With the optimisations dupes will be silently
2209 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2210 the following demonstrates:
2211
2212  'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2213
2214 which prints out 'word' three times, but
2215
2216  'words'=~/(word|word|word)(?{ print $1 })S/
2217
2218 which doesnt print it out at all. This is due to other optimisations kicking in.
2219
2220 Example of what happens on a structural level:
2221
2222 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2223
2224    1: CURLYM[1] {1,32767}(18)
2225    5:   BRANCH(8)
2226    6:     EXACT <ac>(16)
2227    8:   BRANCH(11)
2228    9:     EXACT <ad>(16)
2229   11:   BRANCH(14)
2230   12:     EXACT <ab>(16)
2231   16:   SUCCEED(0)
2232   17:   NOTHING(18)
2233   18: END(0)
2234
2235 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2236 and should turn into:
2237
2238    1: CURLYM[1] {1,32767}(18)
2239    5:   TRIE(16)
2240         [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2241           <ac>
2242           <ad>
2243           <ab>
2244   16:   SUCCEED(0)
2245   17:   NOTHING(18)
2246   18: END(0)
2247
2248 Cases where tail != last would be like /(?foo|bar)baz/:
2249
2250    1: BRANCH(4)
2251    2:   EXACT <foo>(8)
2252    4: BRANCH(7)
2253    5:   EXACT <bar>(8)
2254    7: TAIL(8)
2255    8: EXACT <baz>(10)
2256   10: END(0)
2257
2258 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2259 and would end up looking like:
2260
2261     1: TRIE(8)
2262       [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2263         <foo>
2264         <bar>
2265    7: TAIL(8)
2266    8: EXACT <baz>(10)
2267   10: END(0)
2268
2269     d = uvchr_to_utf8_flags(d, uv, 0);
2270
2271 is the recommended Unicode-aware way of saying
2272
2273     *(d++) = uv;
2274 */
2275
2276 #define TRIE_STORE_REVCHAR(val)                                            \
2277     STMT_START {                                                           \
2278         if (UTF) {                                                         \
2279             SV *zlopp = newSV(UTF8_MAXBYTES);                              \
2280             unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp);      \
2281             unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2282             SvCUR_set(zlopp, kapow - flrbbbbb);                            \
2283             SvPOK_on(zlopp);                                               \
2284             SvUTF8_on(zlopp);                                              \
2285             av_push(revcharmap, zlopp);                                    \
2286         } else {                                                           \
2287             char ooooff = (char)val;                                           \
2288             av_push(revcharmap, newSVpvn(&ooooff, 1));                     \
2289         }                                                                  \
2290         } STMT_END
2291
2292 /* This gets the next character from the input, folding it if not already
2293  * folded. */
2294 #define TRIE_READ_CHAR STMT_START {                                           \
2295     wordlen++;                                                                \
2296     if ( UTF ) {                                                              \
2297         /* if it is UTF then it is either already folded, or does not need    \
2298          * folding */                                                         \
2299         uvc = valid_utf8_to_uvchr( (const U8*) uc, &len);                     \
2300     }                                                                         \
2301     else if (folder == PL_fold_latin1) {                                      \
2302         /* This folder implies Unicode rules, which in the range expressible  \
2303          *  by not UTF is the lower case, with the two exceptions, one of     \
2304          *  which should have been taken care of before calling this */       \
2305         assert(*uc != LATIN_SMALL_LETTER_SHARP_S);                            \
2306         uvc = toLOWER_L1(*uc);                                                \
2307         if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU;         \
2308         len = 1;                                                              \
2309     } else {                                                                  \
2310         /* raw data, will be folded later if needed */                        \
2311         uvc = (U32)*uc;                                                       \
2312         len = 1;                                                              \
2313     }                                                                         \
2314 } STMT_END
2315
2316
2317
2318 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START {               \
2319     if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) {    \
2320         U32 ging = TRIE_LIST_LEN( state ) *= 2;                 \
2321         Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2322     }                                                           \
2323     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid;     \
2324     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns;   \
2325     TRIE_LIST_CUR( state )++;                                   \
2326 } STMT_END
2327
2328 #define TRIE_LIST_NEW(state) STMT_START {                       \
2329     Newxz( trie->states[ state ].trans.list,               \
2330         4, reg_trie_trans_le );                                 \
2331      TRIE_LIST_CUR( state ) = 1;                                \
2332      TRIE_LIST_LEN( state ) = 4;                                \
2333 } STMT_END
2334
2335 #define TRIE_HANDLE_WORD(state) STMT_START {                    \
2336     U16 dupe= trie->states[ state ].wordnum;                    \
2337     regnode * const noper_next = regnext( noper );              \
2338                                                                 \
2339     DEBUG_r({                                                   \
2340         /* store the word for dumping */                        \
2341         SV* tmp;                                                \
2342         if (OP(noper) != NOTHING)                               \
2343             tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF);    \
2344         else                                                    \
2345             tmp = newSVpvn_utf8( "", 0, UTF );                  \
2346         av_push( trie_words, tmp );                             \
2347     });                                                         \
2348                                                                 \
2349     curword++;                                                  \
2350     trie->wordinfo[curword].prev   = 0;                         \
2351     trie->wordinfo[curword].len    = wordlen;                   \
2352     trie->wordinfo[curword].accept = state;                     \
2353                                                                 \
2354     if ( noper_next < tail ) {                                  \
2355         if (!trie->jump)                                        \
2356             trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2357                                                  sizeof(U16) ); \
2358         trie->jump[curword] = (U16)(noper_next - convert);      \
2359         if (!jumper)                                            \
2360             jumper = noper_next;                                \
2361         if (!nextbranch)                                        \
2362             nextbranch= regnext(cur);                           \
2363     }                                                           \
2364                                                                 \
2365     if ( dupe ) {                                               \
2366         /* It's a dupe. Pre-insert into the wordinfo[].prev   */\
2367         /* chain, so that when the bits of chain are later    */\
2368         /* linked together, the dups appear in the chain      */\
2369         trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2370         trie->wordinfo[dupe].prev = curword;                    \
2371     } else {                                                    \
2372         /* we haven't inserted this word yet.                */ \
2373         trie->states[ state ].wordnum = curword;                \
2374     }                                                           \
2375 } STMT_END
2376
2377
2378 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special)          \
2379      ( ( base + charid >=  ucharcount                                   \
2380          && base + charid < ubound                                      \
2381          && state == trie->trans[ base - ucharcount + charid ].check    \
2382          && trie->trans[ base - ucharcount + charid ].next )            \
2383            ? trie->trans[ base - ucharcount + charid ].next             \
2384            : ( state==1 ? special : 0 )                                 \
2385       )
2386
2387 #define MADE_TRIE       1
2388 #define MADE_JUMP_TRIE  2
2389 #define MADE_EXACT_TRIE 4
2390
2391 STATIC I32
2392 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2393                   regnode *first, regnode *last, regnode *tail,
2394                   U32 word_count, U32 flags, U32 depth)
2395 {
2396     /* first pass, loop through and scan words */
2397     reg_trie_data *trie;
2398     HV *widecharmap = NULL;
2399     AV *revcharmap = newAV();
2400     regnode *cur;
2401     STRLEN len = 0;
2402     UV uvc = 0;
2403     U16 curword = 0;
2404     U32 next_alloc = 0;
2405     regnode *jumper = NULL;
2406     regnode *nextbranch = NULL;
2407     regnode *convert = NULL;
2408     U32 *prev_states; /* temp array mapping each state to previous one */
2409     /* we just use folder as a flag in utf8 */
2410     const U8 * folder = NULL;
2411
2412 #ifdef DEBUGGING
2413     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuuu"));
2414     AV *trie_words = NULL;
2415     /* along with revcharmap, this only used during construction but both are
2416      * useful during debugging so we store them in the struct when debugging.
2417      */
2418 #else
2419     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2420     STRLEN trie_charcount=0;
2421 #endif
2422     SV *re_trie_maxbuff;
2423     GET_RE_DEBUG_FLAGS_DECL;
2424
2425     PERL_ARGS_ASSERT_MAKE_TRIE;
2426 #ifndef DEBUGGING
2427     PERL_UNUSED_ARG(depth);
2428 #endif
2429
2430     switch (flags) {
2431         case EXACT: case EXACTL: break;
2432         case EXACTFA:
2433         case EXACTFU_SS:
2434         case EXACTFU:
2435         case EXACTFLU8: folder = PL_fold_latin1; break;
2436         case EXACTF:  folder = PL_fold; break;
2437         default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2438     }
2439
2440     trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2441     trie->refcount = 1;
2442     trie->startstate = 1;
2443     trie->wordcount = word_count;
2444     RExC_rxi->data->data[ data_slot ] = (void*)trie;
2445     trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2446     if (flags == EXACT || flags == EXACTL)
2447         trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2448     trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2449                        trie->wordcount+1, sizeof(reg_trie_wordinfo));
2450
2451     DEBUG_r({
2452         trie_words = newAV();
2453     });
2454
2455     re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2456     assert(re_trie_maxbuff);
2457     if (!SvIOK(re_trie_maxbuff)) {
2458         sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2459     }
2460     DEBUG_TRIE_COMPILE_r({
2461         PerlIO_printf( Perl_debug_log,
2462           "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2463           (int)depth * 2 + 2, "",
2464           REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
2465           REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2466     });
2467
2468    /* Find the node we are going to overwrite */
2469     if ( first == startbranch && OP( last ) != BRANCH ) {
2470         /* whole branch chain */
2471         convert = first;
2472     } else {
2473         /* branch sub-chain */
2474         convert = NEXTOPER( first );
2475     }
2476
2477     /*  -- First loop and Setup --
2478
2479        We first traverse the branches and scan each word to determine if it
2480        contains widechars, and how many unique chars there are, this is
2481        important as we have to build a table with at least as many columns as we
2482        have unique chars.
2483
2484        We use an array of integers to represent the character codes 0..255
2485        (trie->charmap) and we use a an HV* to store Unicode characters. We use
2486        the native representation of the character value as the key and IV's for
2487        the coded index.
2488
2489        *TODO* If we keep track of how many times each character is used we can
2490        remap the columns so that the table compression later on is more
2491        efficient in terms of memory by ensuring the most common value is in the
2492        middle and the least common are on the outside.  IMO this would be better
2493        than a most to least common mapping as theres a decent chance the most
2494        common letter will share a node with the least common, meaning the node
2495        will not be compressible. With a middle is most common approach the worst
2496        case is when we have the least common nodes twice.
2497
2498      */
2499
2500     for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2501         regnode *noper = NEXTOPER( cur );
2502         const U8 *uc = (U8*)STRING( noper );
2503         const U8 *e  = uc + STR_LEN( noper );
2504         int foldlen = 0;
2505         U32 wordlen      = 0;         /* required init */
2506         STRLEN minchars = 0;
2507         STRLEN maxchars = 0;
2508         bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2509                                                bitmap?*/
2510
2511         if (OP(noper) == NOTHING) {
2512             regnode *noper_next= regnext(noper);
2513             if (noper_next != tail && OP(noper_next) == flags) {
2514                 noper = noper_next;
2515                 uc= (U8*)STRING(noper);
2516                 e= uc + STR_LEN(noper);
2517                 trie->minlen= STR_LEN(noper);
2518             } else {
2519                 trie->minlen= 0;
2520                 continue;
2521             }
2522         }
2523
2524         if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2525             TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2526                                           regardless of encoding */
2527             if (OP( noper ) == EXACTFU_SS) {
2528                 /* false positives are ok, so just set this */
2529                 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2530             }
2531         }
2532         for ( ; uc < e ; uc += len ) {  /* Look at each char in the current
2533                                            branch */
2534             TRIE_CHARCOUNT(trie)++;
2535             TRIE_READ_CHAR;
2536
2537             /* TRIE_READ_CHAR returns the current character, or its fold if /i
2538              * is in effect.  Under /i, this character can match itself, or
2539              * anything that folds to it.  If not under /i, it can match just
2540              * itself.  Most folds are 1-1, for example k, K, and KELVIN SIGN
2541              * all fold to k, and all are single characters.   But some folds
2542              * expand to more than one character, so for example LATIN SMALL
2543              * LIGATURE FFI folds to the three character sequence 'ffi'.  If
2544              * the string beginning at 'uc' is 'ffi', it could be matched by
2545              * three characters, or just by the one ligature character. (It
2546              * could also be matched by two characters: LATIN SMALL LIGATURE FF
2547              * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2548              * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2549              * match.)  The trie needs to know the minimum and maximum number
2550              * of characters that could match so that it can use size alone to
2551              * quickly reject many match attempts.  The max is simple: it is
2552              * the number of folded characters in this branch (since a fold is
2553              * never shorter than what folds to it. */
2554
2555             maxchars++;
2556
2557             /* And the min is equal to the max if not under /i (indicated by
2558              * 'folder' being NULL), or there are no multi-character folds.  If
2559              * there is a multi-character fold, the min is incremented just
2560              * once, for the character that folds to the sequence.  Each
2561              * character in the sequence needs to be added to the list below of
2562              * characters in the trie, but we count only the first towards the
2563              * min number of characters needed.  This is done through the
2564              * variable 'foldlen', which is returned by the macros that look
2565              * for these sequences as the number of bytes the sequence
2566              * occupies.  Each time through the loop, we decrement 'foldlen' by
2567              * how many bytes the current char occupies.  Only when it reaches
2568              * 0 do we increment 'minchars' or look for another multi-character
2569              * sequence. */
2570             if (folder == NULL) {
2571                 minchars++;
2572             }
2573             else if (foldlen > 0) {
2574                 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2575             }
2576             else {
2577                 minchars++;
2578
2579                 /* See if *uc is the beginning of a multi-character fold.  If
2580                  * so, we decrement the length remaining to look at, to account
2581                  * for the current character this iteration.  (We can use 'uc'
2582                  * instead of the fold returned by TRIE_READ_CHAR because for
2583                  * non-UTF, the latin1_safe macro is smart enough to account
2584                  * for all the unfolded characters, and because for UTF, the
2585                  * string will already have been folded earlier in the
2586                  * compilation process */
2587                 if (UTF) {
2588                     if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2589                         foldlen -= UTF8SKIP(uc);
2590                     }
2591                 }
2592                 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2593                     foldlen--;
2594                 }
2595             }
2596
2597             /* The current character (and any potential folds) should be added
2598              * to the possible matching characters for this position in this
2599              * branch */
2600             if ( uvc < 256 ) {
2601                 if ( folder ) {
2602                     U8 folded= folder[ (U8) uvc ];
2603                     if ( !trie->charmap[ folded ] ) {
2604                         trie->charmap[ folded ]=( ++trie->uniquecharcount );
2605                         TRIE_STORE_REVCHAR( folded );
2606                     }
2607                 }
2608                 if ( !trie->charmap[ uvc ] ) {
2609                     trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2610                     TRIE_STORE_REVCHAR( uvc );
2611                 }
2612                 if ( set_bit ) {
2613                     /* store the codepoint in the bitmap, and its folded
2614                      * equivalent. */
2615                     TRIE_BITMAP_SET(trie, uvc);
2616
2617                     /* store the folded codepoint */
2618                     if ( folder ) TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);
2619
2620                     if ( !UTF ) {
2621                         /* store first byte of utf8 representation of
2622                            variant codepoints */
2623                         if (! UVCHR_IS_INVARIANT(uvc)) {
2624                             TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
2625                         }
2626                     }
2627                     set_bit = 0; /* We've done our bit :-) */
2628                 }
2629             } else {
2630
2631                 /* XXX We could come up with the list of code points that fold
2632                  * to this using PL_utf8_foldclosures, except not for
2633                  * multi-char folds, as there may be multiple combinations
2634                  * there that could work, which needs to wait until runtime to
2635                  * resolve (The comment about LIGATURE FFI above is such an
2636                  * example */
2637
2638                 SV** svpp;
2639                 if ( !widecharmap )
2640                     widecharmap = newHV();
2641
2642                 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2643
2644                 if ( !svpp )
2645                     Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
2646
2647                 if ( !SvTRUE( *svpp ) ) {
2648                     sv_setiv( *svpp, ++trie->uniquecharcount );
2649                     TRIE_STORE_REVCHAR(uvc);
2650                 }
2651             }
2652         } /* end loop through characters in this branch of the trie */
2653
2654         /* We take the min and max for this branch and combine to find the min
2655          * and max for all branches processed so far */
2656         if( cur == first ) {
2657             trie->minlen = minchars;
2658             trie->maxlen = maxchars;
2659         } else if (minchars < trie->minlen) {
2660             trie->minlen = minchars;
2661         } else if (maxchars > trie->maxlen) {
2662             trie->maxlen = maxchars;
2663         }
2664     } /* end first pass */
2665     DEBUG_TRIE_COMPILE_r(
2666         PerlIO_printf( Perl_debug_log,
2667                 "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2668                 (int)depth * 2 + 2,"",
2669                 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2670                 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2671                 (int)trie->minlen, (int)trie->maxlen )
2672     );
2673
2674     /*
2675         We now know what we are dealing with in terms of unique chars and
2676         string sizes so we can calculate how much memory a naive
2677         representation using a flat table  will take. If it's over a reasonable
2678         limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2679         conservative but potentially much slower representation using an array
2680         of lists.
2681
2682         At the end we convert both representations into the same compressed
2683         form that will be used in regexec.c for matching with. The latter
2684         is a form that cannot be used to construct with but has memory
2685         properties similar to the list form and access properties similar
2686         to the table form making it both suitable for fast searches and
2687         small enough that its feasable to store for the duration of a program.
2688
2689         See the comment in the code where the compressed table is produced
2690         inplace from the flat tabe representation for an explanation of how
2691         the compression works.
2692
2693     */
2694
2695
2696     Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2697     prev_states[1] = 0;
2698
2699     if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2700                                                     > SvIV(re_trie_maxbuff) )
2701     {
2702         /*
2703             Second Pass -- Array Of Lists Representation
2704
2705             Each state will be represented by a list of charid:state records
2706             (reg_trie_trans_le) the first such element holds the CUR and LEN
2707             points of the allocated array. (See defines above).
2708
2709             We build the initial structure using the lists, and then convert
2710             it into the compressed table form which allows faster lookups
2711             (but cant be modified once converted).
2712         */
2713
2714         STRLEN transcount = 1;
2715
2716         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
2717             "%*sCompiling trie using list compiler\n",
2718             (int)depth * 2 + 2, ""));
2719
2720         trie->states = (reg_trie_state *)
2721             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2722                                   sizeof(reg_trie_state) );
2723         TRIE_LIST_NEW(1);
2724         next_alloc = 2;
2725
2726         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2727
2728             regnode *noper   = NEXTOPER( cur );
2729             U8 *uc           = (U8*)STRING( noper );
2730             const U8 *e      = uc + STR_LEN( noper );
2731             U32 state        = 1;         /* required init */
2732             U16 charid       = 0;         /* sanity init */
2733             U32 wordlen      = 0;         /* required init */
2734
2735             if (OP(noper) == NOTHING) {
2736                 regnode *noper_next= regnext(noper);
2737                 if (noper_next != tail && OP(noper_next) == flags) {
2738                     noper = noper_next;
2739                     uc= (U8*)STRING(noper);
2740                     e= uc + STR_LEN(noper);
2741                 }
2742             }
2743
2744             if (OP(noper) != NOTHING) {
2745                 for ( ; uc < e ; uc += len ) {
2746
2747                     TRIE_READ_CHAR;
2748
2749                     if ( uvc < 256 ) {
2750                         charid = trie->charmap[ uvc ];
2751                     } else {
2752                         SV** const svpp = hv_fetch( widecharmap,
2753                                                     (char*)&uvc,
2754                                                     sizeof( UV ),
2755                                                     0);
2756                         if ( !svpp ) {
2757                             charid = 0;
2758                         } else {
2759                             charid=(U16)SvIV( *svpp );
2760                         }
2761                     }
2762                     /* charid is now 0 if we dont know the char read, or
2763                      * nonzero if we do */
2764                     if ( charid ) {
2765
2766                         U16 check;
2767                         U32 newstate = 0;
2768
2769                         charid--;
2770                         if ( !trie->states[ state ].trans.list ) {
2771                             TRIE_LIST_NEW( state );
2772                         }
2773                         for ( check = 1;
2774                               check <= TRIE_LIST_USED( state );
2775                               check++ )
2776                         {
2777                             if ( TRIE_LIST_ITEM( state, check ).forid
2778                                                                     == charid )
2779                             {
2780                                 newstate = TRIE_LIST_ITEM( state, check ).newstate;
2781                                 break;
2782                             }
2783                         }
2784                         if ( ! newstate ) {
2785                             newstate = next_alloc++;
2786                             prev_states[newstate] = state;
2787                             TRIE_LIST_PUSH( state, charid, newstate );
2788                             transcount++;
2789                         }
2790                         state = newstate;
2791                     } else {
2792                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2793                     }
2794                 }
2795             }
2796             TRIE_HANDLE_WORD(state);
2797
2798         } /* end second pass */
2799
2800         /* next alloc is the NEXT state to be allocated */
2801         trie->statecount = next_alloc;
2802         trie->states = (reg_trie_state *)
2803             PerlMemShared_realloc( trie->states,
2804                                    next_alloc
2805                                    * sizeof(reg_trie_state) );
2806
2807         /* and now dump it out before we compress it */
2808         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
2809                                                          revcharmap, next_alloc,
2810                                                          depth+1)
2811         );
2812
2813         trie->trans = (reg_trie_trans *)
2814             PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
2815         {
2816             U32 state;
2817             U32 tp = 0;
2818             U32 zp = 0;
2819
2820
2821             for( state=1 ; state < next_alloc ; state ++ ) {
2822                 U32 base=0;
2823
2824                 /*
2825                 DEBUG_TRIE_COMPILE_MORE_r(
2826                     PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
2827                 );
2828                 */
2829
2830                 if (trie->states[state].trans.list) {
2831                     U16 minid=TRIE_LIST_ITEM( state, 1).forid;
2832                     U16 maxid=minid;
2833                     U16 idx;
2834
2835                     for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
2836                         const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
2837                         if ( forid < minid ) {
2838                             minid=forid;
2839                         } else if ( forid > maxid ) {
2840                             maxid=forid;
2841                         }
2842                     }
2843                     if ( transcount < tp + maxid - minid + 1) {
2844                         transcount *= 2;
2845                         trie->trans = (reg_trie_trans *)
2846                             PerlMemShared_realloc( trie->trans,
2847                                                      transcount
2848                                                      * sizeof(reg_trie_trans) );
2849                         Zero( trie->trans + (transcount / 2),
2850                               transcount / 2,
2851                               reg_trie_trans );
2852                     }
2853                     base = trie->uniquecharcount + tp - minid;
2854                     if ( maxid == minid ) {
2855                         U32 set = 0;
2856                         for ( ; zp < tp ; zp++ ) {
2857                             if ( ! trie->trans[ zp ].next ) {
2858                                 base = trie->uniquecharcount + zp - minid;
2859                                 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
2860                                                                    1).newstate;
2861                                 trie->trans[ zp ].check = state;
2862                                 set = 1;
2863                                 break;
2864                             }
2865                         }
2866                         if ( !set ) {
2867                             trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
2868                                                                    1).newstate;
2869                             trie->trans[ tp ].check = state;
2870                             tp++;
2871                             zp = tp;
2872                         }
2873                     } else {
2874                         for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
2875                             const U32 tid = base
2876                                            - trie->uniquecharcount
2877                                            + TRIE_LIST_ITEM( state, idx ).forid;
2878                             trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
2879                                                                 idx ).newstate;
2880                             trie->trans[ tid ].check = state;
2881                         }
2882                         tp += ( maxid - minid + 1 );
2883                     }
2884                     Safefree(trie->states[ state ].trans.list);
2885                 }
2886                 /*
2887                 DEBUG_TRIE_COMPILE_MORE_r(
2888                     PerlIO_printf( Perl_debug_log, " base: %d\n",base);
2889                 );
2890                 */
2891                 trie->states[ state ].trans.base=base;
2892             }
2893             trie->lasttrans = tp + 1;
2894         }
2895     } else {
2896         /*
2897            Second Pass -- Flat Table Representation.
2898
2899            we dont use the 0 slot of either trans[] or states[] so we add 1 to
2900            each.  We know that we will need Charcount+1 trans at most to store
2901            the data (one row per char at worst case) So we preallocate both
2902            structures assuming worst case.
2903
2904            We then construct the trie using only the .next slots of the entry
2905            structs.
2906
2907            We use the .check field of the first entry of the node temporarily
2908            to make compression both faster and easier by keeping track of how
2909            many non zero fields are in the node.
2910
2911            Since trans are numbered from 1 any 0 pointer in the table is a FAIL
2912            transition.
2913
2914            There are two terms at use here: state as a TRIE_NODEIDX() which is
2915            a number representing the first entry of the node, and state as a
2916            TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
2917            and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
2918            if there are 2 entrys per node. eg:
2919
2920              A B       A B
2921           1. 2 4    1. 3 7
2922           2. 0 3    3. 0 5
2923           3. 0 0    5. 0 0
2924           4. 0 0    7. 0 0
2925
2926            The table is internally in the right hand, idx form. However as we
2927            also have to deal with the states array which is indexed by nodenum
2928            we have to use TRIE_NODENUM() to convert.
2929
2930         */
2931         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
2932             "%*sCompiling trie using table compiler\n",
2933             (int)depth * 2 + 2, ""));
2934
2935         trie->trans = (reg_trie_trans *)
2936             PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
2937                                   * trie->uniquecharcount + 1,
2938                                   sizeof(reg_trie_trans) );
2939         trie->states = (reg_trie_state *)
2940             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2941                                   sizeof(reg_trie_state) );
2942         next_alloc = trie->uniquecharcount + 1;
2943
2944
2945         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2946
2947             regnode *noper   = NEXTOPER( cur );
2948             const U8 *uc     = (U8*)STRING( noper );
2949             const U8 *e      = uc + STR_LEN( noper );
2950
2951             U32 state        = 1;         /* required init */
2952
2953             U16 charid       = 0;         /* sanity init */
2954             U32 accept_state = 0;         /* sanity init */
2955
2956             U32 wordlen      = 0;         /* required init */
2957
2958             if (OP(noper) == NOTHING) {
2959                 regnode *noper_next= regnext(noper);
2960                 if (noper_next != tail && OP(noper_next) == flags) {
2961                     noper = noper_next;
2962                     uc= (U8*)STRING(noper);
2963                     e= uc + STR_LEN(noper);
2964                 }
2965             }
2966
2967             if ( OP(noper) != NOTHING ) {
2968                 for ( ; uc < e ; uc += len ) {
2969
2970                     TRIE_READ_CHAR;
2971
2972                     if ( uvc < 256 ) {
2973                         charid = trie->charmap[ uvc ];
2974                     } else {
2975                         SV* const * const svpp = hv_fetch( widecharmap,
2976                                                            (char*)&uvc,
2977                                                            sizeof( UV ),
2978                                                            0);
2979                         charid = svpp ? (U16)SvIV(*svpp) : 0;
2980                     }
2981                     if ( charid ) {
2982                         charid--;
2983                         if ( !trie->trans[ state + charid ].next ) {
2984                             trie->trans[ state + charid ].next = next_alloc;
2985                             trie->trans[ state ].check++;
2986                             prev_states[TRIE_NODENUM(next_alloc)]
2987                                     = TRIE_NODENUM(state);
2988                             next_alloc += trie->uniquecharcount;
2989                         }
2990                         state = trie->trans[ state + charid ].next;
2991                     } else {
2992                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2993                     }
2994                     /* charid is now 0 if we dont know the char read, or
2995                      * nonzero if we do */
2996                 }
2997             }
2998             accept_state = TRIE_NODENUM( state );
2999             TRIE_HANDLE_WORD(accept_state);
3000
3001         } /* end second pass */
3002
3003         /* and now dump it out before we compress it */
3004         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3005                                                           revcharmap,
3006                                                           next_alloc, depth+1));
3007
3008         {
3009         /*
3010            * Inplace compress the table.*
3011
3012            For sparse data sets the table constructed by the trie algorithm will
3013            be mostly 0/FAIL transitions or to put it another way mostly empty.
3014            (Note that leaf nodes will not contain any transitions.)
3015
3016            This algorithm compresses the tables by eliminating most such
3017            transitions, at the cost of a modest bit of extra work during lookup:
3018
3019            - Each states[] entry contains a .base field which indicates the
3020            index in the state[] array wheres its transition data is stored.
3021
3022            - If .base is 0 there are no valid transitions from that node.
3023
3024            - If .base is nonzero then charid is added to it to find an entry in
3025            the trans array.
3026
3027            -If trans[states[state].base+charid].check!=state then the
3028            transition is taken to be a 0/Fail transition. Thus if there are fail
3029            transitions at the front of the node then the .base offset will point
3030            somewhere inside the previous nodes data (or maybe even into a node
3031            even earlier), but the .check field determines if the transition is
3032            valid.
3033
3034            XXX - wrong maybe?
3035            The following process inplace converts the table to the compressed
3036            table: We first do not compress the root node 1,and mark all its
3037            .check pointers as 1 and set its .base pointer as 1 as well. This
3038            allows us to do a DFA construction from the compressed table later,
3039            and ensures that any .base pointers we calculate later are greater
3040            than 0.
3041
3042            - We set 'pos' to indicate the first entry of the second node.
3043
3044            - We then iterate over the columns of the node, finding the first and
3045            last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3046            and set the .check pointers accordingly, and advance pos
3047            appropriately and repreat for the next node. Note that when we copy
3048            the next pointers we have to convert them from the original
3049            NODEIDX form to NODENUM form as the former is not valid post
3050            compression.
3051
3052            - If a node has no transitions used we mark its base as 0 and do not
3053            advance the pos pointer.
3054
3055            - If a node only has one transition we use a second pointer into the
3056            structure to fill in allocated fail transitions from other states.
3057            This pointer is independent of the main pointer and scans forward
3058            looking for null transitions that are allocated to a state. When it
3059            finds one it writes the single transition into the "hole".  If the
3060            pointer doesnt find one the single transition is appended as normal.
3061
3062            - Once compressed we can Renew/realloc the structures to release the
3063            excess space.
3064
3065            See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3066            specifically Fig 3.47 and the associated pseudocode.
3067
3068            demq
3069         */
3070         const U32 laststate = TRIE_NODENUM( next_alloc );
3071         U32 state, charid;
3072         U32 pos = 0, zp=0;
3073         trie->statecount = laststate;
3074
3075         for ( state = 1 ; state < laststate ; state++ ) {
3076             U8 flag = 0;
3077             const U32 stateidx = TRIE_NODEIDX( state );
3078             const U32 o_used = trie->trans[ stateidx ].check;
3079             U32 used = trie->trans[ stateidx ].check;
3080             trie->trans[ stateidx ].check = 0;
3081
3082             for ( charid = 0;
3083                   used && charid < trie->uniquecharcount;
3084                   charid++ )
3085             {
3086                 if ( flag || trie->trans[ stateidx + charid ].next ) {
3087                     if ( trie->trans[ stateidx + charid ].next ) {
3088                         if (o_used == 1) {
3089                             for ( ; zp < pos ; zp++ ) {
3090                                 if ( ! trie->trans[ zp ].next ) {
3091                                     break;
3092                                 }
3093                             }
3094                             trie->states[ state ].trans.base
3095                                                     = zp
3096                                                       + trie->uniquecharcount
3097                                                       - charid ;
3098                             trie->trans[ zp ].next
3099                                 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3100                                                              + charid ].next );
3101                             trie->trans[ zp ].check = state;
3102                             if ( ++zp > pos ) pos = zp;
3103                             break;
3104                         }
3105                         used--;
3106                     }
3107                     if ( !flag ) {
3108                         flag = 1;
3109                         trie->states[ state ].trans.base
3110                                        = pos + trie->uniquecharcount - charid ;
3111                     }
3112                     trie->trans[ pos ].next
3113                         = SAFE_TRIE_NODENUM(
3114                                        trie->trans[ stateidx + charid ].next );
3115                     trie->trans[ pos ].check = state;
3116                     pos++;
3117                 }
3118             }
3119         }
3120         trie->lasttrans = pos + 1;
3121         trie->states = (reg_trie_state *)
3122             PerlMemShared_realloc( trie->states, laststate
3123                                    * sizeof(reg_trie_state) );
3124         DEBUG_TRIE_COMPILE_MORE_r(
3125             PerlIO_printf( Perl_debug_log,
3126                 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
3127                 (int)depth * 2 + 2,"",
3128                 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3129                        + 1 ),
3130                 (IV)next_alloc,
3131                 (IV)pos,
3132                 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3133             );
3134
3135         } /* end table compress */
3136     }
3137     DEBUG_TRIE_COMPILE_MORE_r(
3138             PerlIO_printf(Perl_debug_log,
3139                 "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
3140                 (int)depth * 2 + 2, "",
3141                 (UV)trie->statecount,
3142                 (UV)trie->lasttrans)
3143     );
3144     /* resize the trans array to remove unused space */
3145     trie->trans = (reg_trie_trans *)
3146         PerlMemShared_realloc( trie->trans, trie->lasttrans
3147                                * sizeof(reg_trie_trans) );
3148
3149     {   /* Modify the program and insert the new TRIE node */
3150         U8 nodetype =(U8)(flags & 0xFF);
3151         char *str=NULL;
3152
3153 #ifdef DEBUGGING
3154         regnode *optimize = NULL;
3155 #ifdef RE_TRACK_PATTERN_OFFSETS
3156
3157         U32 mjd_offset = 0;
3158         U32 mjd_nodelen = 0;
3159 #endif /* RE_TRACK_PATTERN_OFFSETS */
3160 #endif /* DEBUGGING */
3161         /*
3162            This means we convert either the first branch or the first Exact,
3163            depending on whether the thing following (in 'last') is a branch
3164            or not and whther first is the startbranch (ie is it a sub part of
3165            the alternation or is it the whole thing.)
3166            Assuming its a sub part we convert the EXACT otherwise we convert
3167            the whole branch sequence, including the first.
3168          */
3169         /* Find the node we are going to overwrite */
3170         if ( first != startbranch || OP( last ) == BRANCH ) {
3171             /* branch sub-chain */
3172             NEXT_OFF( first ) = (U16)(last - first);
3173 #ifdef RE_TRACK_PATTERN_OFFSETS
3174             DEBUG_r({
3175                 mjd_offset= Node_Offset((convert));
3176                 mjd_nodelen= Node_Length((convert));
3177             });
3178 #endif
3179             /* whole branch chain */
3180         }
3181 #ifdef RE_TRACK_PATTERN_OFFSETS
3182         else {
3183             DEBUG_r({
3184                 const  regnode *nop = NEXTOPER( convert );
3185                 mjd_offset= Node_Offset((nop));
3186                 mjd_nodelen= Node_Length((nop));
3187             });
3188         }
3189         DEBUG_OPTIMISE_r(
3190             PerlIO_printf(Perl_debug_log,
3191                 "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
3192                 (int)depth * 2 + 2, "",
3193                 (UV)mjd_offset, (UV)mjd_nodelen)
3194         );
3195 #endif
3196         /* But first we check to see if there is a common prefix we can
3197            split out as an EXACT and put in front of the TRIE node.  */
3198         trie->startstate= 1;
3199         if ( trie->bitmap && !widecharmap && !trie->jump  ) {
3200             U32 state;
3201             for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3202                 U32 ofs = 0;
3203                 I32 idx = -1;
3204                 U32 count = 0;
3205                 const U32 base = trie->states[ state ].trans.base;
3206
3207                 if ( trie->states[state].wordnum )
3208                         count = 1;
3209
3210                 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3211                     if ( ( base + ofs >= trie->uniquecharcount ) &&
3212                          ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3213                          trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3214                     {
3215                         if ( ++count > 1 ) {
3216                             SV **tmp = av_fetch( revcharmap, ofs, 0);
3217                             const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
3218                             if ( state == 1 ) break;
3219                             if ( count == 2 ) {
3220                                 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3221                                 DEBUG_OPTIMISE_r(
3222                                     PerlIO_printf(Perl_debug_log,
3223                                         "%*sNew Start State=%"UVuf" Class: [",
3224                                         (int)depth * 2 + 2, "",
3225                                         (UV)state));
3226                                 if (idx >= 0) {
3227                                     SV ** const tmp = av_fetch( revcharmap, idx, 0);
3228                                     const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3229
3230                                     TRIE_BITMAP_SET(trie,*ch);
3231                                     if ( folder )
3232                                         TRIE_BITMAP_SET(trie, folder[ *ch ]);
3233                                     DEBUG_OPTIMISE_r(
3234                                         PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
3235                                     );
3236                                 }
3237                             }
3238                             TRIE_BITMAP_SET(trie,*ch);
3239                             if ( folder )
3240                                 TRIE_BITMAP_SET(trie,folder[ *ch ]);
3241                             DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
3242                         }
3243                         idx = ofs;
3244                     }
3245                 }
3246                 if ( count == 1 ) {
3247                     SV **tmp = av_fetch( revcharmap, idx, 0);
3248                     STRLEN len;
3249                     char *ch = SvPV( *tmp, len );
3250                     DEBUG_OPTIMISE_r({
3251                         SV *sv=sv_newmortal();
3252                         PerlIO_printf( Perl_debug_log,
3253                             "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
3254                             (int)depth * 2 + 2, "",
3255                             (UV)state, (UV)idx,
3256                             pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3257                                 PL_colors[0], PL_colors[1],
3258                                 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3259                                 PERL_PV_ESCAPE_FIRSTCHAR
3260                             )
3261                         );
3262                     });
3263                     if ( state==1 ) {
3264                         OP( convert ) = nodetype;
3265                         str=STRING(convert);
3266                         STR_LEN(convert)=0;
3267                     }
3268                     STR_LEN(convert) += len;
3269                     while (len--)
3270                         *str++ = *ch++;
3271                 } else {
3272 #ifdef DEBUGGING
3273                     if (state>1)
3274                         DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
3275 #endif
3276                     break;
3277                 }
3278             }
3279             trie->prefixlen = (state-1);
3280             if (str) {
3281                 regnode *n = convert+NODE_SZ_STR(convert);
3282                 NEXT_OFF(convert) = NODE_SZ_STR(convert);
3283                 trie->startstate = state;
3284                 trie->minlen -= (state - 1);
3285                 trie->maxlen -= (state - 1);
3286 #ifdef DEBUGGING
3287                /* At least the UNICOS C compiler choked on this
3288                 * being argument to DEBUG_r(), so let's just have
3289                 * it right here. */
3290                if (
3291 #ifdef PERL_EXT_RE_BUILD
3292                    1
3293 #else
3294                    DEBUG_r_TEST
3295 #endif
3296                    ) {
3297                    regnode *fix = convert;
3298                    U32 word = trie->wordcount;
3299                    mjd_nodelen++;
3300                    Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3301                    while( ++fix < n ) {
3302                        Set_Node_Offset_Length(fix, 0, 0);
3303                    }
3304                    while (word--) {
3305                        SV ** const tmp = av_fetch( trie_words, word, 0 );
3306                        if (tmp) {
3307                            if ( STR_LEN(convert) <= SvCUR(*tmp) )
3308                                sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3309                            else
3310                                sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3311                        }
3312                    }
3313                }
3314 #endif
3315                 if (trie->maxlen) {
3316                     convert = n;
3317                 } else {
3318                     NEXT_OFF(convert) = (U16)(tail - convert);
3319                     DEBUG_r(optimize= n);
3320                 }
3321             }
3322         }
3323         if (!jumper)
3324             jumper = last;
3325         if ( trie->maxlen ) {
3326             NEXT_OFF( convert ) = (U16)(tail - convert);
3327             ARG_SET( convert, data_slot );
3328             /* Store the offset to the first unabsorbed branch in
3329                jump[0], which is otherwise unused by the jump logic.
3330                We use this when dumping a trie and during optimisation. */
3331             if (trie->jump)
3332                 trie->jump[0] = (U16)(nextbranch - convert);
3333
3334             /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3335              *   and there is a bitmap
3336              *   and the first "jump target" node we found leaves enough room
3337              * then convert the TRIE node into a TRIEC node, with the bitmap
3338              * embedded inline in the opcode - this is hypothetically faster.
3339              */
3340             if ( !trie->states[trie->startstate].wordnum
3341                  && trie->bitmap
3342                  && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3343             {
3344                 OP( convert ) = TRIEC;
3345                 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3346                 PerlMemShared_free(trie->bitmap);
3347                 trie->bitmap= NULL;
3348             } else
3349                 OP( convert ) = TRIE;
3350
3351             /* store the type in the flags */
3352             convert->flags = nodetype;
3353             DEBUG_r({
3354             optimize = convert
3355                       + NODE_STEP_REGNODE
3356                       + regarglen[ OP( convert ) ];
3357             });
3358             /* XXX We really should free up the resource in trie now,
3359                    as we won't use them - (which resources?) dmq */
3360         }
3361         /* needed for dumping*/
3362         DEBUG_r(if (optimize) {
3363             regnode *opt = convert;
3364
3365             while ( ++opt < optimize) {
3366                 Set_Node_Offset_Length(opt,0,0);
3367             }
3368             /*
3369                 Try to clean up some of the debris left after the
3370                 optimisation.
3371              */
3372             while( optimize < jumper ) {
3373                 mjd_nodelen += Node_Length((optimize));
3374                 OP( optimize ) = OPTIMIZED;
3375                 Set_Node_Offset_Length(optimize,0,0);
3376                 optimize++;
3377             }
3378             Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
3379         });
3380     } /* end node insert */
3381
3382     /*  Finish populating the prev field of the wordinfo array.  Walk back
3383      *  from each accept state until we find another accept state, and if
3384      *  so, point the first word's .prev field at the second word. If the
3385      *  second already has a .prev field set, stop now. This will be the
3386      *  case either if we've already processed that word's accept state,
3387      *  or that state had multiple words, and the overspill words were
3388      *  already linked up earlier.
3389      */
3390     {
3391         U16 word;
3392         U32 state;
3393         U16 prev;
3394
3395         for (word=1; word <= trie->wordcount; word++) {
3396             prev = 0;
3397             if (trie->wordinfo[word].prev)
3398                 continue;
3399             state = trie->wordinfo[word].accept;
3400             while (state) {
3401                 state = prev_states[state];
3402                 if (!state)
3403                     break;
3404                 prev = trie->states[state].wordnum;
3405                 if (prev)
3406                     break;
3407             }
3408             trie->wordinfo[word].prev = prev;
3409         }
3410         Safefree(prev_states);
3411     }
3412
3413
3414     /* and now dump out the compressed format */
3415     DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3416
3417     RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3418 #ifdef DEBUGGING
3419     RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3420     RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3421 #else
3422     SvREFCNT_dec_NN(revcharmap);
3423 #endif
3424     return trie->jump
3425            ? MADE_JUMP_TRIE
3426            : trie->startstate>1
3427              ? MADE_EXACT_TRIE
3428              : MADE_TRIE;
3429 }
3430
3431 STATIC regnode *
3432 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3433 {
3434 /* The Trie is constructed and compressed now so we can build a fail array if
3435  * it's needed
3436
3437    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3438    3.32 in the
3439    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3440    Ullman 1985/88
3441    ISBN 0-201-10088-6
3442
3443    We find the fail state for each state in the trie, this state is the longest
3444    proper suffix of the current state's 'word' that is also a proper prefix of
3445    another word in our trie. State 1 represents the word '' and is thus the
3446    default fail state. This allows the DFA not to have to restart after its
3447    tried and failed a word at a given point, it simply continues as though it
3448    had been matching the other word in the first place.
3449    Consider
3450       'abcdgu'=~/abcdefg|cdgu/
3451    When we get to 'd' we are still matching the first word, we would encounter
3452    'g' which would fail, which would bring us to the state representing 'd' in
3453    the second word where we would try 'g' and succeed, proceeding to match
3454    'cdgu'.
3455  */
3456  /* add a fail transition */
3457     const U32 trie_offset = ARG(source);
3458     reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3459     U32 *q;
3460     const U32 ucharcount = trie->uniquecharcount;
3461     const U32 numstates = trie->statecount;
3462     const U32 ubound = trie->lasttrans + ucharcount;
3463     U32 q_read = 0;
3464     U32 q_write = 0;
3465     U32 charid;
3466     U32 base = trie->states[ 1 ].trans.base;
3467     U32 *fail;
3468     reg_ac_data *aho;
3469     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3470     regnode *stclass;
3471     GET_RE_DEBUG_FLAGS_DECL;
3472
3473     PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3474     PERL_UNUSED_CONTEXT;
3475 #ifndef DEBUGGING
3476     PERL_UNUSED_ARG(depth);
3477 #endif
3478
3479     if ( OP(source) == TRIE ) {
3480         struct regnode_1 *op = (struct regnode_1 *)
3481             PerlMemShared_calloc(1, sizeof(struct regnode_1));
3482         StructCopy(source,op,struct regnode_1);
3483         stclass = (regnode *)op;
3484     } else {
3485         struct regnode_charclass *op = (struct regnode_charclass *)
3486             PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3487         StructCopy(source,op,struct regnode_charclass);
3488         stclass = (regnode *)op;
3489     }
3490     OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3491
3492     ARG_SET( stclass, data_slot );
3493     aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3494     RExC_rxi->data->data[ data_slot ] = (void*)aho;
3495     aho->trie=trie_offset;
3496     aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3497     Copy( trie->states, aho->states, numstates, reg_trie_state );
3498     Newxz( q, numstates, U32);
3499     aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3500     aho->refcount = 1;
3501     fail = aho->fail;
3502     /* initialize fail[0..1] to be 1 so that we always have
3503        a valid final fail state */
3504     fail[ 0 ] = fail[ 1 ] = 1;
3505
3506     for ( charid = 0; charid < ucharcount ; charid++ ) {
3507         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3508         if ( newstate ) {
3509             q[ q_write ] = newstate;
3510             /* set to point at the root */
3511             fail[ q[ q_write++ ] ]=1;
3512         }
3513     }
3514     while ( q_read < q_write) {
3515         const U32 cur = q[ q_read++ % numstates ];
3516         base = trie->states[ cur ].trans.base;
3517
3518         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3519             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3520             if (ch_state) {
3521                 U32 fail_state = cur;
3522                 U32 fail_base;
3523                 do {
3524                     fail_state = fail[ fail_state ];
3525                     fail_base = aho->states[ fail_state ].trans.base;
3526                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3527
3528                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3529                 fail[ ch_state ] = fail_state;
3530                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3531                 {
3532                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
3533                 }
3534                 q[ q_write++ % numstates] = ch_state;
3535             }
3536         }
3537     }
3538     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3539        when we fail in state 1, this allows us to use the
3540        charclass scan to find a valid start char. This is based on the principle
3541        that theres a good chance the string being searched contains lots of stuff
3542        that cant be a start char.
3543      */
3544     fail[ 0 ] = fail[ 1 ] = 0;
3545     DEBUG_TRIE_COMPILE_r({
3546         PerlIO_printf(Perl_debug_log,
3547                       "%*sStclass Failtable (%"UVuf" states): 0",
3548                       (int)(depth * 2), "", (UV)numstates
3549         );
3550         for( q_read=1; q_read<numstates; q_read++ ) {
3551             PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
3552         }
3553         PerlIO_printf(Perl_debug_log, "\n");
3554     });
3555     Safefree(q);
3556     /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3557     return stclass;
3558 }
3559
3560
3561 #define DEBUG_PEEP(str,scan,depth) \
3562     DEBUG_OPTIMISE_r({if (scan){ \
3563        regnode *Next = regnext(scan); \
3564        regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state); \
3565        PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)", \
3566            (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),\
3567            Next ? (REG_NODE_NUM(Next)) : 0 ); \
3568        DEBUG_SHOW_STUDY_FLAGS(flags," [ ","]");\
3569        PerlIO_printf(Perl_debug_log, "\n"); \
3570    }});
3571
3572 /* The below joins as many adjacent EXACTish nodes as possible into a single
3573  * one.  The regop may be changed if the node(s) contain certain sequences that
3574  * require special handling.  The joining is only done if:
3575  * 1) there is room in the current conglomerated node to entirely contain the
3576  *    next one.
3577  * 2) they are the exact same node type
3578  *
3579  * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3580  * these get optimized out
3581  *
3582  * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3583  * as possible, even if that means splitting an existing node so that its first
3584  * part is moved to the preceeding node.  This would maximise the efficiency of
3585  * memEQ during matching.  Elsewhere in this file, khw proposes splitting
3586  * EXACTFish nodes into portions that don't change under folding vs those that
3587  * do.  Those portions that don't change may be the only things in the pattern that
3588  * could be used to find fixed and floating strings.
3589  *
3590  * If a node is to match under /i (folded), the number of characters it matches
3591  * can be different than its character length if it contains a multi-character
3592  * fold.  *min_subtract is set to the total delta number of characters of the
3593  * input nodes.
3594  *
3595  * And *unfolded_multi_char is set to indicate whether or not the node contains
3596  * an unfolded multi-char fold.  This happens when whether the fold is valid or
3597  * not won't be known until runtime; namely for EXACTF nodes that contain LATIN
3598  * SMALL LETTER SHARP S, as only if the target string being matched against
3599  * turns out to be UTF-8 is that fold valid; and also for EXACTFL nodes whose
3600  * folding rules depend on the locale in force at runtime.  (Multi-char folds
3601  * whose components are all above the Latin1 range are not run-time locale
3602  * dependent, and have already been folded by the time this function is
3603  * called.)
3604  *
3605  * This is as good a place as any to discuss the design of handling these
3606  * multi-character fold sequences.  It's been wrong in Perl for a very long
3607  * time.  There are three code points in Unicode whose multi-character folds
3608  * were long ago discovered to mess things up.  The previous designs for
3609  * dealing with these involved assigning a special node for them.  This
3610  * approach doesn't always work, as evidenced by this example:
3611  *      "\xDFs" =~ /s\xDF/ui    # Used to fail before these patches
3612  * Both sides fold to "sss", but if the pattern is parsed to create a node that
3613  * would match just the \xDF, it won't be able to handle the case where a
3614  * successful match would have to cross the node's boundary.  The new approach
3615  * that hopefully generally solves the problem generates an EXACTFU_SS node
3616  * that is "sss" in this case.
3617  *
3618  * It turns out that there are problems with all multi-character folds, and not
3619  * just these three.  Now the code is general, for all such cases.  The
3620  * approach taken is:
3621  * 1)   This routine examines each EXACTFish node that could contain multi-
3622  *      character folded sequences.  Since a single character can fold into
3623  *      such a sequence, the minimum match length for this node is less than
3624  *      the number of characters in the node.  This routine returns in
3625  *      *min_subtract how many characters to subtract from the the actual
3626  *      length of the string to get a real minimum match length; it is 0 if
3627  *      there are no multi-char foldeds.  This delta is used by the caller to
3628  *      adjust the min length of the match, and the delta between min and max,
3629  *      so that the optimizer doesn't reject these possibilities based on size
3630  *      constraints.
3631  * 2)   For the sequence involving the Sharp s (\xDF), the node type EXACTFU_SS
3632  *      is used for an EXACTFU node that contains at least one "ss" sequence in
3633  *      it.  For non-UTF-8 patterns and strings, this is the only case where
3634  *      there is a possible fold length change.  That means that a regular
3635  *      EXACTFU node without UTF-8 involvement doesn't have to concern itself
3636  *      with length changes, and so can be processed faster.  regexec.c takes
3637  *      advantage of this.  Generally, an EXACTFish node that is in UTF-8 is
3638  *      pre-folded by regcomp.c (except EXACTFL, some of whose folds aren't
3639  *      known until runtime).  This saves effort in regex matching.  However,
3640  *      the pre-folding isn't done for non-UTF8 patterns because the fold of
3641  *      the MICRO SIGN requires UTF-8, and we don't want to slow things down by
3642  *      forcing the pattern into UTF8 unless necessary.  Also what EXACTF (and,
3643  *      again, EXACTFL) nodes fold to isn't known until runtime.  The fold
3644  *      possibilities for the non-UTF8 patterns are quite simple, except for
3645  *      the sharp s.  All the ones that don't involve a UTF-8 target string are
3646  *      members of a fold-pair, and arrays are set up for all of them so that
3647  *      the other member of the pair can be found quickly.  Code elsewhere in
3648  *      this file makes sure that in EXACTFU nodes, the sharp s gets folded to
3649  *      'ss', even if the pattern isn't UTF-8.  This avoids the issues
3650  *      described in the next item.
3651  * 3)   A problem remains for unfolded multi-char folds. (These occur when the
3652  *      validity of the fold won't be known until runtime, and so must remain
3653  *      unfolded for now.  This happens for the sharp s in EXACTF and EXACTFA
3654  *      nodes when the pattern isn't in UTF-8.  (Note, BTW, that there cannot
3655  *      be an EXACTF node with a UTF-8 pattern.)  They also occur for various
3656  *      folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3657  *      The reason this is a problem is that the optimizer part of regexec.c
3658  *      (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3659  *      that a character in the pattern corresponds to at most a single
3660  *      character in the target string.  (And I do mean character, and not byte
3661  *      here, unlike other parts of the documentation that have never been
3662  *      updated to account for multibyte Unicode.)  sharp s in EXACTF and
3663  *      EXACTFL nodes can match the two character string 'ss'; in EXACTFA nodes
3664  *      it can match "\x{17F}\x{17F}".  These, along with other ones in EXACTFL
3665  *      nodes, violate the assumption, and they are the only instances where it
3666  *      is violated.  I'm reluctant to try to change the assumption, as the
3667  *      code involved is impenetrable to me (khw), so instead the code here
3668  *      punts.  This routine examines EXACTFL nodes, and (when the pattern
3669  *      isn't UTF-8) EXACTF and EXACTFA for such unfolded folds, and returns a
3670  *      boolean indicating whether or not the node contains such a fold.  When
3671  *      it is true, the caller sets a flag that later causes the optimizer in
3672  *      this file to not set values for the floating and fixed string lengths,
3673  *      and thus avoids the optimizer code in regexec.c that makes the invalid
3674  *      assumption.  Thus, there is no optimization based on string lengths for
3675  *      EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3676  *      EXACTF and EXACTFA nodes that contain the sharp s.  (The reason the
3677  *      assumption is wrong only in these cases is that all other non-UTF-8
3678  *      folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3679  *      their expanded versions.  (Again, we can't prefold sharp s to 'ss' in
3680  *      EXACTF nodes because we don't know at compile time if it actually
3681  *      matches 'ss' or not.  For EXACTF nodes it will match iff the target
3682  *      string is in UTF-8.  This is in contrast to EXACTFU nodes, where it
3683  *      always matches; and EXACTFA where it never does.  In an EXACTFA node in
3684  *      a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3685  *      problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3686  *      string would require the pattern to be forced into UTF-8, the overhead
3687  *      of which we want to avoid.  Similarly the unfolded multi-char folds in
3688  *      EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3689  *      locale.)
3690  *
3691  *      Similarly, the code that generates tries doesn't currently handle
3692  *      not-already-folded multi-char folds, and it looks like a pain to change
3693  *      that.  Therefore, trie generation of EXACTFA nodes with the sharp s
3694  *      doesn't work.  Instead, such an EXACTFA is turned into a new regnode,
3695  *      EXACTFA_NO_TRIE, which the trie code knows not to handle.  Most people
3696  *      using /iaa matching will be doing so almost entirely with ASCII
3697  *      strings, so this should rarely be encountered in practice */
3698
3699 #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
3700     if (PL_regkind[OP(scan)] == EXACT) \
3701         join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags),NULL,depth+1)
3702
3703 STATIC U32
3704 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
3705                    UV *min_subtract, bool *unfolded_multi_char,
3706                    U32 flags,regnode *val, U32 depth)
3707 {
3708     /* Merge several consecutive EXACTish nodes into one. */
3709     regnode *n = regnext(scan);
3710     U32 stringok = 1;
3711     regnode *next = scan + NODE_SZ_STR(scan);
3712     U32 merged = 0;
3713     U32 stopnow = 0;
3714 #ifdef DEBUGGING
3715     regnode *stop = scan;
3716     GET_RE_DEBUG_FLAGS_DECL;
3717 #else
3718     PERL_UNUSED_ARG(depth);
3719 #endif
3720
3721     PERL_ARGS_ASSERT_JOIN_EXACT;
3722 #ifndef EXPERIMENTAL_INPLACESCAN
3723     PERL_UNUSED_ARG(flags);
3724     PERL_UNUSED_ARG(val);
3725 #endif
3726     DEBUG_PEEP("join",scan,depth);
3727
3728     /* Look through the subsequent nodes in the chain.  Skip NOTHING, merge
3729      * EXACT ones that are mergeable to the current one. */
3730     while (n
3731            && (PL_regkind[OP(n)] == NOTHING
3732                || (stringok && OP(n) == OP(scan)))
3733            && NEXT_OFF(n)
3734            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
3735     {
3736
3737         if (OP(n) == TAIL || n > next)
3738             stringok = 0;
3739         if (PL_regkind[OP(n)] == NOTHING) {
3740             DEBUG_PEEP("skip:",n,depth);
3741             NEXT_OFF(scan) += NEXT_OFF(n);
3742             next = n + NODE_STEP_REGNODE;
3743 #ifdef DEBUGGING
3744             if (stringok)
3745                 stop = n;
3746 #endif
3747             n = regnext(n);
3748         }
3749         else if (stringok) {
3750             const unsigned int oldl = STR_LEN(scan);
3751             regnode * const nnext = regnext(n);
3752
3753             /* XXX I (khw) kind of doubt that this works on platforms (should
3754              * Perl ever run on one) where U8_MAX is above 255 because of lots
3755              * of other assumptions */
3756             /* Don't join if the sum can't fit into a single node */
3757             if (oldl + STR_LEN(n) > U8_MAX)
3758                 break;
3759
3760             DEBUG_PEEP("merg",n,depth);
3761             merged++;
3762
3763             NEXT_OFF(scan) += NEXT_OFF(n);
3764             STR_LEN(scan) += STR_LEN(n);
3765             next = n + NODE_SZ_STR(n);
3766             /* Now we can overwrite *n : */
3767             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
3768 #ifdef DEBUGGING
3769             stop = next - 1;
3770 #endif
3771             n = nnext;
3772             if (stopnow) break;
3773         }
3774
3775 #ifdef EXPERIMENTAL_INPLACESCAN
3776         if (flags && !NEXT_OFF(n)) {
3777             DEBUG_PEEP("atch", val, depth);
3778             if (reg_off_by_arg[OP(n)]) {
3779                 ARG_SET(n, val - n);
3780             }
3781             else {
3782                 NEXT_OFF(n) = val - n;
3783             }
3784             stopnow = 1;
3785         }
3786 #endif
3787     }
3788
3789     *min_subtract = 0;
3790     *unfolded_multi_char = FALSE;
3791
3792     /* Here, all the adjacent mergeable EXACTish nodes have been merged.  We
3793      * can now analyze for sequences of problematic code points.  (Prior to
3794      * this final joining, sequences could have been split over boundaries, and
3795      * hence missed).  The sequences only happen in folding, hence for any
3796      * non-EXACT EXACTish node */
3797     if (OP(scan) != EXACT && OP(scan) != EXACTL) {
3798         U8* s0 = (U8*) STRING(scan);
3799         U8* s = s0;
3800         U8* s_end = s0 + STR_LEN(scan);
3801
3802         int total_count_delta = 0;  /* Total delta number of characters that
3803                                        multi-char folds expand to */
3804
3805         /* One pass is made over the node's string looking for all the
3806          * possibilities.  To avoid some tests in the loop, there are two main
3807          * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
3808          * non-UTF-8 */
3809         if (UTF) {
3810             U8* folded = NULL;
3811
3812             if (OP(scan) == EXACTFL) {
3813                 U8 *d;
3814
3815                 /* An EXACTFL node would already have been changed to another
3816                  * node type unless there is at least one character in it that
3817                  * is problematic; likely a character whose fold definition
3818                  * won't be known until runtime, and so has yet to be folded.
3819                  * For all but the UTF-8 locale, folds are 1-1 in length, but
3820                  * to handle the UTF-8 case, we need to create a temporary
3821                  * folded copy using UTF-8 locale rules in order to analyze it.
3822                  * This is because our macros that look to see if a sequence is
3823                  * a multi-char fold assume everything is folded (otherwise the
3824                  * tests in those macros would be too complicated and slow).
3825                  * Note that here, the non-problematic folds will have already
3826                  * been done, so we can just copy such characters.  We actually
3827                  * don't completely fold the EXACTFL string.  We skip the
3828                  * unfolded multi-char folds, as that would just create work
3829                  * below to figure out the size they already are */
3830
3831                 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
3832                 d = folded;
3833                 while (s < s_end) {
3834                     STRLEN s_len = UTF8SKIP(s);
3835                     if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
3836                         Copy(s, d, s_len, U8);
3837                         d += s_len;
3838                     }
3839                     else if (is_FOLDS_TO_MULTI_utf8(s)) {
3840                         *unfolded_multi_char = TRUE;
3841                         Copy(s, d, s_len, U8);
3842                         d += s_len;
3843                     }
3844                     else if (isASCII(*s)) {
3845                         *(d++) = toFOLD(*s);
3846                     }
3847                     else {
3848                         STRLEN len;
3849                         _to_utf8_fold_flags(s, d, &len, FOLD_FLAGS_FULL);
3850                         d += len;
3851                     }
3852                     s += s_len;
3853                 }
3854
3855                 /* Point the remainder of the routine to look at our temporary
3856                  * folded copy */
3857                 s = folded;
3858                 s_end = d;
3859             } /* End of creating folded copy of EXACTFL string */
3860
3861             /* Examine the string for a multi-character fold sequence.  UTF-8
3862              * patterns have all characters pre-folded by the time this code is
3863              * executed */
3864             while (s < s_end - 1) /* Can stop 1 before the end, as minimum
3865                                      length sequence we are looking for is 2 */
3866             {
3867                 int count = 0;  /* How many characters in a multi-char fold */
3868                 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
3869                 if (! len) {    /* Not a multi-char fold: get next char */
3870                     s += UTF8SKIP(s);
3871                     continue;
3872                 }
3873
3874                 /* Nodes with 'ss' require special handling, except for
3875                  * EXACTFA-ish for which there is no multi-char fold to this */
3876                 if (len == 2 && *s == 's' && *(s+1) == 's'
3877                     && OP(scan) != EXACTFA
3878                     && OP(scan) != EXACTFA_NO_TRIE)
3879                 {
3880                     count = 2;
3881                     if (OP(scan) != EXACTFL) {
3882                         OP(scan) = EXACTFU_SS;
3883                     }
3884                     s += 2;
3885                 }
3886                 else { /* Here is a generic multi-char fold. */
3887                     U8* multi_end  = s + len;
3888
3889                     /* Count how many characters are in it.  In the case of
3890                      * /aa, no folds which contain ASCII code points are
3891                      * allowed, so check for those, and skip if found. */
3892                     if (OP(scan) != EXACTFA && OP(scan) != EXACTFA_NO_TRIE) {
3893                         count = utf8_length(s, multi_end);
3894                         s = multi_end;
3895                     }
3896                     else {
3897                         while (s < multi_end) {
3898                             if (isASCII(*s)) {
3899                                 s++;
3900                                 goto next_iteration;
3901                             }
3902                             else {
3903                                 s += UTF8SKIP(s);
3904                             }
3905                             count++;
3906                         }
3907                     }
3908                 }
3909
3910                 /* The delta is how long the sequence is minus 1 (1 is how long
3911                  * the character that folds to the sequence is) */
3912                 total_count_delta += count - 1;
3913               next_iteration: ;
3914             }
3915
3916             /* We created a temporary folded copy of the string in EXACTFL
3917              * nodes.  Therefore we need to be sure it doesn't go below zero,
3918              * as the real string could be shorter */
3919             if (OP(scan) == EXACTFL) {
3920                 int total_chars = utf8_length((U8*) STRING(scan),
3921                                            (U8*) STRING(scan) + STR_LEN(scan));
3922                 if (total_count_delta > total_chars) {
3923                     total_count_delta = total_chars;
3924                 }
3925             }
3926
3927             *min_subtract += total_count_delta;
3928             Safefree(folded);
3929         }
3930         else if (OP(scan) == EXACTFA) {
3931
3932             /* Non-UTF-8 pattern, EXACTFA node.  There can't be a multi-char
3933              * fold to the ASCII range (and there are no existing ones in the
3934              * upper latin1 range).  But, as outlined in the comments preceding
3935              * this function, we need to flag any occurrences of the sharp s.
3936              * This character forbids trie formation (because of added
3937              * complexity) */
3938 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
3939    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
3940                                       || UNICODE_DOT_DOT_VERSION > 0)
3941             while (s < s_end) {
3942                 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
3943                     OP(scan) = EXACTFA_NO_TRIE;
3944                     *unfolded_multi_char = TRUE;
3945                     break;
3946                 }
3947                 s++;
3948             }
3949         }
3950         else {
3951
3952             /* Non-UTF-8 pattern, not EXACTFA node.  Look for the multi-char
3953              * folds that are all Latin1.  As explained in the comments
3954              * preceding this function, we look also for the sharp s in EXACTF
3955              * and EXACTFL nodes; it can be in the final position.  Otherwise
3956              * we can stop looking 1 byte earlier because have to find at least
3957              * two characters for a multi-fold */
3958             const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
3959                               ? s_end
3960                               : s_end -1;
3961
3962             while (s < upper) {
3963                 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
3964                 if (! len) {    /* Not a multi-char fold. */
3965                     if (*s == LATIN_SMALL_LETTER_SHARP_S
3966                         && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
3967                     {
3968                         *unfolded_multi_char = TRUE;
3969                     }
3970                     s++;
3971                     continue;
3972                 }
3973
3974             &nb