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