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