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