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